blob: 12ffe75436cfd5c832b70ba4237e131b8e44145f [file] [log] [blame]
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001#include <sys/socket.h>
2
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01006#include <lauxlib.h>
7#include <lua.h>
8#include <lualib.h>
9
Thierry FOURNIER463119c2015-03-10 00:35:36 +010010#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
11#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010012#endif
13
Thierry FOURNIER380d0932015-01-23 14:27:52 +010014#include <ebpttree.h>
15
16#include <common/cfgparse.h>
17
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010018#include <types/connection.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010019#include <types/hlua.h>
20#include <types/proxy.h>
21
Thierry FOURNIER55da1652015-01-23 11:36:30 +010022#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020023#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010024#include <proto/channel.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010025#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010026#include <proto/hlua.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020027#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010028#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010029#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010030#include <proto/payload.h>
31#include <proto/proto_http.h>
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010032#include <proto/proto_tcp.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010033#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010034#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010035#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020036#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020037#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010038#include <proto/ssl_sock.h>
39#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010040#include <proto/task.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020041#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010042
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010043/* Lua uses longjmp to perform yield or throwing errors. This
44 * macro is used only for identifying the function that can
45 * not return because a longjmp is executed.
46 * __LJMP marks a prototype of hlua file that can use longjmp.
47 * WILL_LJMP() marks an lua function that will use longjmp.
48 * MAY_LJMP() marks an lua function that may use longjmp.
49 */
50#define __LJMP
51#define WILL_LJMP(func) func
52#define MAY_LJMP(func) func
53
Thierry FOURNIERbabae282015-09-17 11:36:37 +020054/* This couple of function executes securely some Lua calls outside of
55 * the lua runtime environment. Each Lua call can return a longjmp
56 * if it encounter a memory error.
57 *
58 * Lua documentation extract:
59 *
60 * If an error happens outside any protected environment, Lua calls
61 * a panic function (see lua_atpanic) and then calls abort, thus
62 * exiting the host application. Your panic function can avoid this
63 * exit by never returning (e.g., doing a long jump to your own
64 * recovery point outside Lua).
65 *
66 * The panic function runs as if it were a message handler (see
67 * §2.3); in particular, the error message is at the top of the
68 * stack. However, there is no guarantee about stack space. To push
69 * anything on the stack, the panic function must first check the
70 * available space (see §4.2).
71 *
72 * We must check all the Lua entry point. This includes:
73 * - The include/proto/hlua.h exported functions
74 * - the task wrapper function
75 * - The action wrapper function
76 * - The converters wrapper function
77 * - The sample-fetch wrapper functions
78 *
79 * It is tolerated that the initilisation function returns an abort.
80 * Before each Lua abort, an error message is writed on stderr.
81 *
82 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
83 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
84 * because they must be exists in the program stack when the longjmp
85 * is called.
86 */
87jmp_buf safe_ljmp_env;
88static int hlua_panic_safe(lua_State *L) { return 0; }
89static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
90
91#define SET_SAFE_LJMP(__L) \
92 ({ \
93 int ret; \
94 if (setjmp(safe_ljmp_env) != 0) { \
95 lua_atpanic(__L, hlua_panic_safe); \
96 ret = 0; \
97 } else { \
98 lua_atpanic(__L, hlua_panic_ljmp); \
99 ret = 1; \
100 } \
101 ret; \
102 })
103
104/* If we are the last function catching Lua errors, we
105 * must reset the panic function.
106 */
107#define RESET_SAFE_LJMP(__L) \
108 do { \
109 lua_atpanic(__L, hlua_panic_safe); \
110 } while(0)
111
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200112/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200113#define APPLET_DONE 0x01 /* applet processing is done. */
114#define APPLET_100C 0x02 /* 100 continue expected. */
115#define APPLET_HDR_SENT 0x04 /* Response header sent. */
116#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
117#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
118
119#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200120
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100121/* The main Lua execution context. */
122struct hlua gL;
123
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100124/* This is the memory pool containing all the signal structs. These
125 * struct are used to store each requiered signal between two tasks.
126 */
127struct pool_head *pool2_hlua_com;
128
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100129/* Used for Socket connection. */
130static struct proxy socket_proxy;
131static struct server socket_tcp;
132#ifdef USE_OPENSSL
133static struct server socket_ssl;
134#endif
135
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100136/* List head of the function called at the initialisation time. */
137struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
138
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100139/* The following variables contains the reference of the different
140 * Lua classes. These references are useful for identify metadata
141 * associated with an object.
142 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100143static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100144static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100145static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100146static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100147static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100148static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200149static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200150static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200151static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100152
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100153/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200154 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100155 * short timeout. Lua linked with tasks doesn't have a timeout
156 * because a task may remain alive during all the haproxy execution.
157 */
158static unsigned int hlua_timeout_session = 4000; /* session timeout. */
159static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200160static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100161
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100162/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
163 * it is used for preventing infinite loops.
164 *
165 * I test the scheer with an infinite loop containing one incrementation
166 * and one test. I run this loop between 10 seconds, I raise a ceil of
167 * 710M loops from one interrupt each 9000 instructions, so I fix the value
168 * to one interrupt each 10 000 instructions.
169 *
170 * configured | Number of
171 * instructions | loops executed
172 * between two | in milions
173 * forced yields |
174 * ---------------+---------------
175 * 10 | 160
176 * 500 | 670
177 * 1000 | 680
178 * 5000 | 700
179 * 7000 | 700
180 * 8000 | 700
181 * 9000 | 710 <- ceil
182 * 10000 | 710
183 * 100000 | 710
184 * 1000000 | 710
185 *
186 */
187static unsigned int hlua_nb_instruction = 10000;
188
Willy Tarreau32f61e22015-03-18 17:54:59 +0100189/* Descriptor for the memory allocation state. If limit is not null, it will
190 * be enforced on any memory allocation.
191 */
192struct hlua_mem_allocator {
193 size_t allocated;
194 size_t limit;
195};
196
197static struct hlua_mem_allocator hlua_global_allocator;
198
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200199static const char error_500[] =
200 "HTTP/1.0 500 Server Error\r\n"
201 "Cache-Control: no-cache\r\n"
202 "Connection: close\r\n"
203 "Content-Type: text/html\r\n"
204 "\r\n"
205 "<html><body><h1>500 Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
206
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100207/* These functions converts types between HAProxy internal args or
208 * sample and LUA types. Another function permits to check if the
209 * LUA stack contains arguments according with an required ARG_T
210 * format.
211 */
212static int hlua_arg2lua(lua_State *L, const struct arg *arg);
213static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100214__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
215 unsigned int mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100216static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100217static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100218static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
219
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200220__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
221
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200222#define SEND_ERR(__be, __fmt, __args...) \
223 do { \
224 send_log(__be, LOG_ERR, __fmt, ## __args); \
225 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
226 Alert(__fmt, ## __args); \
227 } while (0)
228
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100229/* Used to check an Lua function type in the stack. It creates and
230 * returns a reference of the function. This function throws an
231 * error if the rgument is not a "function".
232 */
233__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
234{
235 if (!lua_isfunction(L, argno)) {
236 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
237 WILL_LJMP(luaL_argerror(L, argno, msg));
238 }
239 lua_pushvalue(L, argno);
240 return luaL_ref(L, LUA_REGISTRYINDEX);
241}
242
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200243/* Return the string that is of the top of the stack. */
244const char *hlua_get_top_error_string(lua_State *L)
245{
246 if (lua_gettop(L) < 1)
247 return "unknown error";
248 if (lua_type(L, -1) != LUA_TSTRING)
249 return "unknown error";
250 return lua_tostring(L, -1);
251}
252
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100253/* The three following functions are useful for adding entries
254 * in a table. These functions takes a string and respectively an
255 * integer, a string or a function and add it to the table in the
256 * top of the stack.
257 *
258 * These functions throws an error if no more stack size is
259 * available.
260 */
261__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100262 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100263{
264 if (!lua_checkstack(L, 2))
265 WILL_LJMP(luaL_error(L, "full stack"));
266 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100267 lua_pushinteger(L, value);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200268 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100269}
270__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
271 const char *value)
272{
273 if (!lua_checkstack(L, 2))
274 WILL_LJMP(luaL_error(L, "full stack"));
275 lua_pushstring(L, name);
276 lua_pushstring(L, value);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200277 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100278}
279__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
280 int (*function)(lua_State *L))
281{
282 if (!lua_checkstack(L, 2))
283 WILL_LJMP(luaL_error(L, "full stack"));
284 lua_pushstring(L, name);
285 lua_pushcclosure(L, function, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200286 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100287}
288
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +0200289__LJMP static int hlua_dump_object(struct lua_State *L)
290{
291 const char *name = (const char *)lua_tostring(L, lua_upvalueindex(1));
292 lua_pushfstring(L, "HAProxy class %s", name);
293 return 1;
294}
295
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100296/* This function check the number of arguments available in the
297 * stack. If the number of arguments available is not the same
298 * then <nb> an error is throwed.
299 */
300__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
301{
302 if (lua_gettop(L) == nb)
303 return;
304 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
305}
306
307/* Return true if the data in stack[<ud>] is an object of
308 * type <class_ref>.
309 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100310static int hlua_metaistype(lua_State *L, int ud, int class_ref)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100311{
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100312 if (!lua_getmetatable(L, ud))
313 return 0;
314
315 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
316 if (!lua_rawequal(L, -1, -2)) {
317 lua_pop(L, 2);
318 return 0;
319 }
320
321 lua_pop(L, 2);
322 return 1;
323}
324
325/* Return an object of the expected type, or throws an error. */
326__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
327{
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100328 void *p;
329
330 /* Check if the stack entry is an array. */
331 if (!lua_istable(L, ud))
332 WILL_LJMP(luaL_argerror(L, ud, NULL));
333 /* Check if the metadata have the expected type. */
334 if (!hlua_metaistype(L, ud, class_ref))
335 WILL_LJMP(luaL_argerror(L, ud, NULL));
336 /* Push on the stack at the entry [0] of the table. */
337 lua_rawgeti(L, ud, 0);
338 /* Check if this entry is userdata. */
339 p = lua_touserdata(L, -1);
340 if (!p)
341 WILL_LJMP(luaL_argerror(L, ud, NULL));
342 /* Remove the entry returned by lua_rawgeti(). */
343 lua_pop(L, 1);
344 /* Return the associated struct. */
345 return p;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100346}
347
348/* This fucntion push an error string prefixed by the file name
349 * and the line number where the error is encountered.
350 */
351static int hlua_pusherror(lua_State *L, const char *fmt, ...)
352{
353 va_list argp;
354 va_start(argp, fmt);
355 luaL_where(L, 1);
356 lua_pushvfstring(L, fmt, argp);
357 va_end(argp);
358 lua_concat(L, 2);
359 return 1;
360}
361
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100362/* This function register a new signal. "lua" is the current lua
363 * execution context. It contains a pointer to the associated task.
364 * "link" is a list head attached to an other task that must be wake
365 * the lua task if an event occurs. This is useful with external
366 * events like TCP I/O or sleep functions. This funcion allocate
367 * memory for the signal.
368 */
369static int hlua_com_new(struct hlua *lua, struct list *link)
370{
371 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
372 if (!com)
373 return 0;
374 LIST_ADDQ(&lua->com, &com->purge_me);
375 LIST_ADDQ(link, &com->wake_me);
376 com->task = lua->task;
377 return 1;
378}
379
380/* This function purge all the pending signals when the LUA execution
381 * is finished. This prevent than a coprocess try to wake a deleted
382 * task. This function remove the memory associated to the signal.
383 */
384static void hlua_com_purge(struct hlua *lua)
385{
386 struct hlua_com *com, *back;
387
388 /* Delete all pending communication signals. */
389 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
390 LIST_DEL(&com->purge_me);
391 LIST_DEL(&com->wake_me);
392 pool_free2(pool2_hlua_com, com);
393 }
394}
395
396/* This function sends signals. It wakes all the tasks attached
397 * to a list head, and remove the signal, and free the used
398 * memory.
399 */
400static void hlua_com_wake(struct list *wake)
401{
402 struct hlua_com *com, *back;
403
404 /* Wake task and delete all pending communication signals. */
405 list_for_each_entry_safe(com, back, wake, wake_me) {
406 LIST_DEL(&com->purge_me);
407 LIST_DEL(&com->wake_me);
408 task_wakeup(com->task, TASK_WOKEN_MSG);
409 pool_free2(pool2_hlua_com, com);
410 }
411}
412
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100413/* This functions is used with sample fetch and converters. It
414 * converts the HAProxy configuration argument in a lua stack
415 * values.
416 *
417 * It takes an array of "arg", and each entry of the array is
418 * converted and pushed in the LUA stack.
419 */
420static int hlua_arg2lua(lua_State *L, const struct arg *arg)
421{
422 switch (arg->type) {
423 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100424 case ARGT_TIME:
425 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100426 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100427 break;
428
429 case ARGT_STR:
430 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
431 break;
432
433 case ARGT_IPV4:
434 case ARGT_IPV6:
435 case ARGT_MSK4:
436 case ARGT_MSK6:
437 case ARGT_FE:
438 case ARGT_BE:
439 case ARGT_TAB:
440 case ARGT_SRV:
441 case ARGT_USR:
442 case ARGT_MAP:
443 default:
444 lua_pushnil(L);
445 break;
446 }
447 return 1;
448}
449
450/* This function take one entrie in an LUA stack at the index "ud",
451 * and try to convert it in an HAProxy argument entry. This is useful
452 * with sample fetch wrappers. The input arguments are gived to the
453 * lua wrapper and converted as arg list by thi function.
454 */
455static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
456{
457 switch (lua_type(L, ud)) {
458
459 case LUA_TNUMBER:
460 case LUA_TBOOLEAN:
461 arg->type = ARGT_SINT;
462 arg->data.sint = lua_tointeger(L, ud);
463 break;
464
465 case LUA_TSTRING:
466 arg->type = ARGT_STR;
467 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
468 break;
469
470 case LUA_TUSERDATA:
471 case LUA_TNIL:
472 case LUA_TTABLE:
473 case LUA_TFUNCTION:
474 case LUA_TTHREAD:
475 case LUA_TLIGHTUSERDATA:
476 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200477 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100478 break;
479 }
480 return 1;
481}
482
483/* the following functions are used to convert a struct sample
484 * in Lua type. This useful to convert the return of the
485 * fetchs or converters.
486 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100487static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100488{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200489 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100490 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100491 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200492 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100493 break;
494
495 case SMP_T_BIN:
496 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200497 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100498 break;
499
500 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200501 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100502 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
503 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
504 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
505 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
506 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
507 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
508 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
509 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
510 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200511 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100512 break;
513 default:
514 lua_pushnil(L);
515 break;
516 }
517 break;
518
519 case SMP_T_IPV4:
520 case SMP_T_IPV6:
521 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200522 if (sample_casts[smp->data.type][SMP_T_STR] &&
523 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200524 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100525 else
526 lua_pushnil(L);
527 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100528 default:
529 lua_pushnil(L);
530 break;
531 }
532 return 1;
533}
534
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100535/* the following functions are used to convert a struct sample
536 * in Lua strings. This is useful to convert the return of the
537 * fetchs or converters.
538 */
539static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
540{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200541 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100542
543 case SMP_T_BIN:
544 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200545 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100546 break;
547
548 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200549 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100550 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
551 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
552 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
553 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
554 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
555 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
556 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
557 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
558 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200559 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100560 break;
561 default:
562 lua_pushstring(L, "");
563 break;
564 }
565 break;
566
567 case SMP_T_SINT:
568 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100569 case SMP_T_IPV4:
570 case SMP_T_IPV6:
571 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200572 if (sample_casts[smp->data.type][SMP_T_STR] &&
573 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200574 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100575 else
576 lua_pushstring(L, "");
577 break;
578 default:
579 lua_pushstring(L, "");
580 break;
581 }
582 return 1;
583}
584
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100585/* the following functions are used to convert an Lua type in a
586 * struct sample. This is useful to provide data from a converter
587 * to the LUA code.
588 */
589static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
590{
591 switch (lua_type(L, ud)) {
592
593 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200594 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200595 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100596 break;
597
598
599 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200600 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200601 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100602 break;
603
604 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200605 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100606 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200607 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100608 break;
609
610 case LUA_TUSERDATA:
611 case LUA_TNIL:
612 case LUA_TTABLE:
613 case LUA_TFUNCTION:
614 case LUA_TTHREAD:
615 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200616 case LUA_TNONE:
617 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200618 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200619 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100620 break;
621 }
622 return 1;
623}
624
625/* This function check the "argp" builded by another conversion function
626 * is in accord with the expected argp defined by the "mask". The fucntion
627 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100628 *
629 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
630 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100631 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100632__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
633 unsigned int mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100634{
635 int min_arg;
636 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100637 struct proxy *px;
638 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100639
640 idx = 0;
641 min_arg = ARGM(mask);
642 mask >>= ARGM_BITS;
643
644 while (1) {
645
646 /* Check oversize. */
647 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100648 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100649 }
650
651 /* Check for mandatory arguments. */
652 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100653 if (idx < min_arg) {
654
655 /* If miss other argument than the first one, we return an error. */
656 if (idx > 0)
657 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
658
659 /* If first argument have a certain type, some default values
660 * may be used. See the function smp_resolve_args().
661 */
662 switch (mask & ARGT_MASK) {
663
664 case ARGT_FE:
665 if (!(p->cap & PR_CAP_FE))
666 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
667 argp[idx].data.prx = p;
668 argp[idx].type = ARGT_FE;
669 argp[idx+1].type = ARGT_STOP;
670 break;
671
672 case ARGT_BE:
673 if (!(p->cap & PR_CAP_BE))
674 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
675 argp[idx].data.prx = p;
676 argp[idx].type = ARGT_BE;
677 argp[idx+1].type = ARGT_STOP;
678 break;
679
680 case ARGT_TAB:
681 argp[idx].data.prx = p;
682 argp[idx].type = ARGT_TAB;
683 argp[idx+1].type = ARGT_STOP;
684 break;
685
686 default:
687 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
688 break;
689 }
690 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100691 return 0;
692 }
693
694 /* Check for exceed the number of requiered argument. */
695 if ((mask & ARGT_MASK) == ARGT_STOP &&
696 argp[idx].type != ARGT_STOP) {
697 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
698 }
699
700 if ((mask & ARGT_MASK) == ARGT_STOP &&
701 argp[idx].type == ARGT_STOP) {
702 return 0;
703 }
704
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100705 /* Convert some argument types. */
706 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100707 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100708 if (argp[idx].type != ARGT_SINT)
709 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
710 argp[idx].type = ARGT_SINT;
711 break;
712
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100713 case ARGT_TIME:
714 if (argp[idx].type != ARGT_SINT)
715 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200716 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100717 break;
718
719 case ARGT_SIZE:
720 if (argp[idx].type != ARGT_SINT)
721 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200722 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100723 break;
724
725 case ARGT_FE:
726 if (argp[idx].type != ARGT_STR)
727 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
728 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
729 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200730 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100731 if (!argp[idx].data.prx)
732 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
733 argp[idx].type = ARGT_FE;
734 break;
735
736 case ARGT_BE:
737 if (argp[idx].type != ARGT_STR)
738 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
739 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
740 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200741 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100742 if (!argp[idx].data.prx)
743 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
744 argp[idx].type = ARGT_BE;
745 break;
746
747 case ARGT_TAB:
748 if (argp[idx].type != ARGT_STR)
749 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
750 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
751 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200752 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100753 if (!argp[idx].data.prx)
754 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
755 argp[idx].type = ARGT_TAB;
756 break;
757
758 case ARGT_SRV:
759 if (argp[idx].type != ARGT_STR)
760 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
761 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
762 trash.str[argp[idx].data.str.len] = 0;
763 sname = strrchr(trash.str, '/');
764 if (sname) {
765 *sname++ = '\0';
766 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200767 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100768 if (!px)
769 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
770 }
771 else {
772 sname = trash.str;
773 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100774 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100775 argp[idx].data.srv = findserver(px, sname);
776 if (!argp[idx].data.srv)
777 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
778 argp[idx].type = ARGT_SRV;
779 break;
780
781 case ARGT_IPV4:
782 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
783 trash.str[argp[idx].data.str.len] = 0;
784 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
785 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
786 argp[idx].type = ARGT_IPV4;
787 break;
788
789 case ARGT_MSK4:
790 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
791 trash.str[argp[idx].data.str.len] = 0;
792 if (!str2mask(trash.str, &argp[idx].data.ipv4))
793 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
794 argp[idx].type = ARGT_MSK4;
795 break;
796
797 case ARGT_IPV6:
798 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
799 trash.str[argp[idx].data.str.len] = 0;
800 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
801 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
802 argp[idx].type = ARGT_IPV6;
803 break;
804
805 case ARGT_MSK6:
806 case ARGT_MAP:
807 case ARGT_REG:
808 case ARGT_USR:
809 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100810 break;
811 }
812
813 /* Check for type of argument. */
814 if ((mask & ARGT_MASK) != argp[idx].type) {
815 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
816 arg_type_names[(mask & ARGT_MASK)],
817 arg_type_names[argp[idx].type & ARGT_MASK]);
818 WILL_LJMP(luaL_argerror(L, first + idx, msg));
819 }
820
821 /* Next argument. */
822 mask >>= ARGT_BITS;
823 idx++;
824 }
825}
826
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100827/*
828 * The following functions are used to make correspondance between the the
829 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100830 *
831 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100832 * - hlua_sethlua : create the association between hlua context and lua_state.
833 */
834static inline struct hlua *hlua_gethlua(lua_State *L)
835{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100836 struct hlua **hlua = lua_getextraspace(L);
837 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100838}
839static inline void hlua_sethlua(struct hlua *hlua)
840{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100841 struct hlua **hlua_store = lua_getextraspace(hlua->T);
842 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100843}
844
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100845/* This function is used to send logs. It try to send on screen (stderr)
846 * and on the default syslog server.
847 */
848static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
849{
850 struct tm tm;
851 char *p;
852
853 /* Cleanup the log message. */
854 p = trash.str;
855 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200856 if (p >= trash.str + trash.size - 1) {
857 /* Break the message if exceed the buffer size. */
858 *(p-4) = ' ';
859 *(p-3) = '.';
860 *(p-2) = '.';
861 *(p-1) = '.';
862 break;
863 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100864 if (isprint(*msg))
865 *p = *msg;
866 else
867 *p = '.';
868 }
869 *p = '\0';
870
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200871 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100872 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200873 get_localtime(date.tv_sec, &tm);
874 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100875 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
876 (int)getpid(), trash.str);
877 fflush(stderr);
878 }
879}
880
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100881/* This function just ensure that the yield will be always
882 * returned with a timeout and permit to set some flags
883 */
884__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100885 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100886{
887 struct hlua *hlua = hlua_gethlua(L);
888
889 /* Set the wake timeout. If timeout is required, we set
890 * the expiration time.
891 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100892 hlua->wake_time = tick_first(timeout, hlua->expire);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100893
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100894 hlua->flags |= flags;
895
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100896 /* Process the yield. */
897 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
898}
899
Willy Tarreau87b09662015-04-03 00:22:06 +0200900/* This function initialises the Lua environment stored in the stream.
901 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100902 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200903 *
904 * This function is particular. it initialises a new Lua thread. If the
905 * initialisation fails (example: out of memory error), the lua function
906 * throws an error (longjmp).
907 *
908 * This function manipulates two Lua stack: the main and the thread. Only
909 * the main stack can fail. The thread is not manipulated. This function
910 * MUST NOT manipulate the created thread stack state, because is not
911 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100912 */
913int hlua_ctx_init(struct hlua *lua, struct task *task)
914{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200915 if (!SET_SAFE_LJMP(gL.T)) {
916 lua->Tref = LUA_REFNIL;
917 return 0;
918 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100919 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100920 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100921 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100922 lua->T = lua_newthread(gL.T);
923 if (!lua->T) {
924 lua->Tref = LUA_REFNIL;
925 return 0;
926 }
927 hlua_sethlua(lua);
928 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
929 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200930 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100931 return 1;
932}
933
Willy Tarreau87b09662015-04-03 00:22:06 +0200934/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100935 * is destroyed. The destroy also the memory context. The struct "lua"
936 * is not freed.
937 */
938void hlua_ctx_destroy(struct hlua *lua)
939{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100940 if (!lua->T)
941 return;
942
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100943 /* Purge all the pending signals. */
944 hlua_com_purge(lua);
945
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100946 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
947 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200948
949 /* Forces a garbage collecting process. If the Lua program is finished
950 * without error, we run the GC on the thread pointer. Its freed all
951 * the unused memory.
952 * If the thread is finnish with an error or is currently yielded,
953 * it seems that the GC applied on the thread doesn't clean anything,
954 * so e run the GC on the main thread.
955 * NOTE: maybe this action locks all the Lua threads untiml the en of
956 * the garbage collection.
957 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200958 if (lua->flags & HLUA_MUST_GC) {
959 lua_gc(lua->T, LUA_GCCOLLECT, 0);
960 if (lua_status(lua->T) != LUA_OK)
961 lua_gc(gL.T, LUA_GCCOLLECT, 0);
962 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200963
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200964 lua->T = NULL;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100965}
966
967/* This function is used to restore the Lua context when a coroutine
968 * fails. This function copy the common memory between old coroutine
969 * and the new coroutine. The old coroutine is destroyed, and its
970 * replaced by the new coroutine.
971 * If the flag "keep_msg" is set, the last entry of the old is assumed
972 * as string error message and it is copied in the new stack.
973 */
974static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
975{
976 lua_State *T;
977 int new_ref;
978
979 /* Renew the main LUA stack doesn't have sense. */
980 if (lua == &gL)
981 return 0;
982
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100983 /* New Lua coroutine. */
984 T = lua_newthread(gL.T);
985 if (!T)
986 return 0;
987
988 /* Copy last error message. */
989 if (keep_msg)
990 lua_xmove(lua->T, T, 1);
991
992 /* Copy data between the coroutines. */
993 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
994 lua_xmove(lua->T, T, 1);
995 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
996
997 /* Destroy old data. */
998 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
999
1000 /* The thread is garbage collected by Lua. */
1001 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
1002
1003 /* Fill the struct with the new coroutine values. */
1004 lua->Mref = new_ref;
1005 lua->T = T;
1006 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
1007
1008 /* Set context. */
1009 hlua_sethlua(lua);
1010
1011 return 1;
1012}
1013
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001014void hlua_hook(lua_State *L, lua_Debug *ar)
1015{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001016 struct hlua *hlua = hlua_gethlua(L);
1017
1018 /* Lua cannot yield when its returning from a function,
1019 * so, we can fix the interrupt hook to 1 instruction,
1020 * expecting that the function is finnished.
1021 */
1022 if (lua_gethookmask(L) & LUA_MASKRET) {
1023 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1024 return;
1025 }
1026
1027 /* restore the interrupt condition. */
1028 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1029
1030 /* If we interrupt the Lua processing in yieldable state, we yield.
1031 * If the state is not yieldable, trying yield causes an error.
1032 */
1033 if (lua_isyieldable(L))
1034 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
1035
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001036 /* If we cannot yield, update the clock and check the timeout. */
1037 tv_update_date(0, 1);
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001038 if (tick_is_expired(hlua->expire, now_ms)) {
1039 lua_pushfstring(L, "execution timeout");
1040 WILL_LJMP(lua_error(L));
1041 }
1042
1043 /* Try to interrupt the process at the end of the current
1044 * unyieldable function.
1045 */
1046 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001047}
1048
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001049/* This function start or resumes the Lua stack execution. If the flag
1050 * "yield_allowed" if no set and the LUA stack execution returns a yield
1051 * The function return an error.
1052 *
1053 * The function can returns 4 values:
1054 * - HLUA_E_OK : The execution is terminated without any errors.
1055 * - HLUA_E_AGAIN : The execution must continue at the next associated
1056 * task wakeup.
1057 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
1058 * the top of the stack.
1059 * - HLUA_E_ERR : An error has occured without error message.
1060 *
1061 * If an error occured, the stack is renewed and it is ready to run new
1062 * LUA code.
1063 */
1064static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1065{
1066 int ret;
1067 const char *msg;
1068
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001069 /* If we want to resume the task, then check first the execution timeout.
1070 * if it is reached, we can interrupt the Lua processing.
1071 */
1072 if (tick_is_expired(lua->expire, now_ms))
1073 goto timeout_reached;
1074
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001075resume_execution:
1076
1077 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1078 * instructions. it is used for preventing infinite loops.
1079 */
1080 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1081
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001082 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001083 HLUA_SET_RUN(lua);
1084 HLUA_CLR_CTRLYIELD(lua);
1085 HLUA_CLR_WAKERESWR(lua);
1086 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001087
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001088 /* Call the function. */
1089 ret = lua_resume(lua->T, gL.T, lua->nargs);
1090 switch (ret) {
1091
1092 case LUA_OK:
1093 ret = HLUA_E_OK;
1094 break;
1095
1096 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001097 /* Check if the execution timeout is expired. It it is the case, we
1098 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001099 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001100 if (tick_is_expired(lua->expire, now_ms)) {
1101
1102timeout_reached:
1103
1104 lua_settop(lua->T, 0); /* Empty the stack. */
1105 if (!lua_checkstack(lua->T, 1)) {
1106 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001107 break;
1108 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001109 lua_pushfstring(lua->T, "execution timeout");
1110 ret = HLUA_E_ERRMSG;
1111 break;
1112 }
1113 /* Process the forced yield. if the general yield is not allowed or
1114 * if no task were associated this the current Lua execution
1115 * coroutine, we resume the execution. Else we want to return in the
1116 * scheduler and we want to be waked up again, to continue the
1117 * current Lua execution. So we schedule our own task.
1118 */
1119 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001120 if (!yield_allowed || !lua->task)
1121 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001122 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001123 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001124 if (!yield_allowed) {
1125 lua_settop(lua->T, 0); /* Empty the stack. */
1126 if (!lua_checkstack(lua->T, 1)) {
1127 ret = HLUA_E_ERR;
1128 break;
1129 }
1130 lua_pushfstring(lua->T, "yield not allowed");
1131 ret = HLUA_E_ERRMSG;
1132 break;
1133 }
1134 ret = HLUA_E_AGAIN;
1135 break;
1136
1137 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001138
1139 /* Special exit case. The traditionnal exit is returned as an error
1140 * because the errors ares the only one mean to return immediately
1141 * from and lua execution.
1142 */
1143 if (lua->flags & HLUA_EXIT) {
1144 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001145 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001146 break;
1147 }
1148
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001149 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001150 if (!lua_checkstack(lua->T, 1)) {
1151 ret = HLUA_E_ERR;
1152 break;
1153 }
1154 msg = lua_tostring(lua->T, -1);
1155 lua_settop(lua->T, 0); /* Empty the stack. */
1156 lua_pop(lua->T, 1);
1157 if (msg)
1158 lua_pushfstring(lua->T, "runtime error: %s", msg);
1159 else
1160 lua_pushfstring(lua->T, "unknown runtime error");
1161 ret = HLUA_E_ERRMSG;
1162 break;
1163
1164 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001165 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001166 lua_settop(lua->T, 0); /* Empty the stack. */
1167 if (!lua_checkstack(lua->T, 1)) {
1168 ret = HLUA_E_ERR;
1169 break;
1170 }
1171 lua_pushfstring(lua->T, "out of memory error");
1172 ret = HLUA_E_ERRMSG;
1173 break;
1174
1175 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001176 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001177 if (!lua_checkstack(lua->T, 1)) {
1178 ret = HLUA_E_ERR;
1179 break;
1180 }
1181 msg = lua_tostring(lua->T, -1);
1182 lua_settop(lua->T, 0); /* Empty the stack. */
1183 lua_pop(lua->T, 1);
1184 if (msg)
1185 lua_pushfstring(lua->T, "message handler error: %s", msg);
1186 else
1187 lua_pushfstring(lua->T, "message handler error");
1188 ret = HLUA_E_ERRMSG;
1189 break;
1190
1191 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001192 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001193 lua_settop(lua->T, 0); /* Empty the stack. */
1194 if (!lua_checkstack(lua->T, 1)) {
1195 ret = HLUA_E_ERR;
1196 break;
1197 }
1198 lua_pushfstring(lua->T, "unknonwn error");
1199 ret = HLUA_E_ERRMSG;
1200 break;
1201 }
1202
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001203 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001204 if (lua->flags & HLUA_MUST_GC &&
1205 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001206 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1207
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001208 switch (ret) {
1209 case HLUA_E_AGAIN:
1210 break;
1211
1212 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001213 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001214 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001215 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001216 break;
1217
1218 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001219 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001220 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001221 hlua_ctx_renew(lua, 0);
1222 break;
1223
1224 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001225 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001226 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001227 break;
1228 }
1229
1230 return ret;
1231}
1232
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001233/* This function exit the current code. */
1234__LJMP static int hlua_done(lua_State *L)
1235{
1236 struct hlua *hlua = hlua_gethlua(L);
1237
1238 hlua->flags |= HLUA_EXIT;
1239 WILL_LJMP(lua_error(L));
1240
1241 return 0;
1242}
1243
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001244/* This function is an LUA binding. It provides a function
1245 * for deleting ACL from a referenced ACL file.
1246 */
1247__LJMP static int hlua_del_acl(lua_State *L)
1248{
1249 const char *name;
1250 const char *key;
1251 struct pat_ref *ref;
1252
1253 MAY_LJMP(check_args(L, 2, "del_acl"));
1254
1255 name = MAY_LJMP(luaL_checkstring(L, 1));
1256 key = MAY_LJMP(luaL_checkstring(L, 2));
1257
1258 ref = pat_ref_lookup(name);
1259 if (!ref)
1260 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
1261
1262 pat_ref_delete(ref, key);
1263 return 0;
1264}
1265
1266/* This function is an LUA binding. It provides a function
1267 * for deleting map entry from a referenced map file.
1268 */
1269static int hlua_del_map(lua_State *L)
1270{
1271 const char *name;
1272 const char *key;
1273 struct pat_ref *ref;
1274
1275 MAY_LJMP(check_args(L, 2, "del_map"));
1276
1277 name = MAY_LJMP(luaL_checkstring(L, 1));
1278 key = MAY_LJMP(luaL_checkstring(L, 2));
1279
1280 ref = pat_ref_lookup(name);
1281 if (!ref)
1282 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
1283
1284 pat_ref_delete(ref, key);
1285 return 0;
1286}
1287
1288/* This function is an LUA binding. It provides a function
1289 * for adding ACL pattern from a referenced ACL file.
1290 */
1291static int hlua_add_acl(lua_State *L)
1292{
1293 const char *name;
1294 const char *key;
1295 struct pat_ref *ref;
1296
1297 MAY_LJMP(check_args(L, 2, "add_acl"));
1298
1299 name = MAY_LJMP(luaL_checkstring(L, 1));
1300 key = MAY_LJMP(luaL_checkstring(L, 2));
1301
1302 ref = pat_ref_lookup(name);
1303 if (!ref)
1304 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
1305
1306 if (pat_ref_find_elt(ref, key) == NULL)
1307 pat_ref_add(ref, key, NULL, NULL);
1308 return 0;
1309}
1310
1311/* This function is an LUA binding. It provides a function
1312 * for setting map pattern and sample from a referenced map
1313 * file.
1314 */
1315static int hlua_set_map(lua_State *L)
1316{
1317 const char *name;
1318 const char *key;
1319 const char *value;
1320 struct pat_ref *ref;
1321
1322 MAY_LJMP(check_args(L, 3, "set_map"));
1323
1324 name = MAY_LJMP(luaL_checkstring(L, 1));
1325 key = MAY_LJMP(luaL_checkstring(L, 2));
1326 value = MAY_LJMP(luaL_checkstring(L, 3));
1327
1328 ref = pat_ref_lookup(name);
1329 if (!ref)
1330 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
1331
1332 if (pat_ref_find_elt(ref, key) != NULL)
1333 pat_ref_set(ref, key, value, NULL);
1334 else
1335 pat_ref_add(ref, key, value, NULL);
1336 return 0;
1337}
1338
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001339/* A class is a lot of memory that contain data. This data can be a table,
1340 * an integer or user data. This data is associated with a metatable. This
1341 * metatable have an original version registred in the global context with
1342 * the name of the object (_G[<name>] = <metable> ).
1343 *
1344 * A metable is a table that modify the standard behavior of a standard
1345 * access to the associated data. The entries of this new metatable are
1346 * defined as is:
1347 *
1348 * http://lua-users.org/wiki/MetatableEvents
1349 *
1350 * __index
1351 *
1352 * we access an absent field in a table, the result is nil. This is
1353 * true, but it is not the whole truth. Actually, such access triggers
1354 * the interpreter to look for an __index metamethod: If there is no
1355 * such method, as usually happens, then the access results in nil;
1356 * otherwise, the metamethod will provide the result.
1357 *
1358 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1359 * the key does not appear in the table, but the metatable has an __index
1360 * property:
1361 *
1362 * - if the value is a function, the function is called, passing in the
1363 * table and the key; the return value of that function is returned as
1364 * the result.
1365 *
1366 * - if the value is another table, the value of the key in that table is
1367 * asked for and returned (and if it doesn't exist in that table, but that
1368 * table's metatable has an __index property, then it continues on up)
1369 *
1370 * - Use "rawget(myTable,key)" to skip this metamethod.
1371 *
1372 * http://www.lua.org/pil/13.4.1.html
1373 *
1374 * __newindex
1375 *
1376 * Like __index, but control property assignment.
1377 *
1378 * __mode - Control weak references. A string value with one or both
1379 * of the characters 'k' and 'v' which specifies that the the
1380 * keys and/or values in the table are weak references.
1381 *
1382 * __call - Treat a table like a function. When a table is followed by
1383 * parenthesis such as "myTable( 'foo' )" and the metatable has
1384 * a __call key pointing to a function, that function is invoked
1385 * (passing any specified arguments) and the return value is
1386 * returned.
1387 *
1388 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1389 * called, if the metatable for myTable has a __metatable
1390 * key, the value of that key is returned instead of the
1391 * actual metatable.
1392 *
1393 * __tostring - Control string representation. When the builtin
1394 * "tostring( myTable )" function is called, if the metatable
1395 * for myTable has a __tostring property set to a function,
1396 * that function is invoked (passing myTable to it) and the
1397 * return value is used as the string representation.
1398 *
1399 * __len - Control table length. When the table length is requested using
1400 * the length operator ( '#' ), if the metatable for myTable has
1401 * a __len key pointing to a function, that function is invoked
1402 * (passing myTable to it) and the return value used as the value
1403 * of "#myTable".
1404 *
1405 * __gc - Userdata finalizer code. When userdata is set to be garbage
1406 * collected, if the metatable has a __gc field pointing to a
1407 * function, that function is first invoked, passing the userdata
1408 * to it. The __gc metamethod is not called for tables.
1409 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1410 *
1411 * Special metamethods for redefining standard operators:
1412 * http://www.lua.org/pil/13.1.html
1413 *
1414 * __add "+"
1415 * __sub "-"
1416 * __mul "*"
1417 * __div "/"
1418 * __unm "!"
1419 * __pow "^"
1420 * __concat ".."
1421 *
1422 * Special methods for redfining standar relations
1423 * http://www.lua.org/pil/13.2.html
1424 *
1425 * __eq "=="
1426 * __lt "<"
1427 * __le "<="
1428 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001429
1430/*
1431 *
1432 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001433 * Class Map
1434 *
1435 *
1436 */
1437
1438/* Returns a struct hlua_map if the stack entry "ud" is
1439 * a class session, otherwise it throws an error.
1440 */
1441__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1442{
1443 return (struct map_descriptor *)MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
1444}
1445
1446/* This function is the map constructor. It don't need
1447 * the class Map object. It creates and return a new Map
1448 * object. It must be called only during "body" or "init"
1449 * context because it process some filesystem accesses.
1450 */
1451__LJMP static int hlua_map_new(struct lua_State *L)
1452{
1453 const char *fn;
1454 int match = PAT_MATCH_STR;
1455 struct sample_conv conv;
1456 const char *file = "";
1457 int line = 0;
1458 lua_Debug ar;
1459 char *err = NULL;
1460 struct arg args[2];
1461
1462 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1463 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1464
1465 fn = MAY_LJMP(luaL_checkstring(L, 1));
1466
1467 if (lua_gettop(L) >= 2) {
1468 match = MAY_LJMP(luaL_checkinteger(L, 2));
1469 if (match < 0 || match >= PAT_MATCH_NUM)
1470 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1471 }
1472
1473 /* Get Lua filename and line number. */
1474 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1475 lua_getinfo(L, "Sl", &ar); /* get info about it */
1476 if (ar.currentline > 0) { /* is there info? */
1477 file = ar.short_src;
1478 line = ar.currentline;
1479 }
1480 }
1481
1482 /* fill fake sample_conv struct. */
1483 conv.kw = ""; /* unused. */
1484 conv.process = NULL; /* unused. */
1485 conv.arg_mask = 0; /* unused. */
1486 conv.val_args = NULL; /* unused. */
1487 conv.out_type = SMP_T_STR;
1488 conv.private = (void *)(long)match;
1489 switch (match) {
1490 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1491 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1492 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1493 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1494 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1495 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1496 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001497 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001498 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1499 default:
1500 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1501 }
1502
1503 /* fill fake args. */
1504 args[0].type = ARGT_STR;
1505 args[0].data.str.str = (char *)fn;
1506 args[1].type = ARGT_STOP;
1507
1508 /* load the map. */
1509 if (!sample_load_map(args, &conv, file, line, &err)) {
1510 /* error case: we cant use luaL_error because we must
1511 * free the err variable.
1512 */
1513 luaL_where(L, 1);
1514 lua_pushfstring(L, "'new': %s.", err);
1515 lua_concat(L, 2);
1516 free(err);
1517 WILL_LJMP(lua_error(L));
1518 }
1519
1520 /* create the lua object. */
1521 lua_newtable(L);
1522 lua_pushlightuserdata(L, args[0].data.map);
1523 lua_rawseti(L, -2, 0);
1524
1525 /* Pop a class Map metatable and affect it to the userdata. */
1526 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1527 lua_setmetatable(L, -2);
1528
1529
1530 return 1;
1531}
1532
1533__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1534{
1535 struct map_descriptor *desc;
1536 struct pattern *pat;
1537 struct sample smp;
1538
1539 MAY_LJMP(check_args(L, 2, "lookup"));
1540 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001541 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001542 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001543 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001544 }
1545 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001546 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001547 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001548 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 +02001549 }
1550
1551 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001552 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001553 if (str)
1554 lua_pushstring(L, "");
1555 else
1556 lua_pushnil(L);
1557 return 1;
1558 }
1559
1560 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001561 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001562 return 1;
1563}
1564
1565__LJMP static int hlua_map_lookup(struct lua_State *L)
1566{
1567 return _hlua_map_lookup(L, 0);
1568}
1569
1570__LJMP static int hlua_map_slookup(struct lua_State *L)
1571{
1572 return _hlua_map_lookup(L, 1);
1573}
1574
1575/*
1576 *
1577 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001578 * Class Socket
1579 *
1580 *
1581 */
1582
1583__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1584{
1585 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1586}
1587
1588/* This function is the handler called for each I/O on the established
1589 * connection. It is used for notify space avalaible to send or data
1590 * received.
1591 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001592static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001593{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001594 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001595 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001596
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001597 /* If the connection object is not avalaible, close all the
1598 * streams and wakeup everithing waiting for.
1599 */
1600 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001601 si_shutw(si);
1602 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001603 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001604 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1605 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001606 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001607 }
1608
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001609 /* If we cant write, wakeup the pending write signals. */
1610 if (channel_output_closed(si_ic(si)))
1611 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1612
1613 /* If we cant read, wakeup the pending read signals. */
1614 if (channel_input_closed(si_oc(si)))
1615 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1616
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001617 /* if the connection is not estabkished, inform the stream that we want
1618 * to be notified whenever the connection completes.
1619 */
1620 if (!(c->flags & CO_FL_CONNECTED)) {
1621 si_applet_cant_get(si);
1622 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001623 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001624 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001625
1626 /* This function is called after the connect. */
1627 appctx->ctx.hlua.connected = 1;
1628
1629 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001630 if (channel_may_recv(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001631 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1632
1633 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001634 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001635 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1636}
1637
Willy Tarreau87b09662015-04-03 00:22:06 +02001638/* This function is called when the "struct stream" is destroyed.
1639 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001640 * Wake all the pending signals.
1641 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001642static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001643{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001644 /* Remove my link in the original object. */
1645 if (appctx->ctx.hlua.socket)
1646 appctx->ctx.hlua.socket->s = NULL;
1647
1648 /* Wake all the task waiting for me. */
1649 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1650 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1651}
1652
1653/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001654 * uses this object. If the stream does not exists, just quit.
1655 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001656 * pending signal can rest in the read and write lists. destroy
1657 * it.
1658 */
1659__LJMP static int hlua_socket_gc(lua_State *L)
1660{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001661 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001662 struct appctx *appctx;
1663
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001664 MAY_LJMP(check_args(L, 1, "__gc"));
1665
1666 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001667 if (!socket->s)
1668 return 0;
1669
Willy Tarreau87b09662015-04-03 00:22:06 +02001670 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001671 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001672 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001673 socket->s = NULL;
1674 appctx->ctx.hlua.socket = NULL;
1675
1676 return 0;
1677}
1678
1679/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001680 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001681 */
1682__LJMP static int hlua_socket_close(lua_State *L)
1683{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001684 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001685 struct appctx *appctx;
1686
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001687 MAY_LJMP(check_args(L, 1, "close"));
1688
1689 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001690 if (!socket->s)
1691 return 0;
1692
Willy Tarreau87b09662015-04-03 00:22:06 +02001693 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001694 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001695 appctx = objt_appctx(socket->s->si[0].end);
1696 appctx->ctx.hlua.socket = NULL;
1697 socket->s = NULL;
1698
1699 return 0;
1700}
1701
1702/* This Lua function assumes that the stack contain three parameters.
1703 * 1 - USERDATA containing a struct socket
1704 * 2 - INTEGER with values of the macro defined below
1705 * If the integer is -1, we must read at most one line.
1706 * If the integer is -2, we ust read all the data until the
1707 * end of the stream.
1708 * If the integer is positive value, we must read a number of
1709 * bytes corresponding to this value.
1710 */
1711#define HLSR_READ_LINE (-1)
1712#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001713__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001714{
1715 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1716 int wanted = lua_tointeger(L, 2);
1717 struct hlua *hlua = hlua_gethlua(L);
1718 struct appctx *appctx;
1719 int len;
1720 int nblk;
1721 char *blk1;
1722 int len1;
1723 char *blk2;
1724 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001725 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001726 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001727
1728 /* Check if this lua stack is schedulable. */
1729 if (!hlua || !hlua->task)
1730 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1731 "'frontend', 'backend' or 'task'"));
1732
1733 /* check for connection closed. If some data where read, return it. */
1734 if (!socket->s)
1735 goto connection_closed;
1736
Willy Tarreau94aa6172015-03-13 14:19:06 +01001737 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001738 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001739 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001740 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001741 if (nblk < 0) /* Connection close. */
1742 goto connection_closed;
1743 if (nblk == 0) /* No data avalaible. */
1744 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001745
1746 /* remove final \r\n. */
1747 if (nblk == 1) {
1748 if (blk1[len1-1] == '\n') {
1749 len1--;
1750 skip_at_end++;
1751 if (blk1[len1-1] == '\r') {
1752 len1--;
1753 skip_at_end++;
1754 }
1755 }
1756 }
1757 else {
1758 if (blk2[len2-1] == '\n') {
1759 len2--;
1760 skip_at_end++;
1761 if (blk2[len2-1] == '\r') {
1762 len2--;
1763 skip_at_end++;
1764 }
1765 }
1766 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001767 }
1768
1769 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001770 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001771 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001772 if (nblk < 0) /* Connection close. */
1773 goto connection_closed;
1774 if (nblk == 0) /* No data avalaible. */
1775 goto connection_empty;
1776 }
1777
1778 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001779 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001780 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001781 if (nblk < 0) /* Connection close. */
1782 goto connection_closed;
1783 if (nblk == 0) /* No data avalaible. */
1784 goto connection_empty;
1785
1786 if (len1 > wanted) {
1787 nblk = 1;
1788 len1 = wanted;
1789 } if (nblk == 2 && len1 + len2 > wanted)
1790 len2 = wanted - len1;
1791 }
1792
1793 len = len1;
1794
1795 luaL_addlstring(&socket->b, blk1, len1);
1796 if (nblk == 2) {
1797 len += len2;
1798 luaL_addlstring(&socket->b, blk2, len2);
1799 }
1800
1801 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001802 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001803
1804 /* Don't wait anything. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001805 stream_int_notify(&socket->s->si[0]);
1806 stream_int_update_applet(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001807
1808 /* If the pattern reclaim to read all the data
1809 * in the connection, got out.
1810 */
1811 if (wanted == HLSR_READ_ALL)
1812 goto connection_empty;
1813 else if (wanted >= 0 && len < wanted)
1814 goto connection_empty;
1815
1816 /* Return result. */
1817 luaL_pushresult(&socket->b);
1818 return 1;
1819
1820connection_closed:
1821
1822 /* If the buffer containds data. */
1823 if (socket->b.n > 0) {
1824 luaL_pushresult(&socket->b);
1825 return 1;
1826 }
1827 lua_pushnil(L);
1828 lua_pushstring(L, "connection closed.");
1829 return 2;
1830
1831connection_empty:
1832
1833 appctx = objt_appctx(socket->s->si[0].end);
1834 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1835 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001836 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001837 return 0;
1838}
1839
1840/* This Lus function gets two parameters. The first one can be string
1841 * or a number. If the string is "*l", the user require one line. If
1842 * the string is "*a", the user require all the content of the stream.
1843 * If the value is a number, the user require a number of bytes equal
1844 * to the value. The default value is "*l" (a line).
1845 *
1846 * This paraeter with a variable type is converted in integer. This
1847 * integer takes this values:
1848 * -1 : read a line
1849 * -2 : read all the stream
1850 * >0 : amount if bytes.
1851 *
1852 * The second parameter is optinal. It contains a string that must be
1853 * concatenated with the read data.
1854 */
1855__LJMP static int hlua_socket_receive(struct lua_State *L)
1856{
1857 int wanted = HLSR_READ_LINE;
1858 const char *pattern;
1859 int type;
1860 char *error;
1861 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001862 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001863
1864 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1865 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1866
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001867 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001868
1869 /* check for pattern. */
1870 if (lua_gettop(L) >= 2) {
1871 type = lua_type(L, 2);
1872 if (type == LUA_TSTRING) {
1873 pattern = lua_tostring(L, 2);
1874 if (strcmp(pattern, "*a") == 0)
1875 wanted = HLSR_READ_ALL;
1876 else if (strcmp(pattern, "*l") == 0)
1877 wanted = HLSR_READ_LINE;
1878 else {
1879 wanted = strtoll(pattern, &error, 10);
1880 if (*error != '\0')
1881 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1882 }
1883 }
1884 else if (type == LUA_TNUMBER) {
1885 wanted = lua_tointeger(L, 2);
1886 if (wanted < 0)
1887 WILL_LJMP(luaL_error(L, "Unsupported size."));
1888 }
1889 }
1890
1891 /* Set pattern. */
1892 lua_pushinteger(L, wanted);
1893 lua_replace(L, 2);
1894
1895 /* init bufffer, and fiil it wih prefix. */
1896 luaL_buffinit(L, &socket->b);
1897
1898 /* Check prefix. */
1899 if (lua_gettop(L) >= 3) {
1900 if (lua_type(L, 3) != LUA_TSTRING)
1901 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1902 pattern = lua_tolstring(L, 3, &len);
1903 luaL_addlstring(&socket->b, pattern, len);
1904 }
1905
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001906 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001907}
1908
1909/* Write the Lua input string in the output buffer.
1910 * This fucntion returns a yield if no space are available.
1911 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001912static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001913{
1914 struct hlua_socket *socket;
1915 struct hlua *hlua = hlua_gethlua(L);
1916 struct appctx *appctx;
1917 size_t buf_len;
1918 const char *buf;
1919 int len;
1920 int send_len;
1921 int sent;
1922
1923 /* Check if this lua stack is schedulable. */
1924 if (!hlua || !hlua->task)
1925 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1926 "'frontend', 'backend' or 'task'"));
1927
1928 /* Get object */
1929 socket = MAY_LJMP(hlua_checksocket(L, 1));
1930 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001931 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001932
1933 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001934 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001935 lua_pushinteger(L, -1);
1936 return 1;
1937 }
1938
1939 /* Update the input buffer data. */
1940 buf += sent;
1941 send_len = buf_len - sent;
1942
1943 /* All the data are sent. */
1944 if (sent >= buf_len)
1945 return 1; /* Implicitly return the length sent. */
1946
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001947 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1948 * the request buffer if its not required.
1949 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001950 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001951 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001952 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001953 goto hlua_socket_write_yield_return;
1954 }
1955 }
1956
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001957 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001958 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001959 if (len <= 0)
1960 goto hlua_socket_write_yield_return;
1961
1962 /* send data */
1963 if (len < send_len)
1964 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001965 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001966
1967 /* "Not enough space" (-1), "Buffer too little to contain
1968 * the data" (-2) are not expected because the available length
1969 * is tested.
1970 * Other unknown error are also not expected.
1971 */
1972 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001973 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001974 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001975
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001976 MAY_LJMP(hlua_socket_close(L));
1977 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001978 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001979 return 1;
1980 }
1981
1982 /* update buffers. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001983 stream_int_notify(&socket->s->si[0]);
1984 stream_int_update_applet(&socket->s->si[0]);
1985
Willy Tarreau94aa6172015-03-13 14:19:06 +01001986 socket->s->req.rex = TICK_ETERNITY;
1987 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001988
1989 /* Update length sent. */
1990 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001991 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001992
1993 /* All the data buffer is sent ? */
1994 if (sent + len >= buf_len)
1995 return 1;
1996
1997hlua_socket_write_yield_return:
1998 appctx = objt_appctx(socket->s->si[0].end);
1999 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2000 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002001 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002002 return 0;
2003}
2004
2005/* This function initiate the send of data. It just check the input
2006 * parameters and push an integer in the Lua stack that contain the
2007 * amount of data writed in the buffer. This is used by the function
2008 * "hlua_socket_write_yield" that can yield.
2009 *
2010 * The Lua function gets between 3 and 4 parameters. The first one is
2011 * the associated object. The second is a string buffer. The third is
2012 * a facultative integer that represents where is the buffer position
2013 * of the start of the data that can send. The first byte is the
2014 * position "1". The default value is "1". The fourth argument is a
2015 * facultative integer that represents where is the buffer position
2016 * of the end of the data that can send. The default is the last byte.
2017 */
2018static int hlua_socket_send(struct lua_State *L)
2019{
2020 int i;
2021 int j;
2022 const char *buf;
2023 size_t buf_len;
2024
2025 /* Check number of arguments. */
2026 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2027 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2028
2029 /* Get the string. */
2030 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2031
2032 /* Get and check j. */
2033 if (lua_gettop(L) == 4) {
2034 j = MAY_LJMP(luaL_checkinteger(L, 4));
2035 if (j < 0)
2036 j = buf_len + j + 1;
2037 if (j > buf_len)
2038 j = buf_len + 1;
2039 lua_pop(L, 1);
2040 }
2041 else
2042 j = buf_len;
2043
2044 /* Get and check i. */
2045 if (lua_gettop(L) == 3) {
2046 i = MAY_LJMP(luaL_checkinteger(L, 3));
2047 if (i < 0)
2048 i = buf_len + i + 1;
2049 if (i > buf_len)
2050 i = buf_len + 1;
2051 lua_pop(L, 1);
2052 } else
2053 i = 1;
2054
2055 /* Check bth i and j. */
2056 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002057 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002058 return 1;
2059 }
2060 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002061 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002062 return 1;
2063 }
2064 if (i == 0)
2065 i = 1;
2066 if (j == 0)
2067 j = 1;
2068
2069 /* Pop the string. */
2070 lua_pop(L, 1);
2071
2072 /* Update the buffer length. */
2073 buf += i - 1;
2074 buf_len = j - i + 1;
2075 lua_pushlstring(L, buf, buf_len);
2076
2077 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002078 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002079
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002080 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002081}
2082
Willy Tarreau22b0a682015-06-17 19:43:49 +02002083#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002084__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2085{
2086 static char buffer[SOCKET_INFO_MAX_LEN];
2087 int ret;
2088 int len;
2089 char *p;
2090
2091 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2092 if (ret <= 0) {
2093 lua_pushnil(L);
2094 return 1;
2095 }
2096
2097 if (ret == AF_UNIX) {
2098 lua_pushstring(L, buffer+1);
2099 return 1;
2100 }
2101 else if (ret == AF_INET6) {
2102 buffer[0] = '[';
2103 len = strlen(buffer);
2104 buffer[len] = ']';
2105 len++;
2106 buffer[len] = ':';
2107 len++;
2108 p = buffer;
2109 }
2110 else if (ret == AF_INET) {
2111 p = buffer + 1;
2112 len = strlen(p);
2113 p[len] = ':';
2114 len++;
2115 }
2116 else {
2117 lua_pushnil(L);
2118 return 1;
2119 }
2120
2121 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2122 lua_pushnil(L);
2123 return 1;
2124 }
2125
2126 lua_pushstring(L, p);
2127 return 1;
2128}
2129
2130/* Returns information about the peer of the connection. */
2131__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2132{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002133 struct hlua_socket *socket;
2134 struct connection *conn;
2135
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002136 MAY_LJMP(check_args(L, 1, "getpeername"));
2137
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002138 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002139
2140 /* Check if the tcp object is avalaible. */
2141 if (!socket->s) {
2142 lua_pushnil(L);
2143 return 1;
2144 }
2145
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002146 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002147 if (!conn) {
2148 lua_pushnil(L);
2149 return 1;
2150 }
2151
2152 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
2153 unsigned int salen = sizeof(conn->addr.to);
2154 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
2155 lua_pushnil(L);
2156 return 1;
2157 }
2158 conn->flags |= CO_FL_ADDR_TO_SET;
2159 }
2160
2161 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2162}
2163
2164/* Returns information about my connection side. */
2165static int hlua_socket_getsockname(struct lua_State *L)
2166{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002167 struct hlua_socket *socket;
2168 struct connection *conn;
2169
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002170 MAY_LJMP(check_args(L, 1, "getsockname"));
2171
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002172 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002173
2174 /* Check if the tcp object is avalaible. */
2175 if (!socket->s) {
2176 lua_pushnil(L);
2177 return 1;
2178 }
2179
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002180 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002181 if (!conn) {
2182 lua_pushnil(L);
2183 return 1;
2184 }
2185
2186 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2187 unsigned int salen = sizeof(conn->addr.from);
2188 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2189 lua_pushnil(L);
2190 return 1;
2191 }
2192 conn->flags |= CO_FL_ADDR_FROM_SET;
2193 }
2194
2195 return hlua_socket_info(L, &conn->addr.from);
2196}
2197
2198/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002199static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002200 .obj_type = OBJ_TYPE_APPLET,
2201 .name = "<LUA_TCP>",
2202 .fct = hlua_socket_handler,
2203 .release = hlua_socket_release,
2204};
2205
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002206__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002207{
2208 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2209 struct hlua *hlua = hlua_gethlua(L);
2210 struct appctx *appctx;
2211
2212 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002213 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002214 lua_pushnil(L);
2215 lua_pushstring(L, "Can't connect");
2216 return 2;
2217 }
2218
2219 appctx = objt_appctx(socket->s->si[0].end);
2220
2221 /* Check for connection established. */
2222 if (appctx->ctx.hlua.connected) {
2223 lua_pushinteger(L, 1);
2224 return 1;
2225 }
2226
2227 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2228 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002229 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002230 return 0;
2231}
2232
2233/* This function fail or initite the connection. */
2234__LJMP static int hlua_socket_connect(struct lua_State *L)
2235{
2236 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002237 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002238 const char *ip;
2239 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002240 struct hlua *hlua;
2241 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002242 int low, high;
2243 struct sockaddr_storage *addr;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002244
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002245 if (lua_gettop(L) < 2)
2246 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002247
2248 /* Get args. */
2249 socket = MAY_LJMP(hlua_checksocket(L, 1));
2250 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002251 if (lua_gettop(L) >= 3)
2252 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002253
Willy Tarreau973a5422015-08-05 21:47:23 +02002254 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002255 if (!conn)
2256 WILL_LJMP(luaL_error(L, "connect: internal error"));
2257
Willy Tarreau3adac082015-09-26 17:51:09 +02002258 /* needed for the connection not to be closed */
2259 conn->target = socket->s->target;
2260
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002261 /* Parse ip address. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002262 addr = str2sa_range(ip, &low, &high, NULL, NULL, NULL, 0);
2263 if (!addr)
2264 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
2265 if (low != high)
2266 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
2267 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002268
2269 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002270 if (low == 0) {
2271 if (conn->addr.to.ss_family == AF_INET) {
2272 if (port == -1)
2273 WILL_LJMP(luaL_error(L, "connect: port missing"));
2274 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2275 } else if (conn->addr.to.ss_family == AF_INET6) {
2276 if (port == -1)
2277 WILL_LJMP(luaL_error(L, "connect: port missing"));
2278 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2279 }
2280 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002281
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002282 hlua = hlua_gethlua(L);
2283 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002284
2285 /* inform the stream that we want to be notified whenever the
2286 * connection completes.
2287 */
2288 si_applet_cant_get(&socket->s->si[0]);
2289 si_applet_cant_put(&socket->s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002290 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002291
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002292 hlua->flags |= HLUA_MUST_GC;
2293
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002294 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2295 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002296 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002297
2298 return 0;
2299}
2300
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002301#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002302__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2303{
2304 struct hlua_socket *socket;
2305
2306 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2307 socket = MAY_LJMP(hlua_checksocket(L, 1));
2308 socket->s->target = &socket_ssl.obj_type;
2309 return MAY_LJMP(hlua_socket_connect(L));
2310}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002311#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002312
2313__LJMP static int hlua_socket_setoption(struct lua_State *L)
2314{
2315 return 0;
2316}
2317
2318__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2319{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002320 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002321 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002322
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323 MAY_LJMP(check_args(L, 2, "settimeout"));
2324
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002325 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002326 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002327
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002328 socket->s->req.rto = tmout;
2329 socket->s->req.wto = tmout;
2330 socket->s->res.rto = tmout;
2331 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002332
2333 return 0;
2334}
2335
2336__LJMP static int hlua_socket_new(lua_State *L)
2337{
2338 struct hlua_socket *socket;
2339 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002340 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002341 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002342 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002343
2344 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002345 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002346 hlua_pusherror(L, "socket: full stack");
2347 goto out_fail_conf;
2348 }
2349
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002350 /* Create the object: obj[0] = userdata. */
2351 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002352 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002353 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002354 memset(socket, 0, sizeof(*socket));
2355
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002356 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002357 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002358 hlua_pusherror(L, "socket: uninitialized pools.");
2359 goto out_fail_conf;
2360 }
2361
Willy Tarreau87b09662015-04-03 00:22:06 +02002362 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002363 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2364 lua_setmetatable(L, -2);
2365
Willy Tarreaud420a972015-04-06 00:39:18 +02002366 /* Create the applet context */
2367 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002368 if (!appctx) {
2369 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002370 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002371 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002372
Willy Tarreaud420a972015-04-06 00:39:18 +02002373 appctx->ctx.hlua.socket = socket;
2374 appctx->ctx.hlua.connected = 0;
2375 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2376 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002377
Willy Tarreaud420a972015-04-06 00:39:18 +02002378 /* Now create a session, task and stream for this applet */
2379 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2380 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002381 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002382 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002383 }
2384
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002385 task = task_new();
2386 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002387 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002388 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002389 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002390 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002391
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002392 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002393 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002394 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002395 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002396 }
2397
Willy Tarreaud420a972015-04-06 00:39:18 +02002398 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002399 socket->s = strm;
2400 strm->hlua.T = NULL;
2401 strm->hlua.Tref = LUA_REFNIL;
2402 strm->hlua.Mref = LUA_REFNIL;
2403 strm->hlua.nargs = 0;
2404 strm->hlua.flags = 0;
2405 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002406
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002407 /* Configure "right" stream interface. this "si" is used to connect
2408 * and retrieve data from the server. The connection is initialized
2409 * with the "struct server".
2410 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002411 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002412
2413 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002414 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2415 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002416
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002417 /* Update statistics counters. */
2418 socket_proxy.feconn++; /* beconn will be increased later */
2419 jobs++;
2420 totalconn++;
2421
2422 /* Return yield waiting for connection. */
2423 return 1;
2424
Willy Tarreaud420a972015-04-06 00:39:18 +02002425 out_fail_stream:
2426 task_free(task);
2427 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002428 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002429 out_fail_sess:
2430 appctx_free(appctx);
2431 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002432 WILL_LJMP(lua_error(L));
2433 return 0;
2434}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002435
2436/*
2437 *
2438 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002439 * Class Channel
2440 *
2441 *
2442 */
2443
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002444/* The state between the channel data and the HTTP parser state can be
2445 * unconsistent, so reset the parser and call it again. Warning, this
2446 * action not revalidate the request and not send a 400 if the modified
2447 * resuest is not valid.
2448 *
2449 * This function never fails. If dir is 0 we are a request, if it is 1
2450 * its a response.
2451 */
2452static void hlua_resynchonize_proto(struct stream *stream, int dir)
2453{
2454 /* Protocol HTTP. */
2455 if (stream->be->mode == PR_MODE_HTTP) {
2456
2457 if (dir == 0)
2458 http_txn_reset_req(stream->txn);
2459 else if (dir == 1)
2460 http_txn_reset_res(stream->txn);
2461
2462 if (stream->txn->hdr_idx.v)
2463 hdr_idx_init(&stream->txn->hdr_idx);
2464
2465 if (dir == 0)
2466 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
2467 else if (dir == 1)
2468 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2469 }
2470}
2471
2472/* Check the protocole integrity after the Lua manipulations.
2473 * Close the stream and returns 0 if fails, otherwise returns 1.
2474 */
2475static int hlua_check_proto(struct stream *stream, int dir)
2476{
2477 const struct chunk msg = { .len = 0 };
2478
Willy Tarreau9af89f72015-09-26 11:50:08 +02002479 /* Protocol HTTP. The message parsing state must match the request or
2480 * response state. The problem that may happen is that Lua modifies
2481 * the request or response message *after* it was parsed, and corrupted
2482 * it so that it could not be processed anymore. We just need to verify
2483 * if the parser is still expected to run or not.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002484 */
2485 if (stream->be->mode == PR_MODE_HTTP) {
Willy Tarreau9af89f72015-09-26 11:50:08 +02002486 if (dir == 0 &&
2487 !(stream->req.analysers & AN_REQ_WAIT_HTTP) &&
2488 stream->txn->req.msg_state < HTTP_MSG_BODY) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002489 stream_int_retnclose(&stream->si[0], &msg);
2490 return 0;
2491 }
Willy Tarreau9af89f72015-09-26 11:50:08 +02002492 else if (dir == 1 &&
2493 !(stream->res.analysers & AN_RES_WAIT_HTTP) &&
2494 stream->txn->rsp.msg_state < HTTP_MSG_BODY) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002495 stream_int_retnclose(&stream->si[0], &msg);
2496 return 0;
2497 }
2498 }
2499 return 1;
2500}
2501
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002502/* Returns the struct hlua_channel join to the class channel in the
2503 * stack entry "ud" or throws an argument error.
2504 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002505__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002506{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002507 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002508}
2509
Willy Tarreau47860ed2015-03-10 14:07:50 +01002510/* Pushes the channel onto the top of the stack. If the stask does not have a
2511 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002512 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002513static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002514{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002515 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002516 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002517 return 0;
2518
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002519 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002520 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002521 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002522
2523 /* Pop a class sesison metatable and affect it to the userdata. */
2524 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2525 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002526 return 1;
2527}
2528
2529/* Duplicate all the data present in the input channel and put it
2530 * in a string LUA variables. Returns -1 and push a nil value in
2531 * the stack if the channel is closed and all the data are consumed,
2532 * returns 0 if no data are available, otherwise it returns the length
2533 * of the builded string.
2534 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002535static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002536{
2537 char *blk1;
2538 char *blk2;
2539 int len1;
2540 int len2;
2541 int ret;
2542 luaL_Buffer b;
2543
Willy Tarreau47860ed2015-03-10 14:07:50 +01002544 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002545 if (unlikely(ret == 0))
2546 return 0;
2547
2548 if (unlikely(ret < 0)) {
2549 lua_pushnil(L);
2550 return -1;
2551 }
2552
2553 luaL_buffinit(L, &b);
2554 luaL_addlstring(&b, blk1, len1);
2555 if (unlikely(ret == 2))
2556 luaL_addlstring(&b, blk2, len2);
2557 luaL_pushresult(&b);
2558
2559 if (unlikely(ret == 2))
2560 return len1 + len2;
2561 return len1;
2562}
2563
2564/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2565 * a yield. This function keep the data in the buffer.
2566 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002567__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002568{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002569 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002570
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002571 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2572
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002573 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002574 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002575 return 1;
2576}
2577
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002578/* Check arguments for the function "hlua_channel_dup_yield". */
2579__LJMP static int hlua_channel_dup(lua_State *L)
2580{
2581 MAY_LJMP(check_args(L, 1, "dup"));
2582 MAY_LJMP(hlua_checkchannel(L, 1));
2583 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2584}
2585
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002586/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2587 * a yield. This function consumes the data in the buffer. It returns
2588 * a string containing the data or a nil pointer if no data are available
2589 * and the channel is closed.
2590 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002591__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002592{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002593 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002594 int ret;
2595
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002596 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002597
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002598 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002599 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002600 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002601
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002602 if (unlikely(ret == -1))
2603 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002604
Willy Tarreau47860ed2015-03-10 14:07:50 +01002605 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002606 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002607 return 1;
2608}
2609
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002610/* Check arguments for the fucntion "hlua_channel_get_yield". */
2611__LJMP static int hlua_channel_get(lua_State *L)
2612{
2613 MAY_LJMP(check_args(L, 1, "get"));
2614 MAY_LJMP(hlua_checkchannel(L, 1));
2615 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2616}
2617
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002618/* This functions consumes and returns one line. If the channel is closed,
2619 * and the last data does not contains a final '\n', the data are returned
2620 * without the final '\n'. When no more data are avalaible, it returns nil
2621 * value.
2622 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002623__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002624{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002625 char *blk1;
2626 char *blk2;
2627 int len1;
2628 int len2;
2629 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002630 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002631 int ret;
2632 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002633
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002634 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2635
Willy Tarreau47860ed2015-03-10 14:07:50 +01002636 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002637 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002638 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002639
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002640 if (ret == -1) {
2641 lua_pushnil(L);
2642 return 1;
2643 }
2644
2645 luaL_buffinit(L, &b);
2646 luaL_addlstring(&b, blk1, len1);
2647 len = len1;
2648 if (unlikely(ret == 2)) {
2649 luaL_addlstring(&b, blk2, len2);
2650 len += len2;
2651 }
2652 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002653 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002654 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002655 return 1;
2656}
2657
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002658/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2659__LJMP static int hlua_channel_getline(lua_State *L)
2660{
2661 MAY_LJMP(check_args(L, 1, "getline"));
2662 MAY_LJMP(hlua_checkchannel(L, 1));
2663 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2664}
2665
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002666/* This function takes a string as input, and append it at the
2667 * input side of channel. If the data is too big, but a space
2668 * is probably available after sending some data, the function
2669 * yield. If the data is bigger than the buffer, or if the
2670 * channel is closed, it returns -1. otherwise, it returns the
2671 * amount of data writed.
2672 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002673__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002674{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002675 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002676 size_t len;
2677 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2678 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2679 int ret;
2680 int max;
2681
Willy Tarreau47860ed2015-03-10 14:07:50 +01002682 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002683 if (max > len - l)
2684 max = len - l;
2685
Willy Tarreau47860ed2015-03-10 14:07:50 +01002686 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002687 if (ret == -2 || ret == -3) {
2688 lua_pushinteger(L, -1);
2689 return 1;
2690 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002691 if (ret == -1) {
2692 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002693 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002694 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002695 l += ret;
2696 lua_pop(L, 1);
2697 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002698 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002699
Willy Tarreau47860ed2015-03-10 14:07:50 +01002700 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2701 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002702 /* There are no space avalaible, and the output buffer is empty.
2703 * in this case, we cannot add more data, so we cannot yield,
2704 * we return the amount of copyied data.
2705 */
2706 return 1;
2707 }
2708 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002709 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002710 return 1;
2711}
2712
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002713/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002714 * of the writed string, or -1 if the channel is closed or if the
2715 * buffer size is too little for the data.
2716 */
2717__LJMP static int hlua_channel_append(lua_State *L)
2718{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002719 size_t len;
2720
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002721 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002722 MAY_LJMP(hlua_checkchannel(L, 1));
2723 MAY_LJMP(luaL_checklstring(L, 2, &len));
2724 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002725 lua_pushinteger(L, 0);
2726
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002727 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002728}
2729
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002730/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002731 * his process by cleaning the buffer. The result is a replacement
2732 * of the current data. It returns the length of the writed string,
2733 * or -1 if the channel is closed or if the buffer size is too
2734 * little for the data.
2735 */
2736__LJMP static int hlua_channel_set(lua_State *L)
2737{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002738 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002739
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002740 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002741 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002742 lua_pushinteger(L, 0);
2743
Willy Tarreau47860ed2015-03-10 14:07:50 +01002744 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002745
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002746 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002747}
2748
2749/* Append data in the output side of the buffer. This data is immediatly
2750 * sent. The fcuntion returns the ammount of data writed. If the buffer
2751 * cannot contains the data, the function yield. The function returns -1
2752 * if the channel is closed.
2753 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002754__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002755{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002756 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002757 size_t len;
2758 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2759 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2760 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002761 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002762
Willy Tarreau47860ed2015-03-10 14:07:50 +01002763 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002764 lua_pushinteger(L, -1);
2765 return 1;
2766 }
2767
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002768 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2769 * the request buffer if its not required.
2770 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002771 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002772 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002773 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002774 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002775 }
2776 }
2777
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002778 /* the writed data will be immediatly sent, so we can check
2779 * the avalaible space without taking in account the reserve.
2780 * The reserve is guaranted for the processing of incoming
2781 * data, because the buffer will be flushed.
2782 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002783 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002784
2785 /* If there are no space avalaible, and the output buffer is empty.
2786 * in this case, we cannot add more data, so we cannot yield,
2787 * we return the amount of copyied data.
2788 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002789 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002790 return 1;
2791
2792 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002793 if (max > len - l)
2794 max = len - l;
2795
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002796 /* The buffer avalaible size may be not contiguous. This test
2797 * detects a non contiguous buffer and realign it.
2798 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002799 if (bi_space_for_replace(chn->buf) < max)
2800 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002801
2802 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002803 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002804
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002805 /* buffer replace considers that the input part is filled.
2806 * so, I must forward these new data in the output part.
2807 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002808 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002809
2810 l += max;
2811 lua_pop(L, 1);
2812 lua_pushinteger(L, l);
2813
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002814 /* If there are no space avalaible, and the output buffer is empty.
2815 * in this case, we cannot add more data, so we cannot yield,
2816 * we return the amount of copyied data.
2817 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002818 max = chn->buf->size - buffer_len(chn->buf);
2819 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002820 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002821
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002822 if (l < len) {
2823 /* If we are waiting for space in the response buffer, we
2824 * must set the flag WAKERESWR. This flag required the task
2825 * wake up if any activity is detected on the response buffer.
2826 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002827 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002828 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002829 else
2830 HLUA_SET_WAKEREQWR(hlua);
2831 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002832 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002833
2834 return 1;
2835}
2836
2837/* Just a wraper of "_hlua_channel_send". This wrapper permits
2838 * yield the LUA process, and resume it without checking the
2839 * input arguments.
2840 */
2841__LJMP static int hlua_channel_send(lua_State *L)
2842{
2843 MAY_LJMP(check_args(L, 2, "send"));
2844 lua_pushinteger(L, 0);
2845
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002846 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002847}
2848
2849/* This function forward and amount of butes. The data pass from
2850 * the input side of the buffer to the output side, and can be
2851 * forwarded. This function never fails.
2852 *
2853 * The Lua function takes an amount of bytes to be forwarded in
2854 * imput. It returns the number of bytes forwarded.
2855 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002856__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002857{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002858 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002859 int len;
2860 int l;
2861 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002862 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002863
2864 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2865 len = MAY_LJMP(luaL_checkinteger(L, 2));
2866 l = MAY_LJMP(luaL_checkinteger(L, -1));
2867
2868 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002869 if (max > chn->buf->i)
2870 max = chn->buf->i;
2871 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002872 l += max;
2873
2874 lua_pop(L, 1);
2875 lua_pushinteger(L, l);
2876
2877 /* Check if it miss bytes to forward. */
2878 if (l < len) {
2879 /* The the input channel or the output channel are closed, we
2880 * must return the amount of data forwarded.
2881 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002882 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002883 return 1;
2884
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002885 /* If we are waiting for space data in the response buffer, we
2886 * must set the flag WAKERESWR. This flag required the task
2887 * wake up if any activity is detected on the response buffer.
2888 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002889 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002890 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002891 else
2892 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002893
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002894 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002895 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002896 }
2897
2898 return 1;
2899}
2900
2901/* Just check the input and prepare the stack for the previous
2902 * function "hlua_channel_forward_yield"
2903 */
2904__LJMP static int hlua_channel_forward(lua_State *L)
2905{
2906 MAY_LJMP(check_args(L, 2, "forward"));
2907 MAY_LJMP(hlua_checkchannel(L, 1));
2908 MAY_LJMP(luaL_checkinteger(L, 2));
2909
2910 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002911 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002912}
2913
2914/* Just returns the number of bytes available in the input
2915 * side of the buffer. This function never fails.
2916 */
2917__LJMP static int hlua_channel_get_in_len(lua_State *L)
2918{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002919 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002920
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002921 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002922 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002923 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002924 return 1;
2925}
2926
2927/* Just returns the number of bytes available in the output
2928 * side of the buffer. This function never fails.
2929 */
2930__LJMP static int hlua_channel_get_out_len(lua_State *L)
2931{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002932 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002933
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002934 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002935 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002936 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002937 return 1;
2938}
2939
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002940/*
2941 *
2942 *
2943 * Class Fetches
2944 *
2945 *
2946 */
2947
2948/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002949 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002950 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002951__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002952{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002953 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002954}
2955
2956/* This function creates and push in the stack a fetch object according
2957 * with a current TXN.
2958 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002959static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002960{
Willy Tarreau7073c472015-04-06 11:15:40 +02002961 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002962
2963 /* Check stack size. */
2964 if (!lua_checkstack(L, 3))
2965 return 0;
2966
2967 /* Create the object: obj[0] = userdata.
2968 * Note that the base of the Fetches object is the
2969 * transaction object.
2970 */
2971 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002972 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002973 lua_rawseti(L, -2, 0);
2974
Willy Tarreau7073c472015-04-06 11:15:40 +02002975 hsmp->s = txn->s;
2976 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002977 hsmp->stringsafe = stringsafe;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002978
2979 /* Pop a class sesison metatable and affect it to the userdata. */
2980 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2981 lua_setmetatable(L, -2);
2982
2983 return 1;
2984}
2985
2986/* This function is an LUA binding. It is called with each sample-fetch.
2987 * It uses closure argument to store the associated sample-fetch. It
2988 * returns only one argument or throws an error. An error is thrown
2989 * only if an error is encountered during the argument parsing. If
2990 * the "sample-fetch" function fails, nil is returned.
2991 */
2992__LJMP static int hlua_run_sample_fetch(lua_State *L)
2993{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002994 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002995 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002996 struct arg args[ARGM_NBARGS + 1];
2997 int i;
2998 struct sample smp;
2999
3000 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003001 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003002
3003 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003004 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003005
3006 /* Get extra arguments. */
3007 for (i = 0; i < lua_gettop(L) - 1; i++) {
3008 if (i >= ARGM_NBARGS)
3009 break;
3010 hlua_lua2arg(L, i + 2, &args[i]);
3011 }
3012 args[i].type = ARGT_STOP;
3013
3014 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003015 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003016
3017 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003018 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003019 lua_pushfstring(L, "error in arguments");
3020 WILL_LJMP(lua_error(L));
3021 }
3022
3023 /* Initialise the sample. */
3024 memset(&smp, 0, sizeof(smp));
3025
3026 /* Run the sample fetch process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02003027 smp.px = hsmp->p;
3028 smp.sess = hsmp->s->sess;
3029 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02003030 smp.opt = 0;
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003031 if (!f->process(args, &smp, f->kw, f->private)) {
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003032 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003033 lua_pushstring(L, "");
3034 else
3035 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003036 return 1;
3037 }
3038
3039 /* Convert the returned sample in lua value. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003040 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003041 hlua_smp2lua_str(L, &smp);
3042 else
3043 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003044 return 1;
3045}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003046
3047/*
3048 *
3049 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003050 * Class Converters
3051 *
3052 *
3053 */
3054
3055/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003056 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003057 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003058__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003059{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003060 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003061}
3062
3063/* This function creates and push in the stack a Converters object
3064 * according with a current TXN.
3065 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003066static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003067{
Willy Tarreau7073c472015-04-06 11:15:40 +02003068 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003069
3070 /* Check stack size. */
3071 if (!lua_checkstack(L, 3))
3072 return 0;
3073
3074 /* Create the object: obj[0] = userdata.
3075 * Note that the base of the Converters object is the
3076 * same than the TXN object.
3077 */
3078 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003079 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003080 lua_rawseti(L, -2, 0);
3081
Willy Tarreau7073c472015-04-06 11:15:40 +02003082 hsmp->s = txn->s;
3083 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02003084 hsmp->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003085
Willy Tarreau87b09662015-04-03 00:22:06 +02003086 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003087 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3088 lua_setmetatable(L, -2);
3089
3090 return 1;
3091}
3092
3093/* This function is an LUA binding. It is called with each converter.
3094 * It uses closure argument to store the associated converter. It
3095 * returns only one argument or throws an error. An error is thrown
3096 * only if an error is encountered during the argument parsing. If
3097 * the converter function function fails, nil is returned.
3098 */
3099__LJMP static int hlua_run_sample_conv(lua_State *L)
3100{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003101 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003102 struct sample_conv *conv;
3103 struct arg args[ARGM_NBARGS + 1];
3104 int i;
3105 struct sample smp;
3106
3107 /* Get closure arguments. */
3108 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
3109
3110 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003111 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003112
3113 /* Get extra arguments. */
3114 for (i = 0; i < lua_gettop(L) - 2; i++) {
3115 if (i >= ARGM_NBARGS)
3116 break;
3117 hlua_lua2arg(L, i + 3, &args[i]);
3118 }
3119 args[i].type = ARGT_STOP;
3120
3121 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003122 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003123
3124 /* Run the special args checker. */
3125 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3126 hlua_pusherror(L, "error in arguments");
3127 WILL_LJMP(lua_error(L));
3128 }
3129
3130 /* Initialise the sample. */
3131 if (!hlua_lua2smp(L, 2, &smp)) {
3132 hlua_pusherror(L, "error in the input argument");
3133 WILL_LJMP(lua_error(L));
3134 }
3135
3136 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003137 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003138 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003139 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003140 WILL_LJMP(lua_error(L));
3141 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003142 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3143 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003144 hlua_pusherror(L, "error during the input argument casting");
3145 WILL_LJMP(lua_error(L));
3146 }
3147
3148 /* Run the sample conversion process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02003149 smp.px = hsmp->p;
3150 smp.sess = hsmp->s->sess;
3151 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02003152 smp.opt = 0;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003153 if (!conv->process(args, &smp, conv->private)) {
Willy Tarreauda5f1082015-04-06 11:17:13 +02003154 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003155 lua_pushstring(L, "");
3156 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003157 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003158 return 1;
3159 }
3160
3161 /* Convert the returned sample in lua value. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003162 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003163 hlua_smp2lua_str(L, &smp);
3164 else
3165 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003166 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003167}
3168
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003169/*
3170 *
3171 *
3172 * Class AppletTCP
3173 *
3174 *
3175 */
3176
3177/* Returns a struct hlua_txn if the stack entry "ud" is
3178 * a class stream, otherwise it throws an error.
3179 */
3180__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3181{
3182 return (struct hlua_appctx *)MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
3183}
3184
3185/* This function creates and push in the stack an Applet object
3186 * according with a current TXN.
3187 */
3188static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3189{
3190 struct hlua_appctx *appctx;
3191 struct stream_interface *si = ctx->owner;
3192 struct stream *s = si_strm(si);
3193 struct proxy *p = s->be;
3194
3195 /* Check stack size. */
3196 if (!lua_checkstack(L, 3))
3197 return 0;
3198
3199 /* Create the object: obj[0] = userdata.
3200 * Note that the base of the Converters object is the
3201 * same than the TXN object.
3202 */
3203 lua_newtable(L);
3204 appctx = lua_newuserdata(L, sizeof(*appctx));
3205 lua_rawseti(L, -2, 0);
3206 appctx->appctx = ctx;
3207 appctx->htxn.s = s;
3208 appctx->htxn.p = p;
3209
3210 /* Create the "f" field that contains a list of fetches. */
3211 lua_pushstring(L, "f");
3212 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3213 return 0;
3214 lua_settable(L, -3);
3215
3216 /* Create the "sf" field that contains a list of stringsafe fetches. */
3217 lua_pushstring(L, "sf");
3218 if (!hlua_fetches_new(L, &appctx->htxn, 1))
3219 return 0;
3220 lua_settable(L, -3);
3221
3222 /* Create the "c" field that contains a list of converters. */
3223 lua_pushstring(L, "c");
3224 if (!hlua_converters_new(L, &appctx->htxn, 0))
3225 return 0;
3226 lua_settable(L, -3);
3227
3228 /* Create the "sc" field that contains a list of stringsafe converters. */
3229 lua_pushstring(L, "sc");
3230 if (!hlua_converters_new(L, &appctx->htxn, 1))
3231 return 0;
3232 lua_settable(L, -3);
3233
3234 /* Pop a class stream metatable and affect it to the table. */
3235 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3236 lua_setmetatable(L, -2);
3237
3238 return 1;
3239}
3240
3241/* If expected data not yet available, it returns a yield. This function
3242 * consumes the data in the buffer. It returns a string containing the
3243 * data. This string can be empty.
3244 */
3245__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3246{
3247 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3248 struct stream_interface *si = appctx->appctx->owner;
3249 int ret;
3250 char *blk1;
3251 int len1;
3252 char *blk2;
3253 int len2;
3254
3255 /* Read the maximum amount of data avalaible. */
3256 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3257
3258 /* Data not yet avalaible. return yield. */
3259 if (ret == 0) {
3260 si_applet_cant_get(si);
3261 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3262 }
3263
3264 /* End of data: commit the total strings and return. */
3265 if (ret < 0) {
3266 luaL_pushresult(&appctx->b);
3267 return 1;
3268 }
3269
3270 /* Ensure that the block 2 length is usable. */
3271 if (ret == 1)
3272 len2 = 0;
3273
3274 /* dont check the max length read and dont check. */
3275 luaL_addlstring(&appctx->b, blk1, len1);
3276 luaL_addlstring(&appctx->b, blk2, len2);
3277
3278 /* Consume input channel output buffer data. */
3279 bo_skip(si_oc(si), len1 + len2);
3280 luaL_pushresult(&appctx->b);
3281 return 1;
3282}
3283
3284/* Check arguments for the fucntion "hlua_channel_get_yield". */
3285__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3286{
3287 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3288
3289 /* Initialise the string catenation. */
3290 luaL_buffinit(L, &appctx->b);
3291
3292 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3293}
3294
3295/* If expected data not yet available, it returns a yield. This function
3296 * consumes the data in the buffer. It returns a string containing the
3297 * data. This string can be empty.
3298 */
3299__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3300{
3301 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3302 struct stream_interface *si = appctx->appctx->owner;
3303 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3304 int ret;
3305 char *blk1;
3306 int len1;
3307 char *blk2;
3308 int len2;
3309
3310 /* Read the maximum amount of data avalaible. */
3311 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3312
3313 /* Data not yet avalaible. return yield. */
3314 if (ret == 0) {
3315 si_applet_cant_get(si);
3316 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3317 }
3318
3319 /* End of data: commit the total strings and return. */
3320 if (ret < 0) {
3321 luaL_pushresult(&appctx->b);
3322 return 1;
3323 }
3324
3325 /* Ensure that the block 2 length is usable. */
3326 if (ret == 1)
3327 len2 = 0;
3328
3329 if (len == -1) {
3330
3331 /* If len == -1, catenate all the data avalaile and
3332 * yield because we want to get all the data until
3333 * the end of data stream.
3334 */
3335 luaL_addlstring(&appctx->b, blk1, len1);
3336 luaL_addlstring(&appctx->b, blk2, len2);
3337 bo_skip(si_oc(si), len1 + len2);
3338 si_applet_cant_get(si);
3339 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3340
3341 } else {
3342
3343 /* Copy the fisrt block caping to the length required. */
3344 if (len1 > len)
3345 len1 = len;
3346 luaL_addlstring(&appctx->b, blk1, len1);
3347 len -= len1;
3348
3349 /* Copy the second block. */
3350 if (len2 > len)
3351 len2 = len;
3352 luaL_addlstring(&appctx->b, blk2, len2);
3353 len -= len2;
3354
3355 /* Consume input channel output buffer data. */
3356 bo_skip(si_oc(si), len1 + len2);
3357
3358 /* If we are no other data avalaible, yield waiting for new data. */
3359 if (len > 0) {
3360 lua_pushinteger(L, len);
3361 lua_replace(L, 2);
3362 si_applet_cant_get(si);
3363 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3364 }
3365
3366 /* return the result. */
3367 luaL_pushresult(&appctx->b);
3368 return 1;
3369 }
3370
3371 /* we never executes this */
3372 hlua_pusherror(L, "Lua: internal error");
3373 WILL_LJMP(lua_error(L));
3374 return 0;
3375}
3376
3377/* Check arguments for the fucntion "hlua_channel_get_yield". */
3378__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3379{
3380 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3381 int len = -1;
3382
3383 if (lua_gettop(L) > 2)
3384 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3385 if (lua_gettop(L) >= 2) {
3386 len = MAY_LJMP(luaL_checkinteger(L, 2));
3387 lua_pop(L, 1);
3388 }
3389
3390 /* Confirm or set the required length */
3391 lua_pushinteger(L, len);
3392
3393 /* Initialise the string catenation. */
3394 luaL_buffinit(L, &appctx->b);
3395
3396 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3397}
3398
3399/* Append data in the output side of the buffer. This data is immediatly
3400 * sent. The fcuntion returns the ammount of data writed. If the buffer
3401 * cannot contains the data, the function yield. The function returns -1
3402 * if the channel is closed.
3403 */
3404__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3405{
3406 size_t len;
3407 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3408 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3409 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3410 struct stream_interface *si = appctx->appctx->owner;
3411 struct channel *chn = si_ic(si);
3412 int max;
3413
3414 /* Get the max amount of data which can write as input in the channel. */
3415 max = channel_recv_max(chn);
3416 if (max > (len - l))
3417 max = len - l;
3418
3419 /* Copy data. */
3420 bi_putblk(chn, str + l, max);
3421
3422 /* update counters. */
3423 l += max;
3424 lua_pop(L, 1);
3425 lua_pushinteger(L, l);
3426
3427 /* If some data is not send, declares the situation to the
3428 * applet, and returns a yield.
3429 */
3430 if (l < len) {
3431 si_applet_cant_put(si);
3432 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3433 }
3434
3435 return 1;
3436}
3437
3438/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3439 * yield the LUA process, and resume it without checking the
3440 * input arguments.
3441 */
3442__LJMP static int hlua_applet_tcp_send(lua_State *L)
3443{
3444 MAY_LJMP(check_args(L, 2, "send"));
3445 lua_pushinteger(L, 0);
3446
3447 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3448}
3449
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003450/*
3451 *
3452 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003453 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003454 *
3455 *
3456 */
3457
3458/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003459 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003460 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003461__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003462{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003463 return (struct hlua_appctx *)MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003464}
3465
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003466/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003467 * according with a current TXN.
3468 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003469static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003470{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003471 struct hlua_appctx *appctx;
3472 struct stream_interface *si = ctx->owner;
3473 struct stream *s = si_strm(si);
3474 struct proxy *px = s->be;
3475 struct http_txn *txn = s->txn;
3476 const char *path;
3477 const char *end;
3478 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003479
3480 /* Check stack size. */
3481 if (!lua_checkstack(L, 3))
3482 return 0;
3483
3484 /* Create the object: obj[0] = userdata.
3485 * Note that the base of the Converters object is the
3486 * same than the TXN object.
3487 */
3488 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003489 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003490 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003491 appctx->appctx = ctx;
3492 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
3493 appctx->htxn.s = s;
3494 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003495
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003496 /* Create the "f" field that contains a list of fetches. */
3497 lua_pushstring(L, "f");
3498 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3499 return 0;
3500 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003501
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003502 /* Create the "sf" field that contains a list of stringsafe fetches. */
3503 lua_pushstring(L, "sf");
3504 if (!hlua_fetches_new(L, &appctx->htxn, 1))
3505 return 0;
3506 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003507
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003508 /* Create the "c" field that contains a list of converters. */
3509 lua_pushstring(L, "c");
3510 if (!hlua_converters_new(L, &appctx->htxn, 0))
3511 return 0;
3512 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003513
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003514 /* Create the "sc" field that contains a list of stringsafe converters. */
3515 lua_pushstring(L, "sc");
3516 if (!hlua_converters_new(L, &appctx->htxn, 1))
3517 return 0;
3518 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003519
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003520 /* Stores the request method. */
3521 lua_pushstring(L, "method");
3522 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3523 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003524
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003525 /* Stores the http version. */
3526 lua_pushstring(L, "version");
3527 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3528 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003529
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003530 /* Get path and qs */
3531 path = http_get_path(txn);
3532 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3533 p = path;
3534 while (p < end && *p != '?')
3535 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003536
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003537 /* Stores the request path. */
3538 lua_pushstring(L, "path");
3539 lua_pushlstring(L, path, p - path);
3540 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003541
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003542 /* Stores the query string. */
3543 lua_pushstring(L, "qs");
3544 if (*p == '?')
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003545 p++;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003546 lua_pushlstring(L, p, end - p);
3547 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003548
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003549 /* Stores the request path. */
3550 lua_pushstring(L, "length");
3551 lua_pushinteger(L, txn->req.body_len);
3552 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003553
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003554 /* Create an array of HTTP request headers. */
3555 lua_pushstring(L, "headers");
3556 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3557 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003558
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003559 /* Create an empty array of HTTP request headers. */
3560 lua_pushstring(L, "response");
3561 lua_newtable(L);
3562 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003563
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003564 /* Pop a class stream metatable and affect it to the table. */
3565 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3566 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003567
3568 return 1;
3569}
3570
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003571/* If expected data not yet available, it returns a yield. This function
3572 * consumes the data in the buffer. It returns a string containing the
3573 * data. This string can be empty.
3574 */
3575__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003576{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003577 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3578 struct stream_interface *si = appctx->appctx->owner;
3579 struct channel *chn = si_ic(si);
3580 int ret;
3581 char *blk1;
3582 int len1;
3583 char *blk2;
3584 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003585
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003586 /* Maybe we cant send a 100-continue ? */
3587 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3588 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3589 /* if ret == -2 or -3 the channel closed or the message si too
3590 * big for the buffers. We cant send anything. So, we ignoring
3591 * the error, considers that the 100-continue is sent, and try
3592 * to receive.
3593 * If ret is -1, we dont have room in the buffer, so we yield.
3594 */
3595 if (ret == -1) {
3596 si_applet_cant_put(si);
3597 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3598 }
3599 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3600 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003601
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003602 /* Check for the end of the data. */
3603 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3604 luaL_pushresult(&appctx->b);
3605 return 1;
3606 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003607
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003608 /* Read the maximum amount of data avalaible. */
3609 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003610
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003611 /* Data not yet avalaible. return yield. */
3612 if (ret == 0) {
3613 si_applet_cant_get(si);
3614 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3615 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003616
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003617 /* End of data: commit the total strings and return. */
3618 if (ret < 0) {
3619 luaL_pushresult(&appctx->b);
3620 return 1;
3621 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003622
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003623 /* Ensure that the block 2 length is usable. */
3624 if (ret == 1)
3625 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003626
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003627 /* Copy the fisrt block caping to the length required. */
3628 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3629 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3630 luaL_addlstring(&appctx->b, blk1, len1);
3631 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003632
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003633 /* Copy the second block. */
3634 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3635 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3636 luaL_addlstring(&appctx->b, blk2, len2);
3637 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003638
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003639 /* Consume input channel output buffer data. */
3640 bo_skip(si_oc(si), len1 + len2);
3641 luaL_pushresult(&appctx->b);
3642 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003643}
3644
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003645/* Check arguments for the fucntion "hlua_channel_get_yield". */
3646__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003647{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003648 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003649
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003650 /* Initialise the string catenation. */
3651 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003652
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003653 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003654}
3655
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003656/* If expected data not yet available, it returns a yield. This function
3657 * consumes the data in the buffer. It returns a string containing the
3658 * data. This string can be empty.
3659 */
3660__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003661{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003662 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3663 struct stream_interface *si = appctx->appctx->owner;
3664 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3665 struct channel *chn = si_ic(si);
3666 int ret;
3667 char *blk1;
3668 int len1;
3669 char *blk2;
3670 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003671
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003672 /* Maybe we cant send a 100-continue ? */
3673 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3674 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3675 /* if ret == -2 or -3 the channel closed or the message si too
3676 * big for the buffers. We cant send anything. So, we ignoring
3677 * the error, considers that the 100-continue is sent, and try
3678 * to receive.
3679 * If ret is -1, we dont have room in the buffer, so we yield.
3680 */
3681 if (ret == -1) {
3682 si_applet_cant_put(si);
3683 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3684 }
3685 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3686 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003687
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003688 /* Read the maximum amount of data avalaible. */
3689 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003690
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003691 /* Data not yet avalaible. return yield. */
3692 if (ret == 0) {
3693 si_applet_cant_get(si);
3694 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3695 }
3696
3697 /* End of data: commit the total strings and return. */
3698 if (ret < 0) {
3699 luaL_pushresult(&appctx->b);
3700 return 1;
3701 }
3702
3703 /* Ensure that the block 2 length is usable. */
3704 if (ret == 1)
3705 len2 = 0;
3706
3707 /* Copy the fisrt block caping to the length required. */
3708 if (len1 > len)
3709 len1 = len;
3710 luaL_addlstring(&appctx->b, blk1, len1);
3711 len -= len1;
3712
3713 /* Copy the second block. */
3714 if (len2 > len)
3715 len2 = len;
3716 luaL_addlstring(&appctx->b, blk2, len2);
3717 len -= len2;
3718
3719 /* Consume input channel output buffer data. */
3720 bo_skip(si_oc(si), len1 + len2);
3721 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
3722 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
3723
3724 /* If we are no other data avalaible, yield waiting for new data. */
3725 if (len > 0) {
3726 lua_pushinteger(L, len);
3727 lua_replace(L, 2);
3728 si_applet_cant_get(si);
3729 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3730 }
3731
3732 /* return the result. */
3733 luaL_pushresult(&appctx->b);
3734 return 1;
3735}
3736
3737/* Check arguments for the fucntion "hlua_channel_get_yield". */
3738__LJMP static int hlua_applet_http_recv(lua_State *L)
3739{
3740 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3741 int len = -1;
3742
3743 /* Check arguments. */
3744 if (lua_gettop(L) > 2)
3745 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3746 if (lua_gettop(L) >= 2) {
3747 len = MAY_LJMP(luaL_checkinteger(L, 2));
3748 lua_pop(L, 1);
3749 }
3750
3751 /* Check the required length */
3752 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3753 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3754 lua_pushinteger(L, len);
3755
3756 /* Initialise the string catenation. */
3757 luaL_buffinit(L, &appctx->b);
3758
3759 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
3760}
3761
3762/* Append data in the output side of the buffer. This data is immediatly
3763 * sent. The fcuntion returns the ammount of data writed. If the buffer
3764 * cannot contains the data, the function yield. The function returns -1
3765 * if the channel is closed.
3766 */
3767__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
3768{
3769 size_t len;
3770 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3771 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3772 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3773 struct stream_interface *si = appctx->appctx->owner;
3774 struct channel *chn = si_ic(si);
3775 int max;
3776
3777 /* Get the max amount of data which can write as input in the channel. */
3778 max = channel_recv_max(chn);
3779 if (max > (len - l))
3780 max = len - l;
3781
3782 /* Copy data. */
3783 bi_putblk(chn, str + l, max);
3784
3785 /* update counters. */
3786 l += max;
3787 lua_pop(L, 1);
3788 lua_pushinteger(L, l);
3789
3790 /* If some data is not send, declares the situation to the
3791 * applet, and returns a yield.
3792 */
3793 if (l < len) {
3794 si_applet_cant_put(si);
3795 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
3796 }
3797
3798 return 1;
3799}
3800
3801/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
3802 * yield the LUA process, and resume it without checking the
3803 * input arguments.
3804 */
3805__LJMP static int hlua_applet_http_send(lua_State *L)
3806{
3807 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3808 size_t len;
3809 char hex[10];
3810
3811 MAY_LJMP(luaL_checklstring(L, 2, &len));
3812
3813 /* If transfer encoding chunked is selected, we surround the data
3814 * by chunk data.
3815 */
3816 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
3817 snprintf(hex, 9, "%x", (unsigned int)len);
3818 lua_pushfstring(L, "%s\r\n", hex);
3819 lua_insert(L, 2); /* swap the last 2 entries. */
3820 lua_pushstring(L, "\r\n");
3821 lua_concat(L, 3);
3822 }
3823
3824 /* This interger is used for followinf the amount of data sent. */
3825 lua_pushinteger(L, 0);
3826
3827 /* We want to send some data. Headers must be sent. */
3828 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
3829 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
3830 WILL_LJMP(lua_error(L));
3831 }
3832
3833 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
3834}
3835
3836__LJMP static int hlua_applet_http_addheader(lua_State *L)
3837{
3838 const char *name;
3839 int ret;
3840
3841 MAY_LJMP(hlua_checkapplet_http(L, 1));
3842 name = MAY_LJMP(luaL_checkstring(L, 2));
3843 MAY_LJMP(luaL_checkstring(L, 3));
3844
3845 /* Push in the stack the "response" entry. */
3846 ret = lua_getfield(L, 1, "response");
3847 if (ret != LUA_TTABLE) {
3848 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
3849 "is expected as an array. %s found", lua_typename(L, ret));
3850 WILL_LJMP(lua_error(L));
3851 }
3852
3853 /* check if the header is already registered if it is not
3854 * the case, register it.
3855 */
3856 ret = lua_getfield(L, -1, name);
3857 if (ret == LUA_TNIL) {
3858
3859 /* Entry not found. */
3860 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
3861
3862 /* Insert the new header name in the array in the top of the stack.
3863 * It left the new array in the top of the stack.
3864 */
3865 lua_newtable(L);
3866 lua_pushvalue(L, 2);
3867 lua_pushvalue(L, -2);
3868 lua_settable(L, -4);
3869
3870 } else if (ret != LUA_TTABLE) {
3871
3872 /* corruption error. */
3873 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
3874 "is expected as an array. %s found", name, lua_typename(L, ret));
3875 WILL_LJMP(lua_error(L));
3876 }
3877
3878 /* Now the top od thestack is an array of values. We push
3879 * the header value as new entry.
3880 */
3881 lua_pushvalue(L, 3);
3882 ret = lua_rawlen(L, -2);
3883 lua_rawseti(L, -2, ret + 1);
3884 lua_pushboolean(L, 1);
3885 return 1;
3886}
3887
3888__LJMP static int hlua_applet_http_status(lua_State *L)
3889{
3890 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3891 int status = MAY_LJMP(luaL_checkinteger(L, 2));
3892
3893 if (status < 100 || status > 599) {
3894 lua_pushboolean(L, 0);
3895 return 1;
3896 }
3897
3898 appctx->appctx->ctx.hlua_apphttp.status = status;
3899 lua_pushboolean(L, 1);
3900 return 1;
3901}
3902
3903/* We will build the status line and the headers of the HTTP response.
3904 * We will try send at once if its not possible, we give back the hand
3905 * waiting for more room.
3906 */
3907__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
3908{
3909 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3910 struct stream_interface *si = appctx->appctx->owner;
3911 struct channel *chn = si_ic(si);
3912 int ret;
3913 size_t len;
3914 const char *msg;
3915
3916 /* Get the message as the first argument on the stack. */
3917 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
3918
3919 /* Send the message at once. */
3920 ret = bi_putblk(chn, msg, len);
3921
3922 /* if ret == -2 or -3 the channel closed or the message si too
3923 * big for the buffers.
3924 */
3925 if (ret == -2 || ret == -3) {
3926 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
3927 WILL_LJMP(lua_error(L));
3928 }
3929
3930 /* If ret is -1, we dont have room in the buffer, so we yield. */
3931 if (ret == -1) {
3932 si_applet_cant_put(si);
3933 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
3934 }
3935
3936 /* Headers sent, set the flag. */
3937 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
3938 return 0;
3939}
3940
3941__LJMP static int hlua_applet_http_start_response(lua_State *L)
3942{
3943 struct chunk *tmp = get_trash_chunk();
3944 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3945 struct stream_interface *si = appctx->appctx->owner;
3946 struct stream *s = si_strm(si);
3947 struct http_txn *txn = s->txn;
3948 const char *name;
3949 const char *value;
3950 int id;
3951 int hdr_connection = 0;
3952 int hdr_contentlength = -1;
3953 int hdr_chunked = 0;
3954
3955 /* Use the same http version than the request. */
3956 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
3957 txn->req.flags & HTTP_MSGF_VER_11 ? '1' : '0',
3958 appctx->appctx->ctx.hlua_apphttp.status,
3959 get_reason(appctx->appctx->ctx.hlua_apphttp.status));
3960
3961 /* Get the array associated to the field "response" in the object AppletHTTP. */
3962 lua_pushvalue(L, 0);
3963 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
3964 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
3965 appctx->appctx->rule->arg.hlua_rule->fcn.name);
3966 WILL_LJMP(lua_error(L));
3967 }
3968
3969 /* Browse the list of headers. */
3970 lua_pushnil(L);
3971 while(lua_next(L, -2) != 0) {
3972
3973 /* We expect a string as -2. */
3974 if (lua_type(L, -2) != LUA_TSTRING) {
3975 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
3976 appctx->appctx->rule->arg.hlua_rule->fcn.name,
3977 lua_typename(L, lua_type(L, -2)));
3978 WILL_LJMP(lua_error(L));
3979 }
3980 name = lua_tostring(L, -2);
3981
3982 /* We expect an array as -1. */
3983 if (lua_type(L, -1) != LUA_TTABLE) {
3984 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
3985 appctx->appctx->rule->arg.hlua_rule->fcn.name,
3986 name,
3987 lua_typename(L, lua_type(L, -1)));
3988 WILL_LJMP(lua_error(L));
3989 }
3990
3991 /* Browse the table who is on the top of the stack. */
3992 lua_pushnil(L);
3993 while(lua_next(L, -2) != 0) {
3994
3995 /* We expect a number as -2. */
3996 if (lua_type(L, -2) != LUA_TNUMBER) {
3997 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
3998 appctx->appctx->rule->arg.hlua_rule->fcn.name,
3999 name,
4000 lua_typename(L, lua_type(L, -2)));
4001 WILL_LJMP(lua_error(L));
4002 }
4003 id = lua_tointeger(L, -2);
4004
4005 /* We expect a string as -2. */
4006 if (lua_type(L, -1) != LUA_TSTRING) {
4007 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4008 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4009 name, id,
4010 lua_typename(L, lua_type(L, -1)));
4011 WILL_LJMP(lua_error(L));
4012 }
4013 value = lua_tostring(L, -1);
4014
4015 /* Catenate a new header. */
4016 chunk_appendf(tmp, "%s: %s\r\n", name, value);
4017
4018 /* Protocol checks. */
4019
4020 /* Check if the header conneciton is present. */
4021 if (strcasecmp("connection", name) == 0)
4022 hdr_connection = 1;
4023
4024 /* Copy the header content length. The length conversion
4025 * is done without control. If it contains a ad value, this
4026 * is not our problem.
4027 */
4028 if (strcasecmp("content-length", name) == 0)
4029 hdr_contentlength = atoi(value);
4030
4031 /* Check if the client annouces a transfer-encoding chunked it self. */
4032 if (strcasecmp("transfer-encoding", name) == 0 &&
4033 strcasecmp("chunked", value) == 0)
4034 hdr_chunked = 1;
4035
4036 /* Remove the array from the stack, and get next element with a remaining string. */
4037 lua_pop(L, 1);
4038 }
4039
4040 /* Remove the array from the stack, and get next element with a remaining string. */
4041 lua_pop(L, 1);
4042 }
4043
4044 /* If the http protocol version is 1.1, we expect an header "connection" set
4045 * to "close" to be HAProxy/keeplive compliant. Otherwise, we expect nothing.
4046 * If the header conneciton is present, don't change it, if it is not present,
4047 * we must set.
4048 *
4049 * we set a "connection: close" header for ensuring that the keepalive will be
4050 * respected by haproxy. HAProcy considers that the application cloe the connection
4051 * and it keep the connection from the client open.
4052 */
4053 if (txn->req.flags & HTTP_MSGF_VER_11 && !hdr_connection)
4054 chunk_appendf(tmp, "Connection: close\r\n");
4055
4056 /* If we dont have a content-length set, we must announce a transfer enconding
4057 * chunked. This is required by haproxy for the keepalive compliance.
4058 * If the applet annouce a transfer-encoding chunked itslef, don't
4059 * do anything.
4060 */
4061 if (hdr_contentlength == -1 && hdr_chunked == 0) {
4062 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4063 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4064 }
4065
4066 /* Finalize headers. */
4067 chunk_appendf(tmp, "\r\n");
4068
4069 /* Remove the last entry and the array of headers */
4070 lua_pop(L, 2);
4071
4072 /* Push the headers block. */
4073 lua_pushlstring(L, tmp->str, tmp->len);
4074
4075 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4076}
4077
4078/*
4079 *
4080 *
4081 * Class HTTP
4082 *
4083 *
4084 */
4085
4086/* Returns a struct hlua_txn if the stack entry "ud" is
4087 * a class stream, otherwise it throws an error.
4088 */
4089__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4090{
4091 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
4092}
4093
4094/* This function creates and push in the stack a HTTP object
4095 * according with a current TXN.
4096 */
4097static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4098{
4099 struct hlua_txn *htxn;
4100
4101 /* Check stack size. */
4102 if (!lua_checkstack(L, 3))
4103 return 0;
4104
4105 /* Create the object: obj[0] = userdata.
4106 * Note that the base of the Converters object is the
4107 * same than the TXN object.
4108 */
4109 lua_newtable(L);
4110 htxn = lua_newuserdata(L, sizeof(*htxn));
4111 lua_rawseti(L, -2, 0);
4112
4113 htxn->s = txn->s;
4114 htxn->p = txn->p;
4115
4116 /* Pop a class stream metatable and affect it to the table. */
4117 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4118 lua_setmetatable(L, -2);
4119
4120 return 1;
4121}
4122
4123/* This function creates ans returns an array of HTTP headers.
4124 * This function does not fails. It is used as wrapper with the
4125 * 2 following functions.
4126 */
4127__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4128{
4129 const char *cur_ptr, *cur_next, *p;
4130 int old_idx, cur_idx;
4131 struct hdr_idx_elem *cur_hdr;
4132 const char *hn, *hv;
4133 int hnl, hvl;
4134 int type;
4135 const char *in;
4136 char *out;
4137 int len;
4138
4139 /* Create the table. */
4140 lua_newtable(L);
4141
4142 if (!htxn->s->txn)
4143 return 1;
4144
4145 /* Build array of headers. */
4146 old_idx = 0;
4147 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4148
4149 while (1) {
4150 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4151 if (!cur_idx)
4152 break;
4153 old_idx = cur_idx;
4154
4155 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4156 cur_ptr = cur_next;
4157 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4158
4159 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4160 * and the next header starts at cur_next. We'll check
4161 * this header in the list as well as against the default
4162 * rule.
4163 */
4164
4165 /* look for ': *'. */
4166 hn = cur_ptr;
4167 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4168 if (p >= cur_ptr+cur_hdr->len)
4169 continue;
4170 hnl = p - hn;
4171 p++;
4172 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4173 p++;
4174 if (p >= cur_ptr+cur_hdr->len)
4175 continue;
4176 hv = p;
4177 hvl = cur_ptr+cur_hdr->len-p;
4178
4179 /* Lowercase the key. Don't check the size of trash, it have
4180 * the size of one buffer and the input data contains in one
4181 * buffer.
4182 */
4183 out = trash.str;
4184 for (in=hn; in<hn+hnl; in++, out++)
4185 *out = tolower(*in);
4186 *out = '\0';
4187
4188 /* Check for existing entry:
4189 * assume that the table is on the top of the stack, and
4190 * push the key in the stack, the function lua_gettable()
4191 * perform the lookup.
4192 */
4193 lua_pushlstring(L, trash.str, hnl);
4194 lua_gettable(L, -2);
4195 type = lua_type(L, -1);
4196
4197 switch (type) {
4198 case LUA_TNIL:
4199 /* Table not found, create it. */
4200 lua_pop(L, 1); /* remove the nil value. */
4201 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4202 lua_newtable(L); /* create and push empty table. */
4203 lua_pushlstring(L, hv, hvl); /* push header value. */
4204 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4205 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4206 break;
4207
4208 case LUA_TTABLE:
4209 /* Entry found: push the value in the table. */
4210 len = lua_rawlen(L, -1);
4211 lua_pushlstring(L, hv, hvl); /* push header value. */
4212 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4213 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4214 break;
4215
4216 default:
4217 /* Other cases are errors. */
4218 hlua_pusherror(L, "internal error during the parsing of headers.");
4219 WILL_LJMP(lua_error(L));
4220 }
4221 }
4222
4223 return 1;
4224}
4225
4226__LJMP static int hlua_http_req_get_headers(lua_State *L)
4227{
4228 struct hlua_txn *htxn;
4229
4230 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4231 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4232
4233 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4234}
4235
4236__LJMP static int hlua_http_res_get_headers(lua_State *L)
4237{
4238 struct hlua_txn *htxn;
4239
4240 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4241 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4242
4243 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4244}
4245
4246/* This function replace full header, or just a value in
4247 * the request or in the response. It is a wrapper fir the
4248 * 4 following functions.
4249 */
4250__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4251 struct http_msg *msg, int action)
4252{
4253 size_t name_len;
4254 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4255 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4256 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4257 struct my_regex re;
4258
4259 if (!regex_comp(reg, &re, 1, 1, NULL))
4260 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4261
4262 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4263 regex_free(&re);
4264 return 0;
4265}
4266
4267__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4268{
4269 struct hlua_txn *htxn;
4270
4271 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4272 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4273
4274 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4275}
4276
4277__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4278{
4279 struct hlua_txn *htxn;
4280
4281 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4282 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4283
4284 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4285}
4286
4287__LJMP static int hlua_http_req_rep_val(lua_State *L)
4288{
4289 struct hlua_txn *htxn;
4290
4291 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4292 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4293
4294 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4295}
4296
4297__LJMP static int hlua_http_res_rep_val(lua_State *L)
4298{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004299 struct hlua_txn *htxn;
4300
4301 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4302 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4303
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004304 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004305}
4306
4307/* This function deletes all the occurences of an header.
4308 * It is a wrapper for the 2 following functions.
4309 */
4310__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4311{
4312 size_t len;
4313 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4314 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004315 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004316
4317 ctx.idx = 0;
4318 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4319 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4320 return 0;
4321}
4322
4323__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4324{
4325 struct hlua_txn *htxn;
4326
4327 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4328 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4329
Willy Tarreaueee5b512015-04-03 23:46:31 +02004330 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004331}
4332
4333__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4334{
4335 struct hlua_txn *htxn;
4336
4337 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4338 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4339
Willy Tarreaueee5b512015-04-03 23:46:31 +02004340 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004341}
4342
4343/* This function adds an header. It is a wrapper used by
4344 * the 2 following functions.
4345 */
4346__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4347{
4348 size_t name_len;
4349 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4350 size_t value_len;
4351 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4352 char *p;
4353
4354 /* Check length. */
4355 trash.len = value_len + name_len + 2;
4356 if (trash.len > trash.size)
4357 return 0;
4358
4359 /* Creates the header string. */
4360 p = trash.str;
4361 memcpy(p, name, name_len);
4362 p += name_len;
4363 *p = ':';
4364 p++;
4365 *p = ' ';
4366 p++;
4367 memcpy(p, value, value_len);
4368
Willy Tarreaueee5b512015-04-03 23:46:31 +02004369 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004370 trash.str, trash.len) != 0);
4371
4372 return 0;
4373}
4374
4375__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4376{
4377 struct hlua_txn *htxn;
4378
4379 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4380 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4381
Willy Tarreaueee5b512015-04-03 23:46:31 +02004382 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004383}
4384
4385__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4386{
4387 struct hlua_txn *htxn;
4388
4389 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4390 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4391
Willy Tarreaueee5b512015-04-03 23:46:31 +02004392 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004393}
4394
4395static int hlua_http_req_set_hdr(lua_State *L)
4396{
4397 struct hlua_txn *htxn;
4398
4399 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4400 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4401
Willy Tarreaueee5b512015-04-03 23:46:31 +02004402 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4403 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004404}
4405
4406static int hlua_http_res_set_hdr(lua_State *L)
4407{
4408 struct hlua_txn *htxn;
4409
4410 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4411 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4412
Willy Tarreaueee5b512015-04-03 23:46:31 +02004413 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4414 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004415}
4416
4417/* This function set the method. */
4418static int hlua_http_req_set_meth(lua_State *L)
4419{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004420 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004421 size_t name_len;
4422 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004423
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004424 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004425 return 1;
4426}
4427
4428/* This function set the method. */
4429static int hlua_http_req_set_path(lua_State *L)
4430{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004431 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004432 size_t name_len;
4433 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004434 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004435 return 1;
4436}
4437
4438/* This function set the query-string. */
4439static int hlua_http_req_set_query(lua_State *L)
4440{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004441 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004442 size_t name_len;
4443 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004444
4445 /* Check length. */
4446 if (name_len > trash.size - 1) {
4447 lua_pushboolean(L, 0);
4448 return 1;
4449 }
4450
4451 /* Add the mark question as prefix. */
4452 chunk_reset(&trash);
4453 trash.str[trash.len++] = '?';
4454 memcpy(trash.str + trash.len, name, name_len);
4455 trash.len += name_len;
4456
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004457 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004458 return 1;
4459}
4460
4461/* This function set the uri. */
4462static int hlua_http_req_set_uri(lua_State *L)
4463{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004464 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004465 size_t name_len;
4466 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004467
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004468 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004469 return 1;
4470}
4471
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004472/* This function set the response code. */
4473static int hlua_http_res_set_status(lua_State *L)
4474{
4475 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4476 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
4477
4478 http_set_status(code, htxn->s);
4479 return 0;
4480}
4481
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004482/*
4483 *
4484 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004485 * Class TXN
4486 *
4487 *
4488 */
4489
4490/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004491 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004492 */
4493__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4494{
4495 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
4496}
4497
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004498__LJMP static int hlua_set_var(lua_State *L)
4499{
4500 struct hlua_txn *htxn;
4501 const char *name;
4502 size_t len;
4503 struct sample smp;
4504
4505 MAY_LJMP(check_args(L, 3, "set_var"));
4506
4507 /* It is useles to retrieve the stream, but this function
4508 * runs only in a stream context.
4509 */
4510 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4511 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4512
4513 /* Converts the third argument in a sample. */
4514 hlua_lua2smp(L, 3, &smp);
4515
4516 /* Store the sample in a variable. */
4517 vars_set_by_name(name, len, htxn->s, &smp);
4518 return 0;
4519}
4520
4521__LJMP static int hlua_get_var(lua_State *L)
4522{
4523 struct hlua_txn *htxn;
4524 const char *name;
4525 size_t len;
4526 struct sample smp;
4527
4528 MAY_LJMP(check_args(L, 2, "get_var"));
4529
4530 /* It is useles to retrieve the stream, but this function
4531 * runs only in a stream context.
4532 */
4533 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4534 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4535
4536 if (!vars_get_by_name(name, len, htxn->s, &smp)) {
4537 lua_pushnil(L);
4538 return 1;
4539 }
4540
4541 return hlua_smp2lua(L, &smp);
4542}
4543
Willy Tarreau59551662015-03-10 14:23:13 +01004544__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004545{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004546 struct hlua *hlua;
4547
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004548 MAY_LJMP(check_args(L, 2, "set_priv"));
4549
Willy Tarreau87b09662015-04-03 00:22:06 +02004550 /* It is useles to retrieve the stream, but this function
4551 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004552 */
4553 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004554 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004555
4556 /* Remove previous value. */
4557 if (hlua->Mref != -1)
4558 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
4559
4560 /* Get and store new value. */
4561 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4562 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4563
4564 return 0;
4565}
4566
Willy Tarreau59551662015-03-10 14:23:13 +01004567__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004568{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004569 struct hlua *hlua;
4570
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004571 MAY_LJMP(check_args(L, 1, "get_priv"));
4572
Willy Tarreau87b09662015-04-03 00:22:06 +02004573 /* It is useles to retrieve the stream, but this function
4574 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004575 */
4576 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004577 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004578
4579 /* Push configuration index in the stack. */
4580 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4581
4582 return 1;
4583}
4584
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004585/* Create stack entry containing a class TXN. This function
4586 * return 0 if the stack does not contains free slots,
4587 * otherwise it returns 1.
4588 */
Willy Tarreau15e91e12015-04-04 00:52:09 +02004589static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004590{
Willy Tarreaude491382015-04-06 11:04:28 +02004591 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004592
4593 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004594 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004595 return 0;
4596
4597 /* NOTE: The allocation never fails. The failure
4598 * throw an error, and the function never returns.
4599 * if the throw is not avalaible, the process is aborted.
4600 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004601 /* Create the object: obj[0] = userdata. */
4602 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004603 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004604 lua_rawseti(L, -2, 0);
4605
Willy Tarreaude491382015-04-06 11:04:28 +02004606 htxn->s = s;
4607 htxn->p = p;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004608
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004609 /* Create the "f" field that contains a list of fetches. */
4610 lua_pushstring(L, "f");
Willy Tarreaude491382015-04-06 11:04:28 +02004611 if (!hlua_fetches_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004612 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004613 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004614
4615 /* Create the "sf" field that contains a list of stringsafe fetches. */
4616 lua_pushstring(L, "sf");
Willy Tarreaude491382015-04-06 11:04:28 +02004617 if (!hlua_fetches_new(L, htxn, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004618 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004619 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004620
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004621 /* Create the "c" field that contains a list of converters. */
4622 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004623 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004624 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004625 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004626
4627 /* Create the "sc" field that contains a list of stringsafe converters. */
4628 lua_pushstring(L, "sc");
Willy Tarreaude491382015-04-06 11:04:28 +02004629 if (!hlua_converters_new(L, htxn, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004630 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004631 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004632
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004633 /* Create the "req" field that contains the request channel object. */
4634 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004635 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004636 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004637 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004638
4639 /* Create the "res" field that contains the response channel object. */
4640 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004641 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004642 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004643 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004644
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004645 /* Creates the HTTP object is the current proxy allows http. */
4646 lua_pushstring(L, "http");
4647 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02004648 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004649 return 0;
4650 }
4651 else
4652 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004653 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004654
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004655 /* Pop a class sesison metatable and affect it to the userdata. */
4656 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
4657 lua_setmetatable(L, -2);
4658
4659 return 1;
4660}
4661
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004662__LJMP static int hlua_txn_deflog(lua_State *L)
4663{
4664 const char *msg;
4665 struct hlua_txn *htxn;
4666
4667 MAY_LJMP(check_args(L, 2, "deflog"));
4668 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4669 msg = MAY_LJMP(luaL_checkstring(L, 2));
4670
4671 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
4672 return 0;
4673}
4674
4675__LJMP static int hlua_txn_log(lua_State *L)
4676{
4677 int level;
4678 const char *msg;
4679 struct hlua_txn *htxn;
4680
4681 MAY_LJMP(check_args(L, 3, "log"));
4682 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4683 level = MAY_LJMP(luaL_checkinteger(L, 2));
4684 msg = MAY_LJMP(luaL_checkstring(L, 3));
4685
4686 if (level < 0 || level >= NB_LOG_LEVELS)
4687 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4688
4689 hlua_sendlog(htxn->s->be, level, msg);
4690 return 0;
4691}
4692
4693__LJMP static int hlua_txn_log_debug(lua_State *L)
4694{
4695 const char *msg;
4696 struct hlua_txn *htxn;
4697
4698 MAY_LJMP(check_args(L, 2, "Debug"));
4699 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4700 msg = MAY_LJMP(luaL_checkstring(L, 2));
4701 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
4702 return 0;
4703}
4704
4705__LJMP static int hlua_txn_log_info(lua_State *L)
4706{
4707 const char *msg;
4708 struct hlua_txn *htxn;
4709
4710 MAY_LJMP(check_args(L, 2, "Info"));
4711 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4712 msg = MAY_LJMP(luaL_checkstring(L, 2));
4713 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
4714 return 0;
4715}
4716
4717__LJMP static int hlua_txn_log_warning(lua_State *L)
4718{
4719 const char *msg;
4720 struct hlua_txn *htxn;
4721
4722 MAY_LJMP(check_args(L, 2, "Warning"));
4723 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4724 msg = MAY_LJMP(luaL_checkstring(L, 2));
4725 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
4726 return 0;
4727}
4728
4729__LJMP static int hlua_txn_log_alert(lua_State *L)
4730{
4731 const char *msg;
4732 struct hlua_txn *htxn;
4733
4734 MAY_LJMP(check_args(L, 2, "Alert"));
4735 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4736 msg = MAY_LJMP(luaL_checkstring(L, 2));
4737 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
4738 return 0;
4739}
4740
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004741__LJMP static int hlua_txn_set_loglevel(lua_State *L)
4742{
4743 struct hlua_txn *htxn;
4744 int ll;
4745
4746 MAY_LJMP(check_args(L, 2, "set_loglevel"));
4747 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4748 ll = MAY_LJMP(luaL_checkinteger(L, 2));
4749
4750 if (ll < 0 || ll > 7)
4751 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
4752
4753 htxn->s->logs.level = ll;
4754 return 0;
4755}
4756
4757__LJMP static int hlua_txn_set_tos(lua_State *L)
4758{
4759 struct hlua_txn *htxn;
4760 struct connection *cli_conn;
4761 int tos;
4762
4763 MAY_LJMP(check_args(L, 2, "set_tos"));
4764 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4765 tos = MAY_LJMP(luaL_checkinteger(L, 2));
4766
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004767 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004768 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
4769
4770 return 0;
4771}
4772
4773__LJMP static int hlua_txn_set_mark(lua_State *L)
4774{
4775#ifdef SO_MARK
4776 struct hlua_txn *htxn;
4777 struct connection *cli_conn;
4778 int mark;
4779
4780 MAY_LJMP(check_args(L, 2, "set_mark"));
4781 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4782 mark = MAY_LJMP(luaL_checkinteger(L, 2));
4783
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004784 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02004785 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004786#endif
4787 return 0;
4788}
4789
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004790/* This function is an Lua binding that send pending data
4791 * to the client, and close the stream interface.
4792 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004793__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004794{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004795 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01004796 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004797
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004798 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004799 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004800
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004801 ic = &htxn->s->req;
4802 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01004803
Willy Tarreau630ef452015-08-28 10:06:15 +02004804 if (htxn->s->txn) {
4805 /* HTTP mode, let's stay in sync with the stream */
4806 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
4807 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
4808 htxn->s->txn->req.sov = 0;
4809 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
4810 oc->analysers = AN_RES_HTTP_XFER_BODY;
4811 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
4812 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
4813
4814 /* Trim any possible response */
4815 oc->buf->i = 0;
4816 htxn->s->txn->rsp.next = htxn->s->txn->rsp.sov = 0;
4817
4818 /* Note that if we want to support keep-alive, we need
4819 * to bypass the close/shutr_now calls below, but that
4820 * may only be done if the HTTP request was already
4821 * processed and the connection header is known (ie
4822 * not during TCP rules).
4823 */
4824 }
4825
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004826 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01004827 channel_abort(ic);
4828 channel_auto_close(ic);
4829 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004830
4831 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01004832 channel_auto_read(oc);
4833 channel_auto_close(oc);
4834 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004835
Willy Tarreau0458b082015-08-28 09:40:04 +02004836 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004837
4838 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004839 return 0;
4840}
4841
4842__LJMP static int hlua_log(lua_State *L)
4843{
4844 int level;
4845 const char *msg;
4846
4847 MAY_LJMP(check_args(L, 2, "log"));
4848 level = MAY_LJMP(luaL_checkinteger(L, 1));
4849 msg = MAY_LJMP(luaL_checkstring(L, 2));
4850
4851 if (level < 0 || level >= NB_LOG_LEVELS)
4852 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4853
4854 hlua_sendlog(NULL, level, msg);
4855 return 0;
4856}
4857
4858__LJMP static int hlua_log_debug(lua_State *L)
4859{
4860 const char *msg;
4861
4862 MAY_LJMP(check_args(L, 1, "debug"));
4863 msg = MAY_LJMP(luaL_checkstring(L, 1));
4864 hlua_sendlog(NULL, LOG_DEBUG, msg);
4865 return 0;
4866}
4867
4868__LJMP static int hlua_log_info(lua_State *L)
4869{
4870 const char *msg;
4871
4872 MAY_LJMP(check_args(L, 1, "info"));
4873 msg = MAY_LJMP(luaL_checkstring(L, 1));
4874 hlua_sendlog(NULL, LOG_INFO, msg);
4875 return 0;
4876}
4877
4878__LJMP static int hlua_log_warning(lua_State *L)
4879{
4880 const char *msg;
4881
4882 MAY_LJMP(check_args(L, 1, "warning"));
4883 msg = MAY_LJMP(luaL_checkstring(L, 1));
4884 hlua_sendlog(NULL, LOG_WARNING, msg);
4885 return 0;
4886}
4887
4888__LJMP static int hlua_log_alert(lua_State *L)
4889{
4890 const char *msg;
4891
4892 MAY_LJMP(check_args(L, 1, "alert"));
4893 msg = MAY_LJMP(luaL_checkstring(L, 1));
4894 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004895 return 0;
4896}
4897
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004898__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004899{
4900 int wakeup_ms = lua_tointeger(L, -1);
4901 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004902 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004903 return 0;
4904}
4905
4906__LJMP static int hlua_sleep(lua_State *L)
4907{
4908 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004909 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004910
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004911 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004912
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004913 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004914 wakeup_ms = tick_add(now_ms, delay);
4915 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004916
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004917 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
4918 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004919}
4920
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004921__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004922{
4923 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004924 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004925
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004926 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004927
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004928 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004929 wakeup_ms = tick_add(now_ms, delay);
4930 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004931
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004932 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
4933 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004934}
4935
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004936/* This functionis an LUA binding. it permits to give back
4937 * the hand at the HAProxy scheduler. It is used when the
4938 * LUA processing consumes a lot of time.
4939 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004940__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004941{
4942 return 0;
4943}
4944
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004945__LJMP static int hlua_yield(lua_State *L)
4946{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004947 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
4948 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004949}
4950
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004951/* This function change the nice of the currently executed
4952 * task. It is used set low or high priority at the current
4953 * task.
4954 */
Willy Tarreau59551662015-03-10 14:23:13 +01004955__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004956{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004957 struct hlua *hlua;
4958 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004959
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004960 MAY_LJMP(check_args(L, 1, "set_nice"));
4961 hlua = hlua_gethlua(L);
4962 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004963
4964 /* If he task is not set, I'm in a start mode. */
4965 if (!hlua || !hlua->task)
4966 return 0;
4967
4968 if (nice < -1024)
4969 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004970 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004971 nice = 1024;
4972
4973 hlua->task->nice = nice;
4974 return 0;
4975}
4976
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004977/* This function is used as a calback of a task. It is called by the
4978 * HAProxy task subsystem when the task is awaked. The LUA runtime can
4979 * return an E_AGAIN signal, the emmiter of this signal must set a
4980 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004981 *
4982 * Task wrapper are longjmp safe because the only one Lua code
4983 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004984 */
4985static struct task *hlua_process_task(struct task *task)
4986{
4987 struct hlua *hlua = task->context;
4988 enum hlua_exec status;
4989
4990 /* We need to remove the task from the wait queue before executing
4991 * the Lua code because we don't know if it needs to wait for
4992 * another timer or not in the case of E_AGAIN.
4993 */
4994 task_delete(task);
4995
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004996 /* If it is the first call to the task, we must initialize the
4997 * execution timeouts.
4998 */
4999 if (!HLUA_IS_RUNNING(hlua))
Camilo Lopez685c0142015-08-02 19:07:28 -04005000 hlua->expire = tick_add_ifset(now_ms, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005001
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005002 /* Execute the Lua code. */
5003 status = hlua_ctx_resume(hlua, 1);
5004
5005 switch (status) {
5006 /* finished or yield */
5007 case HLUA_E_OK:
5008 hlua_ctx_destroy(hlua);
5009 task_delete(task);
5010 task_free(task);
5011 break;
5012
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005013 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5014 if (hlua->wake_time != TICK_ETERNITY)
5015 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005016 break;
5017
5018 /* finished with error. */
5019 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005020 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005021 hlua_ctx_destroy(hlua);
5022 task_delete(task);
5023 task_free(task);
5024 break;
5025
5026 case HLUA_E_ERR:
5027 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005028 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005029 hlua_ctx_destroy(hlua);
5030 task_delete(task);
5031 task_free(task);
5032 break;
5033 }
5034 return NULL;
5035}
5036
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005037/* This function is an LUA binding that register LUA function to be
5038 * executed after the HAProxy configuration parsing and before the
5039 * HAProxy scheduler starts. This function expect only one LUA
5040 * argument that is a function. This function returns nothing, but
5041 * throws if an error is encountered.
5042 */
5043__LJMP static int hlua_register_init(lua_State *L)
5044{
5045 struct hlua_init_function *init;
5046 int ref;
5047
5048 MAY_LJMP(check_args(L, 1, "register_init"));
5049
5050 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5051
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005052 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005053 if (!init)
5054 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5055
5056 init->function_ref = ref;
5057 LIST_ADDQ(&hlua_init_functions, &init->l);
5058 return 0;
5059}
5060
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005061/* This functio is an LUA binding. It permits to register a task
5062 * executed in parallel of the main HAroxy activity. The task is
5063 * created and it is set in the HAProxy scheduler. It can be called
5064 * from the "init" section, "post init" or during the runtime.
5065 *
5066 * Lua prototype:
5067 *
5068 * <none> core.register_task(<function>)
5069 */
5070static int hlua_register_task(lua_State *L)
5071{
5072 struct hlua *hlua;
5073 struct task *task;
5074 int ref;
5075
5076 MAY_LJMP(check_args(L, 1, "register_task"));
5077
5078 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5079
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005080 hlua = calloc(1, sizeof(*hlua));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005081 if (!hlua)
5082 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5083
5084 task = task_new();
5085 task->context = hlua;
5086 task->process = hlua_process_task;
5087
5088 if (!hlua_ctx_init(hlua, task))
5089 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5090
5091 /* Restore the function in the stack. */
5092 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5093 hlua->nargs = 0;
5094
5095 /* Schedule task. */
5096 task_schedule(task, now_ms);
5097
5098 return 0;
5099}
5100
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005101/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5102 * doesn't allow "yield" functions because the HAProxy engine cannot
5103 * resume converters.
5104 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005105static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005106{
5107 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005108 struct stream *stream = smp->strm;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005109
Willy Tarreau87b09662015-04-03 00:22:06 +02005110 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005111 * Lua context can be not initialized. This behavior
5112 * permits to save performances because a systematic
5113 * Lua initialization cause 5% performances loss.
5114 */
Willy Tarreau87b09662015-04-03 00:22:06 +02005115 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005116 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005117 return 0;
5118 }
5119
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005120 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005121 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005122
5123 /* The following Lua calls can fail. */
5124 if (!SET_SAFE_LJMP(stream->hlua.T)) {
5125 SEND_ERR(stream->be, "Lua converter '%s': critical error.\n", fcn->name);
5126 return 0;
5127 }
5128
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005129 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005130 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005131 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005132 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005133 return 0;
5134 }
5135
5136 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005137 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005138
5139 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005140 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005141 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005142 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005143 return 0;
5144 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005145 hlua_smp2lua(stream->hlua.T, smp);
5146 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005147
5148 /* push keywords in the stack. */
5149 if (arg_p) {
5150 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02005151 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005152 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005153 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005154 return 0;
5155 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005156 hlua_arg2lua(stream->hlua.T, arg_p);
5157 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005158 }
5159 }
5160
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005161 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02005162 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005163
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005164 /* At this point the execution is safe. */
5165 RESET_SAFE_LJMP(stream->hlua.T);
5166
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005167 /* Set the currently running flag. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005168 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005169 }
5170
5171 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005172 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005173 /* finished. */
5174 case HLUA_E_OK:
5175 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005176 hlua_lua2smp(stream->hlua.T, -1, smp);
5177 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005178 return 1;
5179
5180 /* yield. */
5181 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005182 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005183 return 0;
5184
5185 /* finished with error. */
5186 case HLUA_E_ERRMSG:
5187 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005188 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
5189 fcn->name, lua_tostring(stream->hlua.T, -1));
Willy Tarreau87b09662015-04-03 00:22:06 +02005190 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005191 return 0;
5192
5193 case HLUA_E_ERR:
5194 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005195 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005196
5197 default:
5198 return 0;
5199 }
5200}
5201
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005202/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5203 * doesn't allow "yield" functions because the HAProxy engine cannot
5204 * resume sample-fetches.
5205 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005206static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5207 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005208{
5209 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005210 struct stream *stream = smp->strm;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005211
Willy Tarreau87b09662015-04-03 00:22:06 +02005212 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005213 * Lua context can be not initialized. This behavior
5214 * permits to save performances because a systematic
5215 * Lua initialization cause 5% performances loss.
5216 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005217 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005218 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005219 return 0;
5220 }
5221
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005222 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005223 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005224
5225 /* The following Lua calls can fail. */
5226 if (!SET_SAFE_LJMP(stream->hlua.T)) {
5227 SEND_ERR(smp->px, "Lua sample-fetch '%s': critical error.\n", fcn->name);
5228 return 0;
5229 }
5230
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005231 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005232 if (!lua_checkstack(stream->hlua.T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005233 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005234 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005235 return 0;
5236 }
5237
5238 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005239 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005240
5241 /* push arguments in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005242 if (!hlua_txn_new(stream->hlua.T, stream, smp->px)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005243 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005244 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005245 return 0;
5246 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005247 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005248
5249 /* push keywords in the stack. */
5250 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5251 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005252 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005253 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005254 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005255 return 0;
5256 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005257 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005258 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005259 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005260 return 0;
5261 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005262 hlua_arg2lua(stream->hlua.T, arg_p);
5263 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005264 }
5265
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005266 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02005267 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005268
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005269 /* At this point the execution is safe. */
5270 RESET_SAFE_LJMP(stream->hlua.T);
5271
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005272 /* Set the currently running flag. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005273 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005274 }
5275
5276 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005277 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005278 /* finished. */
5279 case HLUA_E_OK:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005280 if (!hlua_check_proto(stream, !(smp->opt & SMP_OPT_DIR_REQ)))
5281 return 0;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005282 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005283 hlua_lua2smp(stream->hlua.T, -1, smp);
5284 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005285
5286 /* Set the end of execution flag. */
5287 smp->flags &= ~SMP_F_MAY_CHANGE;
5288 return 1;
5289
5290 /* yield. */
5291 case HLUA_E_AGAIN:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005292 hlua_check_proto(stream, !(smp->opt & SMP_OPT_DIR_REQ));
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005293 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005294 return 0;
5295
5296 /* finished with error. */
5297 case HLUA_E_ERRMSG:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005298 hlua_check_proto(stream, !(smp->opt & SMP_OPT_DIR_REQ));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005299 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005300 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
5301 fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005302 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005303 return 0;
5304
5305 case HLUA_E_ERR:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005306 hlua_check_proto(stream, !(smp->opt & SMP_OPT_DIR_REQ));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005307 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005308 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005309
5310 default:
5311 return 0;
5312 }
5313}
5314
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005315/* This function is an LUA binding used for registering
5316 * "sample-conv" functions. It expects a converter name used
5317 * in the haproxy configuration file, and an LUA function.
5318 */
5319__LJMP static int hlua_register_converters(lua_State *L)
5320{
5321 struct sample_conv_kw_list *sck;
5322 const char *name;
5323 int ref;
5324 int len;
5325 struct hlua_function *fcn;
5326
5327 MAY_LJMP(check_args(L, 2, "register_converters"));
5328
5329 /* First argument : converter name. */
5330 name = MAY_LJMP(luaL_checkstring(L, 1));
5331
5332 /* Second argument : lua function. */
5333 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5334
5335 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005336 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005337 if (!sck)
5338 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005339 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005340 if (!fcn)
5341 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5342
5343 /* Fill fcn. */
5344 fcn->name = strdup(name);
5345 if (!fcn->name)
5346 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5347 fcn->function_ref = ref;
5348
5349 /* List head */
5350 sck->list.n = sck->list.p = NULL;
5351
5352 /* converter keyword. */
5353 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005354 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005355 if (!sck->kw[0].kw)
5356 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5357
5358 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5359 sck->kw[0].process = hlua_sample_conv_wrapper;
5360 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
5361 sck->kw[0].val_args = NULL;
5362 sck->kw[0].in_type = SMP_T_STR;
5363 sck->kw[0].out_type = SMP_T_STR;
5364 sck->kw[0].private = fcn;
5365
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005366 /* Register this new converter */
5367 sample_register_convs(sck);
5368
5369 return 0;
5370}
5371
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005372/* This fucntion is an LUA binding used for registering
5373 * "sample-fetch" functions. It expects a converter name used
5374 * in the haproxy configuration file, and an LUA function.
5375 */
5376__LJMP static int hlua_register_fetches(lua_State *L)
5377{
5378 const char *name;
5379 int ref;
5380 int len;
5381 struct sample_fetch_kw_list *sfk;
5382 struct hlua_function *fcn;
5383
5384 MAY_LJMP(check_args(L, 2, "register_fetches"));
5385
5386 /* First argument : sample-fetch name. */
5387 name = MAY_LJMP(luaL_checkstring(L, 1));
5388
5389 /* Second argument : lua function. */
5390 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5391
5392 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005393 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005394 if (!sfk)
5395 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005396 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005397 if (!fcn)
5398 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5399
5400 /* Fill fcn. */
5401 fcn->name = strdup(name);
5402 if (!fcn->name)
5403 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5404 fcn->function_ref = ref;
5405
5406 /* List head */
5407 sfk->list.n = sfk->list.p = NULL;
5408
5409 /* sample-fetch keyword. */
5410 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005411 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005412 if (!sfk->kw[0].kw)
5413 return luaL_error(L, "lua out of memory error.");
5414
5415 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5416 sfk->kw[0].process = hlua_sample_fetch_wrapper;
5417 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
5418 sfk->kw[0].val_args = NULL;
5419 sfk->kw[0].out_type = SMP_T_STR;
5420 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5421 sfk->kw[0].val = 0;
5422 sfk->kw[0].private = fcn;
5423
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005424 /* Register this new fetch. */
5425 sample_register_fetches(sfk);
5426
5427 return 0;
5428}
5429
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005430/* This function is a wrapper to execute each LUA function declared
5431 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005432 * return ACT_RET_CONT if the processing is finished (with or without
5433 * error) and return ACT_RET_YIELD if the function must be called again
5434 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005435 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005436static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005437 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005438{
5439 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005440 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005441 int dir;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005442
5443 switch (rule->from) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005444 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = 0; break;
5445 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = 1; break;
5446 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = 0; break;
5447 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = 1; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005448 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005449 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005450 return ACT_RET_CONT;
5451 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005452
Willy Tarreau87b09662015-04-03 00:22:06 +02005453 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005454 * Lua context can be not initialized. This behavior
5455 * permits to save performances because a systematic
5456 * Lua initialization cause 5% performances loss.
5457 */
5458 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005459 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005460 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005461 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005462 }
5463
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005464 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01005465 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005466
5467 /* The following Lua calls can fail. */
5468 if (!SET_SAFE_LJMP(s->hlua.T)) {
5469 SEND_ERR(px, "Lua function '%s': critical error.\n",
5470 rule->arg.hlua_rule->fcn.name);
5471 return ACT_RET_CONT;
5472 }
5473
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005474 /* Check stack available size. */
5475 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005476 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005477 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005478 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005479 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005480 }
5481
5482 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005483 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005484
Willy Tarreau87b09662015-04-03 00:22:06 +02005485 /* Create and and push object stream in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02005486 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005487 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005488 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005489 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005490 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005491 }
5492 s->hlua.nargs = 1;
5493
5494 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005495 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005496 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005497 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005498 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005499 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005500 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005501 }
5502 lua_pushstring(s->hlua.T, *arg);
5503 s->hlua.nargs++;
5504 }
5505
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005506 /* Now the execution is safe. */
5507 RESET_SAFE_LJMP(s->hlua.T);
5508
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005509 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02005510 s->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005511
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005512 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01005513 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005514 }
5515
5516 /* Execute the function. */
Willy Tarreau528192d2015-09-27 10:48:01 +02005517 switch (hlua_ctx_resume(&s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005518 /* finished. */
5519 case HLUA_E_OK:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005520 if (!hlua_check_proto(s, dir))
5521 return ACT_RET_ERR;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005522 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005523
5524 /* yield. */
5525 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005526 /* Set timeout in the required channel. */
5527 if (s->hlua.wake_time != TICK_ETERNITY) {
5528 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005529 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005530 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005531 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005532 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005533 /* Some actions can be wake up when a "write" event
5534 * is detected on a response channel. This is useful
5535 * only for actions targetted on the requests.
5536 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01005537 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005538 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005539 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005540 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005541 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01005542 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005543 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005544 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005545
5546 /* finished with error. */
5547 case HLUA_E_ERRMSG:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005548 if (!hlua_check_proto(s, dir))
5549 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005550 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005551 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005552 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005553 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005554 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005555
5556 case HLUA_E_ERR:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005557 if (!hlua_check_proto(s, dir))
5558 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005559 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005560 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005561 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005562
5563 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005564 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005565 }
5566}
5567
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005568struct task *hlua_applet_wakeup(struct task *t)
5569{
5570 struct appctx *ctx = t->context;
5571 struct stream_interface *si = ctx->owner;
5572
5573 /* If the applet is wake up without any expected work, the sheduler
5574 * remove it from the run queue. This flag indicate that the applet
5575 * is waiting for write. If the buffer is full, the main processing
5576 * will send some data and after call the applet, otherwise it call
5577 * the applet ASAP.
5578 */
5579 si_applet_cant_put(si);
5580 appctx_wakeup(ctx);
5581 return NULL;
5582}
5583
5584static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5585{
5586 struct stream_interface *si = ctx->owner;
5587 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5588 struct task *task;
5589 char **arg;
5590
5591 HLUA_INIT(hlua);
5592 ctx->ctx.hlua_apptcp.flags = 0;
5593
5594 /* Create task used by signal to wakeup applets. */
5595 task = task_new();
5596 if (!task) {
5597 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5598 ctx->rule->arg.hlua_rule->fcn.name);
5599 return 0;
5600 }
5601 task->nice = 0;
5602 task->context = ctx;
5603 task->process = hlua_applet_wakeup;
5604 ctx->ctx.hlua_apptcp.task = task;
5605
5606 /* In the execution wrappers linked with a stream, the
5607 * Lua context can be not initialized. This behavior
5608 * permits to save performances because a systematic
5609 * Lua initialization cause 5% performances loss.
5610 */
5611 if (!hlua_ctx_init(hlua, task)) {
5612 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
5613 ctx->rule->arg.hlua_rule->fcn.name);
5614 return 0;
5615 }
5616
5617 /* Set timeout according with the applet configuration. */
5618 hlua->expire = tick_add_ifset(now_ms, ctx->applet->timeout);
5619
5620 /* The following Lua calls can fail. */
5621 if (!SET_SAFE_LJMP(hlua->T)) {
5622 SEND_ERR(px, "Lua applet tcp '%s': critical error.\n",
5623 ctx->rule->arg.hlua_rule->fcn.name);
5624 RESET_SAFE_LJMP(hlua->T);
5625 return 0;
5626 }
5627
5628 /* Check stack available size. */
5629 if (!lua_checkstack(hlua->T, 1)) {
5630 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5631 ctx->rule->arg.hlua_rule->fcn.name);
5632 RESET_SAFE_LJMP(hlua->T);
5633 return 0;
5634 }
5635
5636 /* Restore the function in the stack. */
5637 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5638
5639 /* Create and and push object stream in the stack. */
5640 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
5641 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5642 ctx->rule->arg.hlua_rule->fcn.name);
5643 RESET_SAFE_LJMP(hlua->T);
5644 return 0;
5645 }
5646 hlua->nargs = 1;
5647
5648 /* push keywords in the stack. */
5649 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5650 if (!lua_checkstack(hlua->T, 1)) {
5651 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5652 ctx->rule->arg.hlua_rule->fcn.name);
5653 RESET_SAFE_LJMP(hlua->T);
5654 return 0;
5655 }
5656 lua_pushstring(hlua->T, *arg);
5657 hlua->nargs++;
5658 }
5659
5660 RESET_SAFE_LJMP(hlua->T);
5661
5662 /* Wakeup the applet ASAP. */
5663 si_applet_cant_get(si);
5664 si_applet_cant_put(si);
5665
5666 return 1;
5667}
5668
5669static void hlua_applet_tcp_fct(struct appctx *ctx)
5670{
5671 struct stream_interface *si = ctx->owner;
5672 struct stream *strm = si_strm(si);
5673 struct channel *res = si_ic(si);
5674 struct act_rule *rule = ctx->rule;
5675 struct proxy *px = strm->be;
5676 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5677
5678 /* The applet execution is already done. */
5679 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
5680 return;
5681
5682 /* If the stream is disconnect or closed, ldo nothing. */
5683 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5684 return;
5685
5686 /* Execute the function. */
5687 switch (hlua_ctx_resume(hlua, 1)) {
5688 /* finished. */
5689 case HLUA_E_OK:
5690 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5691
5692 /* log time */
5693 strm->logs.tv_request = now;
5694
5695 /* eat the whole request */
5696 bo_skip(si_oc(si), si_ob(si)->o);
5697 res->flags |= CF_READ_NULL;
5698 si_shutr(si);
5699 return;
5700
5701 /* yield. */
5702 case HLUA_E_AGAIN:
5703 return;
5704
5705 /* finished with error. */
5706 case HLUA_E_ERRMSG:
5707 /* Display log. */
5708 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
5709 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
5710 lua_pop(hlua->T, 1);
5711 goto error;
5712
5713 case HLUA_E_ERR:
5714 /* Display log. */
5715 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
5716 rule->arg.hlua_rule->fcn.name);
5717 goto error;
5718
5719 default:
5720 goto error;
5721 }
5722
5723error:
5724
5725 /* For all other cases, just close the stream. */
5726 si_shutw(si);
5727 si_shutr(si);
5728 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5729}
5730
5731static void hlua_applet_tcp_release(struct appctx *ctx)
5732{
5733 task_free(ctx->ctx.hlua_apptcp.task);
5734 ctx->ctx.hlua_apptcp.task = NULL;
5735 hlua_ctx_destroy(&ctx->ctx.hlua_apptcp.hlua);
5736}
5737
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005738/* The function returns 1 if the initialisation is complete, 0 if
5739 * an errors occurs and -1 if more data are required for initializing
5740 * the applet.
5741 */
5742static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5743{
5744 struct stream_interface *si = ctx->owner;
5745 struct channel *req = si_oc(si);
5746 struct http_msg *msg;
5747 struct http_txn *txn;
5748 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5749 char **arg;
5750 struct hdr_ctx hdr;
5751 struct task *task;
5752 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
5753
5754 /* Wait for a full HTTP request. */
5755 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
5756 if (smp.flags & SMP_F_MAY_CHANGE)
5757 return -1;
5758 return 0;
5759 }
5760 txn = strm->txn;
5761 msg = &txn->req;
5762
5763 HLUA_INIT(hlua);
5764 ctx->ctx.hlua_apphttp.left_bytes = -1;
5765 ctx->ctx.hlua_apphttp.flags = 0;
5766
5767 /* Create task used by signal to wakeup applets. */
5768 task = task_new();
5769 if (!task) {
5770 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
5771 ctx->rule->arg.hlua_rule->fcn.name);
5772 return 0;
5773 }
5774 task->nice = 0;
5775 task->context = ctx;
5776 task->process = hlua_applet_wakeup;
5777 ctx->ctx.hlua_apphttp.task = task;
5778
5779 /* In the execution wrappers linked with a stream, the
5780 * Lua context can be not initialized. This behavior
5781 * permits to save performances because a systematic
5782 * Lua initialization cause 5% performances loss.
5783 */
5784 if (!hlua_ctx_init(hlua, task)) {
5785 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
5786 ctx->rule->arg.hlua_rule->fcn.name);
5787 return 0;
5788 }
5789
5790 /* Set timeout according with the applet configuration. */
5791 hlua->expire = tick_add_ifset(now_ms, ctx->applet->timeout);
5792
5793 /* The following Lua calls can fail. */
5794 if (!SET_SAFE_LJMP(hlua->T)) {
5795 SEND_ERR(px, "Lua applet http '%s': critical error.\n",
5796 ctx->rule->arg.hlua_rule->fcn.name);
5797 return 0;
5798 }
5799
5800 /* Check stack available size. */
5801 if (!lua_checkstack(hlua->T, 1)) {
5802 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5803 ctx->rule->arg.hlua_rule->fcn.name);
5804 RESET_SAFE_LJMP(hlua->T);
5805 return 0;
5806 }
5807
5808 /* Restore the function in the stack. */
5809 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5810
5811 /* Create and and push object stream in the stack. */
5812 if (!hlua_applet_http_new(hlua->T, ctx)) {
5813 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5814 ctx->rule->arg.hlua_rule->fcn.name);
5815 RESET_SAFE_LJMP(hlua->T);
5816 return 0;
5817 }
5818 hlua->nargs = 1;
5819
5820 /* Look for a 100-continue expected. */
5821 if (msg->flags & HTTP_MSGF_VER_11) {
5822 hdr.idx = 0;
5823 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
5824 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
5825 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
5826 }
5827
5828 /* push keywords in the stack. */
5829 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5830 if (!lua_checkstack(hlua->T, 1)) {
5831 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5832 ctx->rule->arg.hlua_rule->fcn.name);
5833 RESET_SAFE_LJMP(hlua->T);
5834 return 0;
5835 }
5836 lua_pushstring(hlua->T, *arg);
5837 hlua->nargs++;
5838 }
5839
5840 RESET_SAFE_LJMP(hlua->T);
5841
5842 /* Wakeup the applet when data is ready for read. */
5843 si_applet_cant_get(si);
5844
5845 return 1;
5846}
5847
5848static void hlua_applet_http_fct(struct appctx *ctx)
5849{
5850 struct stream_interface *si = ctx->owner;
5851 struct stream *strm = si_strm(si);
5852 struct channel *res = si_ic(si);
5853 struct channel *req = si_oc(si);
5854 struct act_rule *rule = ctx->rule;
5855 struct proxy *px = strm->be;
5856 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5857 char *blk1;
5858 int len1;
5859 char *blk2;
5860 int len2;
5861 int ret;
5862
5863 /* If the stream is disconnect or closed, ldo nothing. */
5864 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5865 return;
5866
5867 /* Set the currently running flag. */
5868 if (!HLUA_IS_RUNNING(hlua) &&
5869 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
5870
5871 /* enable the minimally required analyzers to handle keep-alive
5872 * and compression on the HTTP response
5873 */
5874 req->analysers = (req->analysers & AN_REQ_HTTP_BODY) |
5875 AN_REQ_HTTP_XFER_BODY | AN_REQ_HTTP_INNER;
5876
5877 /* Wait for full HTTP analysys. */
5878 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
5879 si_applet_cant_get(si);
5880 return;
5881 }
5882
5883 /* Store the max amount of bytes that we can read. */
5884 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
5885
5886 /* We need to flush the request header. This left the body
5887 * for the Lua.
5888 */
5889
5890 /* Read the maximum amount of data avalaible. */
5891 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
5892 if (ret == -1)
5893 return;
5894
5895 /* No data available, ask for more data. */
5896 if (ret == 1)
5897 len2 = 0;
5898 if (ret == 0)
5899 len1 = 0;
5900 if (len1 + len2 < strm->txn->req.eoh + 2) {
5901 si_applet_cant_get(si);
5902 return;
5903 }
5904
5905 /* skip the requests bytes. */
5906 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
5907 }
5908
5909 /* Executes The applet if it is not done. */
5910 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
5911
5912 /* Execute the function. */
5913 switch (hlua_ctx_resume(hlua, 1)) {
5914 /* finished. */
5915 case HLUA_E_OK:
5916 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
5917 break;
5918
5919 /* yield. */
5920 case HLUA_E_AGAIN:
5921 return;
5922
5923 /* finished with error. */
5924 case HLUA_E_ERRMSG:
5925 /* Display log. */
5926 SEND_ERR(px, "Lua applet http '%s': %s.\n",
5927 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
5928 lua_pop(hlua->T, 1);
5929 goto error;
5930
5931 case HLUA_E_ERR:
5932 /* Display log. */
5933 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
5934 rule->arg.hlua_rule->fcn.name);
5935 goto error;
5936
5937 default:
5938 goto error;
5939 }
5940 }
5941
5942 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
5943
5944 /* We must send the final chunk. */
5945 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
5946 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
5947
5948 /* sent last chunk at once. */
5949 ret = bi_putblk(res, "0\r\n\r\n", 5);
5950
5951 /* critical error. */
5952 if (ret == -2 || ret == -3) {
5953 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
5954 rule->arg.hlua_rule->fcn.name);
5955 goto error;
5956 }
5957
5958 /* no enough space error. */
5959 if (ret == -1) {
5960 si_applet_cant_put(si);
5961 return;
5962 }
5963
5964 /* set the last chunk sent. */
5965 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
5966 }
5967
5968 /* close the connection. */
5969
5970 /* status / log */
5971 strm->txn->status = ctx->ctx.hlua_apphttp.status;
5972 strm->logs.tv_request = now;
5973
5974 /* eat the whole request */
5975 bo_skip(si_oc(si), si_ob(si)->o);
5976 res->flags |= CF_READ_NULL;
5977 si_shutr(si);
5978
5979 return;
5980 }
5981
5982error:
5983
5984 /* If we are in HTTP mode, and we are not send any
5985 * data, return a 500 server error in best effort:
5986 * if there are no room avalaible in the buffer,
5987 * just close the connection.
5988 */
5989 bi_putblk(res, error_500, strlen(error_500));
5990 if (!(strm->flags & SF_ERR_MASK))
5991 strm->flags |= SF_ERR_RESOURCE;
5992 si_shutw(si);
5993 si_shutr(si);
5994 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
5995}
5996
5997static void hlua_applet_http_release(struct appctx *ctx)
5998{
5999 task_free(ctx->ctx.hlua_apphttp.task);
6000 ctx->ctx.hlua_apphttp.task = NULL;
6001 hlua_ctx_destroy(&ctx->ctx.hlua_apphttp.hlua);
6002}
6003
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006004/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6005 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006006 *
6007 * This function can fail with an abort() due to an Lua critical error.
6008 * We are in the configuration parsing process of HAProxy, this abort() is
6009 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006010 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006011static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6012 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006013{
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006014 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6015
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006016 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006017 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006018 if (!rule->arg.hlua_rule) {
6019 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006020 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006021 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006022
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006023 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006024 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006025
6026 /* TODO: later accept arguments. */
6027 rule->arg.hlua_rule->args = NULL;
6028
Thierry FOURNIER42148732015-09-02 17:17:33 +02006029 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006030 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006031 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006032}
6033
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006034static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6035 struct act_rule *rule, char **err)
6036{
6037 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6038
6039 /* Memory for the rule. */
6040 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6041 if (!rule->arg.hlua_rule) {
6042 memprintf(err, "out of memory error");
6043 return ACT_RET_PRS_ERR;
6044 }
6045
6046 /* Reference the Lua function and store the reference. */
6047 rule->arg.hlua_rule->fcn = *fcn;
6048
6049 /* TODO: later accept arguments. */
6050 rule->arg.hlua_rule->args = NULL;
6051
6052 /* Add applet pointer in the rule. */
6053 rule->applet.obj_type = OBJ_TYPE_APPLET;
6054 rule->applet.name = fcn->name;
6055 rule->applet.init = hlua_applet_http_init;
6056 rule->applet.fct = hlua_applet_http_fct;
6057 rule->applet.release = hlua_applet_http_release;
6058 rule->applet.timeout = hlua_timeout_applet;
6059
6060 return ACT_RET_PRS_OK;
6061}
6062
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006063/* This function is an LUA binding used for registering
6064 * "sample-conv" functions. It expects a converter name used
6065 * in the haproxy configuration file, and an LUA function.
6066 */
6067__LJMP static int hlua_register_action(lua_State *L)
6068{
6069 struct action_kw_list *akl;
6070 const char *name;
6071 int ref;
6072 int len;
6073 struct hlua_function *fcn;
6074
6075 MAY_LJMP(check_args(L, 3, "register_service"));
6076
6077 /* First argument : converter name. */
6078 name = MAY_LJMP(luaL_checkstring(L, 1));
6079
6080 /* Second argument : environment. */
6081 if (lua_type(L, 2) != LUA_TTABLE)
6082 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6083
6084 /* Third argument : lua function. */
6085 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6086
6087 /* browse the second argulent as an array. */
6088 lua_pushnil(L);
6089 while (lua_next(L, 2) != 0) {
6090 if (lua_type(L, -1) != LUA_TSTRING)
6091 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6092
6093 /* Check required environment. Only accepted "http" or "tcp". */
6094 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006095 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006096 if (!akl)
6097 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006098 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006099 if (!fcn)
6100 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6101
6102 /* Fill fcn. */
6103 fcn->name = strdup(name);
6104 if (!fcn->name)
6105 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6106 fcn->function_ref = ref;
6107
6108 /* List head */
6109 akl->list.n = akl->list.p = NULL;
6110
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006111 /* action keyword. */
6112 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006113 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006114 if (!akl->kw[0].kw)
6115 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6116
6117 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6118
6119 akl->kw[0].match_pfx = 0;
6120 akl->kw[0].private = fcn;
6121 akl->kw[0].parse = action_register_lua;
6122
6123 /* select the action registering point. */
6124 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6125 tcp_req_cont_keywords_register(akl);
6126 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6127 tcp_res_cont_keywords_register(akl);
6128 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6129 http_req_keywords_register(akl);
6130 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6131 http_res_keywords_register(akl);
6132 else
6133 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6134 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6135 "are expected.", lua_tostring(L, -1)));
6136
6137 /* pop the environment string. */
6138 lua_pop(L, 1);
6139 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006140 return ACT_RET_PRS_OK;
6141}
6142
6143static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6144 struct act_rule *rule, char **err)
6145{
6146 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6147
6148 /* Memory for the rule. */
6149 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6150 if (!rule->arg.hlua_rule) {
6151 memprintf(err, "out of memory error");
6152 return ACT_RET_PRS_ERR;
6153 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006154
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006155 /* Reference the Lua function and store the reference. */
6156 rule->arg.hlua_rule->fcn = *fcn;
6157
6158 /* TODO: later accept arguments. */
6159 rule->arg.hlua_rule->args = NULL;
6160
6161 /* Add applet pointer in the rule. */
6162 rule->applet.obj_type = OBJ_TYPE_APPLET;
6163 rule->applet.name = fcn->name;
6164 rule->applet.init = hlua_applet_tcp_init;
6165 rule->applet.fct = hlua_applet_tcp_fct;
6166 rule->applet.release = hlua_applet_tcp_release;
6167 rule->applet.timeout = hlua_timeout_applet;
6168
6169 return 0;
6170}
6171
6172/* This function is an LUA binding used for registering
6173 * "sample-conv" functions. It expects a converter name used
6174 * in the haproxy configuration file, and an LUA function.
6175 */
6176__LJMP static int hlua_register_service(lua_State *L)
6177{
6178 struct action_kw_list *akl;
6179 const char *name;
6180 const char *env;
6181 int ref;
6182 int len;
6183 struct hlua_function *fcn;
6184
6185 MAY_LJMP(check_args(L, 3, "register_service"));
6186
6187 /* First argument : converter name. */
6188 name = MAY_LJMP(luaL_checkstring(L, 1));
6189
6190 /* Second argument : environment. */
6191 env = MAY_LJMP(luaL_checkstring(L, 2));
6192
6193 /* Third argument : lua function. */
6194 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6195
6196 /* Check required environment. Only accepted "http" or "tcp". */
6197 /* Allocate and fill the sample fetch keyword struct. */
6198 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6199 if (!akl)
6200 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6201 fcn = calloc(1, sizeof(*fcn));
6202 if (!fcn)
6203 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6204
6205 /* Fill fcn. */
6206 len = strlen("<lua.>") + strlen(name) + 1;
6207 fcn->name = calloc(1, len);
6208 if (!fcn->name)
6209 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6210 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6211 fcn->function_ref = ref;
6212
6213 /* List head */
6214 akl->list.n = akl->list.p = NULL;
6215
6216 /* converter keyword. */
6217 len = strlen("lua.") + strlen(name) + 1;
6218 akl->kw[0].kw = calloc(1, len);
6219 if (!akl->kw[0].kw)
6220 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6221
6222 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6223
6224 if (strcmp(env, "tcp") == 0)
6225 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006226 else if (strcmp(env, "http") == 0)
6227 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006228 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006229 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6230 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006231
6232 akl->kw[0].match_pfx = 0;
6233 akl->kw[0].private = fcn;
6234
6235 /* End of array. */
6236 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6237
6238 /* Register this new converter */
6239 service_keywords_register(akl);
6240
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006241 return 0;
6242}
6243
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006244static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
6245 struct proxy *defpx, const char *file, int line,
6246 char **err, unsigned int *timeout)
6247{
6248 const char *error;
6249
6250 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
6251 if (error && *error != '\0') {
6252 memprintf(err, "%s: invalid timeout", args[0]);
6253 return -1;
6254 }
6255 return 0;
6256}
6257
6258static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
6259 struct proxy *defpx, const char *file, int line,
6260 char **err)
6261{
6262 return hlua_read_timeout(args, section_type, curpx, defpx,
6263 file, line, err, &hlua_timeout_session);
6264}
6265
6266static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
6267 struct proxy *defpx, const char *file, int line,
6268 char **err)
6269{
6270 return hlua_read_timeout(args, section_type, curpx, defpx,
6271 file, line, err, &hlua_timeout_task);
6272}
6273
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006274static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
6275 struct proxy *defpx, const char *file, int line,
6276 char **err)
6277{
6278 return hlua_read_timeout(args, section_type, curpx, defpx,
6279 file, line, err, &hlua_timeout_applet);
6280}
6281
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006282static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
6283 struct proxy *defpx, const char *file, int line,
6284 char **err)
6285{
6286 char *error;
6287
6288 hlua_nb_instruction = strtoll(args[1], &error, 10);
6289 if (*error != '\0') {
6290 memprintf(err, "%s: invalid number", args[0]);
6291 return -1;
6292 }
6293 return 0;
6294}
6295
Willy Tarreau32f61e22015-03-18 17:54:59 +01006296static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
6297 struct proxy *defpx, const char *file, int line,
6298 char **err)
6299{
6300 char *error;
6301
6302 if (*(args[1]) == 0) {
6303 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
6304 return -1;
6305 }
6306 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
6307 if (*error != '\0') {
6308 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
6309 return -1;
6310 }
6311 return 0;
6312}
6313
6314
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006315/* This function is called by the main configuration key "lua-load". It loads and
6316 * execute an lua file during the parsing of the HAProxy configuration file. It is
6317 * the main lua entry point.
6318 *
6319 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
6320 * occured, otherwise it returns 0.
6321 *
6322 * In some error case, LUA set an error message in top of the stack. This function
6323 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006324 *
6325 * This function can fail with an abort() due to an Lua critical error.
6326 * We are in the configuration parsing process of HAProxy, this abort() is
6327 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006328 */
6329static int hlua_load(char **args, int section_type, struct proxy *curpx,
6330 struct proxy *defpx, const char *file, int line,
6331 char **err)
6332{
6333 int error;
6334
6335 /* Just load and compile the file. */
6336 error = luaL_loadfile(gL.T, args[1]);
6337 if (error) {
6338 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
6339 lua_pop(gL.T, 1);
6340 return -1;
6341 }
6342
6343 /* If no syntax error where detected, execute the code. */
6344 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
6345 switch (error) {
6346 case LUA_OK:
6347 break;
6348 case LUA_ERRRUN:
6349 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
6350 lua_pop(gL.T, 1);
6351 return -1;
6352 case LUA_ERRMEM:
6353 memprintf(err, "lua out of memory error\n");
6354 return -1;
6355 case LUA_ERRERR:
6356 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
6357 lua_pop(gL.T, 1);
6358 return -1;
6359 case LUA_ERRGCMM:
6360 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
6361 lua_pop(gL.T, 1);
6362 return -1;
6363 default:
6364 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
6365 lua_pop(gL.T, 1);
6366 return -1;
6367 }
6368
6369 return 0;
6370}
6371
6372/* configuration keywords declaration */
6373static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006374 { CFG_GLOBAL, "lua-load", hlua_load },
6375 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
6376 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006377 { CFG_GLOBAL, "tune.lua.applet-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006378 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01006379 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006380 { 0, NULL, NULL },
6381}};
6382
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006383/* This function can fail with an abort() due to an Lua critical error.
6384 * We are in the initialisation process of HAProxy, this abort() is
6385 * tolerated.
6386 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006387int hlua_post_init()
6388{
6389 struct hlua_init_function *init;
6390 const char *msg;
6391 enum hlua_exec ret;
6392
6393 list_for_each_entry(init, &hlua_init_functions, l) {
6394 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
6395 ret = hlua_ctx_resume(&gL, 0);
6396 switch (ret) {
6397 case HLUA_E_OK:
6398 lua_pop(gL.T, -1);
6399 return 1;
6400 case HLUA_E_AGAIN:
6401 Alert("lua init: yield not allowed.\n");
6402 return 0;
6403 case HLUA_E_ERRMSG:
6404 msg = lua_tostring(gL.T, -1);
6405 Alert("lua init: %s.\n", msg);
6406 return 0;
6407 case HLUA_E_ERR:
6408 default:
6409 Alert("lua init: unknown runtime error.\n");
6410 return 0;
6411 }
6412 }
6413 return 1;
6414}
6415
Willy Tarreau32f61e22015-03-18 17:54:59 +01006416/* The memory allocator used by the Lua stack. <ud> is a pointer to the
6417 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
6418 * is the previously allocated size or the kind of object in case of a new
6419 * allocation. <nsize> is the requested new size.
6420 */
6421static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
6422{
6423 struct hlua_mem_allocator *zone = ud;
6424
6425 if (nsize == 0) {
6426 /* it's a free */
6427 if (ptr)
6428 zone->allocated -= osize;
6429 free(ptr);
6430 return NULL;
6431 }
6432
6433 if (!ptr) {
6434 /* it's a new allocation */
6435 if (zone->limit && zone->allocated + nsize > zone->limit)
6436 return NULL;
6437
6438 ptr = malloc(nsize);
6439 if (ptr)
6440 zone->allocated += nsize;
6441 return ptr;
6442 }
6443
6444 /* it's a realloc */
6445 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
6446 return NULL;
6447
6448 ptr = realloc(ptr, nsize);
6449 if (ptr)
6450 zone->allocated += nsize - osize;
6451 return ptr;
6452}
6453
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006454/* Ithis function can fail with an abort() due to an Lua critical error.
6455 * We are in the initialisation process of HAProxy, this abort() is
6456 * tolerated.
6457 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01006458void hlua_init(void)
6459{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006460 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006461 int idx;
6462 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006463 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006464 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006465#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006466 struct srv_kw *kw;
6467 int tmp_error;
6468 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01006469 char *args[] = { /* SSL client configuration. */
6470 "ssl",
6471 "verify",
6472 "none",
6473 "force-sslv3",
6474 NULL
6475 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006476#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006477
Willy Tarreau87b09662015-04-03 00:22:06 +02006478 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006479 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
6480
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006481 /* Register configuration keywords. */
6482 cfg_register_keywords(&cfg_kws);
6483
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006484 /* Init main lua stack. */
6485 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01006486 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006487 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006488 gL.T = luaL_newstate();
6489 hlua_sethlua(&gL);
6490 gL.Tref = LUA_REFNIL;
6491 gL.task = NULL;
6492
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006493 /* From this point, until the end of the initialisation fucntion,
6494 * the Lua function can fail with an abort. We are in the initialisation
6495 * process of HAProxy, this abort() is tolerated.
6496 */
6497
Willy Tarreau32f61e22015-03-18 17:54:59 +01006498 /* change the memory allocators to track memory usage */
6499 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
6500
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006501 /* Initialise lua. */
6502 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006503
6504 /*
6505 *
6506 * Create "core" object.
6507 *
6508 */
6509
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01006510 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006511 lua_newtable(gL.T);
6512
6513 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006514 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006515 hlua_class_const_int(gL.T, log_levels[i], i);
6516
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006517 /* Register special functions. */
6518 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006519 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006520 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006521 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006522 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006523 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006524 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01006525 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006526 hlua_class_function(gL.T, "sleep", hlua_sleep);
6527 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01006528 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
6529 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
6530 hlua_class_function(gL.T, "set_map", hlua_set_map);
6531 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006532 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006533 hlua_class_function(gL.T, "log", hlua_log);
6534 hlua_class_function(gL.T, "Debug", hlua_log_debug);
6535 hlua_class_function(gL.T, "Info", hlua_log_info);
6536 hlua_class_function(gL.T, "Warning", hlua_log_warning);
6537 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02006538 hlua_class_function(gL.T, "done", hlua_done);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006539
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006540 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006541
6542 /*
6543 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006544 * Register class Map
6545 *
6546 */
6547
6548 /* This table entry is the object "Map" base. */
6549 lua_newtable(gL.T);
6550
6551 /* register pattern types. */
6552 for (i=0; i<PAT_MATCH_NUM; i++)
6553 hlua_class_const_int(gL.T, pat_match_names[i], i);
6554
6555 /* register constructor. */
6556 hlua_class_function(gL.T, "new", hlua_map_new);
6557
6558 /* Create and fill the metatable. */
6559 lua_newtable(gL.T);
6560
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006561 /* Create the __tostring identifier */
6562 lua_pushstring(gL.T, "__tostring");
6563 lua_pushstring(gL.T, CLASS_MAP);
6564 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6565 lua_rawset(gL.T, -3);
6566
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006567 /* Create and fille the __index entry. */
6568 lua_pushstring(gL.T, "__index");
6569 lua_newtable(gL.T);
6570
6571 /* Register . */
6572 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
6573 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
6574
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006575 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006576
6577 /* Register previous table in the registry with reference and named entry. */
6578 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6579 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6580 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
6581 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6582
6583 /* Assign the metatable to the mai Map object. */
6584 lua_setmetatable(gL.T, -2);
6585
6586 /* Set a name to the table. */
6587 lua_setglobal(gL.T, "Map");
6588
6589 /*
6590 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006591 * Register class Channel
6592 *
6593 */
6594
6595 /* Create and fill the metatable. */
6596 lua_newtable(gL.T);
6597
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006598 /* Create the __tostring identifier */
6599 lua_pushstring(gL.T, "__tostring");
6600 lua_pushstring(gL.T, CLASS_CHANNEL);
6601 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6602 lua_rawset(gL.T, -3);
6603
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006604 /* Create and fille the __index entry. */
6605 lua_pushstring(gL.T, "__index");
6606 lua_newtable(gL.T);
6607
6608 /* Register . */
6609 hlua_class_function(gL.T, "get", hlua_channel_get);
6610 hlua_class_function(gL.T, "dup", hlua_channel_dup);
6611 hlua_class_function(gL.T, "getline", hlua_channel_getline);
6612 hlua_class_function(gL.T, "set", hlua_channel_set);
6613 hlua_class_function(gL.T, "append", hlua_channel_append);
6614 hlua_class_function(gL.T, "send", hlua_channel_send);
6615 hlua_class_function(gL.T, "forward", hlua_channel_forward);
6616 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
6617 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
6618
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006619 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006620
6621 /* Register previous table in the registry with reference and named entry. */
6622 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6623 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
6624 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6625
6626 /*
6627 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006628 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006629 *
6630 */
6631
6632 /* Create and fill the metatable. */
6633 lua_newtable(gL.T);
6634
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006635 /* Create the __tostring identifier */
6636 lua_pushstring(gL.T, "__tostring");
6637 lua_pushstring(gL.T, CLASS_FETCHES);
6638 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6639 lua_rawset(gL.T, -3);
6640
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006641 /* Create and fille the __index entry. */
6642 lua_pushstring(gL.T, "__index");
6643 lua_newtable(gL.T);
6644
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006645 /* Browse existing fetches and create the associated
6646 * object method.
6647 */
6648 sf = NULL;
6649 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
6650
6651 /* Dont register the keywork if the arguments check function are
6652 * not safe during the runtime.
6653 */
6654 if ((sf->val_args != NULL) &&
6655 (sf->val_args != val_payload_lv) &&
6656 (sf->val_args != val_hdr))
6657 continue;
6658
6659 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
6660 * by an underscore.
6661 */
6662 strncpy(trash.str, sf->kw, trash.size);
6663 trash.str[trash.size - 1] = '\0';
6664 for (p = trash.str; *p; p++)
6665 if (*p == '.' || *p == '-' || *p == '+')
6666 *p = '_';
6667
6668 /* Register the function. */
6669 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01006670 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006671 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006672 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006673 }
6674
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006675 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006676
6677 /* Register previous table in the registry with reference and named entry. */
6678 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6679 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
6680 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6681
6682 /*
6683 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006684 * Register class Converters
6685 *
6686 */
6687
6688 /* Create and fill the metatable. */
6689 lua_newtable(gL.T);
6690
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006691 /* Create the __tostring identifier */
6692 lua_pushstring(gL.T, "__tostring");
6693 lua_pushstring(gL.T, CLASS_CONVERTERS);
6694 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6695 lua_rawset(gL.T, -3);
6696
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006697 /* Create and fill the __index entry. */
6698 lua_pushstring(gL.T, "__index");
6699 lua_newtable(gL.T);
6700
6701 /* Browse existing converters and create the associated
6702 * object method.
6703 */
6704 sc = NULL;
6705 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
6706 /* Dont register the keywork if the arguments check function are
6707 * not safe during the runtime.
6708 */
6709 if (sc->val_args != NULL)
6710 continue;
6711
6712 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
6713 * by an underscore.
6714 */
6715 strncpy(trash.str, sc->kw, trash.size);
6716 trash.str[trash.size - 1] = '\0';
6717 for (p = trash.str; *p; p++)
6718 if (*p == '.' || *p == '-' || *p == '+')
6719 *p = '_';
6720
6721 /* Register the function. */
6722 lua_pushstring(gL.T, trash.str);
6723 lua_pushlightuserdata(gL.T, sc);
6724 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006725 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006726 }
6727
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006728 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006729
6730 /* Register previous table in the registry with reference and named entry. */
6731 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6732 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
6733 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6734
6735 /*
6736 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006737 * Register class HTTP
6738 *
6739 */
6740
6741 /* Create and fill the metatable. */
6742 lua_newtable(gL.T);
6743
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006744 /* Create the __tostring identifier */
6745 lua_pushstring(gL.T, "__tostring");
6746 lua_pushstring(gL.T, CLASS_HTTP);
6747 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6748 lua_rawset(gL.T, -3);
6749
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006750 /* Create and fille the __index entry. */
6751 lua_pushstring(gL.T, "__index");
6752 lua_newtable(gL.T);
6753
6754 /* Register Lua functions. */
6755 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
6756 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
6757 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
6758 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
6759 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
6760 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
6761 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
6762 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
6763 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
6764 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
6765
6766 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
6767 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
6768 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
6769 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
6770 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
6771 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006772 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006773
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006774 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006775
6776 /* Register previous table in the registry with reference and named entry. */
6777 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6778 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
6779 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6780
6781 /*
6782 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006783 * Register class AppletTCP
6784 *
6785 */
6786
6787 /* Create and fill the metatable. */
6788 lua_newtable(gL.T);
6789
6790 /* Create the __tostring identifier */
6791 lua_pushstring(gL.T, "__tostring");
6792 lua_pushstring(gL.T, CLASS_APPLET_TCP);
6793 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6794 lua_rawset(gL.T, -3);
6795
6796 /* Create and fille the __index entry. */
6797 lua_pushstring(gL.T, "__index");
6798 lua_newtable(gL.T);
6799
6800 /* Register Lua functions. */
6801 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
6802 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
6803 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
6804
6805 lua_settable(gL.T, -3);
6806
6807 /* Register previous table in the registry with reference and named entry. */
6808 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6809 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_APPLET_TCP); /* register class session. */
6810 class_applet_tcp_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6811
6812 /*
6813 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006814 * Register class AppletHTTP
6815 *
6816 */
6817
6818 /* Create and fill the metatable. */
6819 lua_newtable(gL.T);
6820
6821 /* Create the __tostring identifier */
6822 lua_pushstring(gL.T, "__tostring");
6823 lua_pushstring(gL.T, CLASS_APPLET_HTTP);
6824 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6825 lua_rawset(gL.T, -3);
6826
6827 /* Create and fille the __index entry. */
6828 lua_pushstring(gL.T, "__index");
6829 lua_newtable(gL.T);
6830
6831 /* Register Lua functions. */
6832 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
6833 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
6834 hlua_class_function(gL.T, "send", hlua_applet_http_send);
6835 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
6836 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
6837 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
6838
6839 lua_settable(gL.T, -3);
6840
6841 /* Register previous table in the registry with reference and named entry. */
6842 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6843 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_APPLET_HTTP); /* register class session. */
6844 class_applet_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6845
6846 /*
6847 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006848 * Register class TXN
6849 *
6850 */
6851
6852 /* Create and fill the metatable. */
6853 lua_newtable(gL.T);
6854
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006855 /* Create the __tostring identifier */
6856 lua_pushstring(gL.T, "__tostring");
6857 lua_pushstring(gL.T, CLASS_TXN);
6858 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6859 lua_rawset(gL.T, -3);
6860
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006861 /* Create and fille the __index entry. */
6862 lua_pushstring(gL.T, "__index");
6863 lua_newtable(gL.T);
6864
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006865 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01006866 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
6867 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006868 hlua_class_function(gL.T, "set_var", hlua_set_var);
6869 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006870 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006871 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
6872 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
6873 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006874 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
6875 hlua_class_function(gL.T, "log", hlua_txn_log);
6876 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
6877 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
6878 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
6879 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006880
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006881 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006882
6883 /* Register previous table in the registry with reference and named entry. */
6884 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6885 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
6886 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006887
6888 /*
6889 *
6890 * Register class Socket
6891 *
6892 */
6893
6894 /* Create and fill the metatable. */
6895 lua_newtable(gL.T);
6896
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006897 /* Create the __tostring identifier */
6898 lua_pushstring(gL.T, "__tostring");
6899 lua_pushstring(gL.T, CLASS_SOCKET);
6900 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6901 lua_rawset(gL.T, -3);
6902
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006903 /* Create and fille the __index entry. */
6904 lua_pushstring(gL.T, "__index");
6905 lua_newtable(gL.T);
6906
Baptiste Assmann84bb4932015-03-02 21:40:06 +01006907#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006908 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01006909#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006910 hlua_class_function(gL.T, "connect", hlua_socket_connect);
6911 hlua_class_function(gL.T, "send", hlua_socket_send);
6912 hlua_class_function(gL.T, "receive", hlua_socket_receive);
6913 hlua_class_function(gL.T, "close", hlua_socket_close);
6914 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
6915 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
6916 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
6917 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
6918
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006919 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006920
6921 /* Register the garbage collector entry. */
6922 lua_pushstring(gL.T, "__gc");
6923 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006924 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006925
6926 /* Register previous table in the registry with reference and named entry. */
6927 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6928 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6929 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
6930 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
6931
6932 /* Proxy and server configuration initialisation. */
6933 memset(&socket_proxy, 0, sizeof(socket_proxy));
6934 init_new_proxy(&socket_proxy);
6935 socket_proxy.parent = NULL;
6936 socket_proxy.last_change = now.tv_sec;
6937 socket_proxy.id = "LUA-SOCKET";
6938 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
6939 socket_proxy.maxconn = 0;
6940 socket_proxy.accept = NULL;
6941 socket_proxy.options2 |= PR_O2_INDEPSTR;
6942 socket_proxy.srv = NULL;
6943 socket_proxy.conn_retries = 0;
6944 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
6945
6946 /* Init TCP server: unchanged parameters */
6947 memset(&socket_tcp, 0, sizeof(socket_tcp));
6948 socket_tcp.next = NULL;
6949 socket_tcp.proxy = &socket_proxy;
6950 socket_tcp.obj_type = OBJ_TYPE_SERVER;
6951 LIST_INIT(&socket_tcp.actconns);
6952 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02006953 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02006954 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02006955 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006956 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
6957 socket_tcp.last_change = 0;
6958 socket_tcp.id = "LUA-TCP-CONN";
6959 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
6960 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
6961 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
6962
6963 /* XXX: Copy default parameter from default server,
6964 * but the default server is not initialized.
6965 */
6966 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
6967 socket_tcp.minconn = socket_proxy.defsrv.minconn;
6968 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
6969 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
6970 socket_tcp.onerror = socket_proxy.defsrv.onerror;
6971 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
6972 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
6973 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
6974 socket_tcp.uweight = socket_proxy.defsrv.iweight;
6975 socket_tcp.iweight = socket_proxy.defsrv.iweight;
6976
6977 socket_tcp.check.status = HCHK_STATUS_INI;
6978 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
6979 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
6980 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
6981 socket_tcp.check.server = &socket_tcp;
6982
6983 socket_tcp.agent.status = HCHK_STATUS_INI;
6984 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
6985 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
6986 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
6987 socket_tcp.agent.server = &socket_tcp;
6988
6989 socket_tcp.xprt = &raw_sock;
6990
6991#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006992 /* Init TCP server: unchanged parameters */
6993 memset(&socket_ssl, 0, sizeof(socket_ssl));
6994 socket_ssl.next = NULL;
6995 socket_ssl.proxy = &socket_proxy;
6996 socket_ssl.obj_type = OBJ_TYPE_SERVER;
6997 LIST_INIT(&socket_ssl.actconns);
6998 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02006999 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007000 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007001 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007002 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
7003 socket_ssl.last_change = 0;
7004 socket_ssl.id = "LUA-SSL-CONN";
7005 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7006 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7007 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7008
7009 /* XXX: Copy default parameter from default server,
7010 * but the default server is not initialized.
7011 */
7012 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7013 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7014 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7015 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7016 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7017 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7018 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7019 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7020 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7021 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7022
7023 socket_ssl.check.status = HCHK_STATUS_INI;
7024 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7025 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7026 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7027 socket_ssl.check.server = &socket_ssl;
7028
7029 socket_ssl.agent.status = HCHK_STATUS_INI;
7030 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7031 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7032 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7033 socket_ssl.agent.server = &socket_ssl;
7034
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007035 socket_ssl.use_ssl = 1;
7036 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007037
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007038 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007039 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7040 /*
7041 *
7042 * If the keyword is not known, we can search in the registered
7043 * server keywords. This is usefull to configure special SSL
7044 * features like client certificates and ssl_verify.
7045 *
7046 */
7047 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7048 if (tmp_error != 0) {
7049 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7050 abort(); /* This must be never arrives because the command line
7051 not editable by the user. */
7052 }
7053 idx += kw->skip;
7054 }
7055 }
7056
7057 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007058 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007059#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007060}