blob: 2ed6f525d7f301c516b0335b1c0d39e71a351322 [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013#include <sys/socket.h>
14
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020016#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010017
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010018#include <lauxlib.h>
19#include <lua.h>
20#include <lualib.h>
21
Thierry FOURNIER463119c2015-03-10 00:35:36 +010022#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
23#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010024#endif
25
Thierry FOURNIER380d0932015-01-23 14:27:52 +010026#include <ebpttree.h>
27
28#include <common/cfgparse.h>
29
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010030#include <types/connection.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010031#include <types/hlua.h>
32#include <types/proxy.h>
33
Thierry FOURNIER55da1652015-01-23 11:36:30 +010034#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020035#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010036#include <proto/channel.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010037#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010038#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010039#include <proto/hlua_fcn.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020040#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010041#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010042#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010043#include <proto/payload.h>
44#include <proto/proto_http.h>
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010045#include <proto/proto_tcp.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010046#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010047#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010048#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020049#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020050#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010051#include <proto/ssl_sock.h>
52#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010053#include <proto/task.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020054#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010055
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010056/* Lua uses longjmp to perform yield or throwing errors. This
57 * macro is used only for identifying the function that can
58 * not return because a longjmp is executed.
59 * __LJMP marks a prototype of hlua file that can use longjmp.
60 * WILL_LJMP() marks an lua function that will use longjmp.
61 * MAY_LJMP() marks an lua function that may use longjmp.
62 */
63#define __LJMP
64#define WILL_LJMP(func) func
65#define MAY_LJMP(func) func
66
Thierry FOURNIERbabae282015-09-17 11:36:37 +020067/* This couple of function executes securely some Lua calls outside of
68 * the lua runtime environment. Each Lua call can return a longjmp
69 * if it encounter a memory error.
70 *
71 * Lua documentation extract:
72 *
73 * If an error happens outside any protected environment, Lua calls
74 * a panic function (see lua_atpanic) and then calls abort, thus
75 * exiting the host application. Your panic function can avoid this
76 * exit by never returning (e.g., doing a long jump to your own
77 * recovery point outside Lua).
78 *
79 * The panic function runs as if it were a message handler (see
80 * §2.3); in particular, the error message is at the top of the
81 * stack. However, there is no guarantee about stack space. To push
82 * anything on the stack, the panic function must first check the
83 * available space (see §4.2).
84 *
85 * We must check all the Lua entry point. This includes:
86 * - The include/proto/hlua.h exported functions
87 * - the task wrapper function
88 * - The action wrapper function
89 * - The converters wrapper function
90 * - The sample-fetch wrapper functions
91 *
92 * It is tolerated that the initilisation function returns an abort.
93 * Before each Lua abort, an error message is writed on stderr.
94 *
95 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
96 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
97 * because they must be exists in the program stack when the longjmp
98 * is called.
99 */
100jmp_buf safe_ljmp_env;
101static int hlua_panic_safe(lua_State *L) { return 0; }
102static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
103
104#define SET_SAFE_LJMP(__L) \
105 ({ \
106 int ret; \
107 if (setjmp(safe_ljmp_env) != 0) { \
108 lua_atpanic(__L, hlua_panic_safe); \
109 ret = 0; \
110 } else { \
111 lua_atpanic(__L, hlua_panic_ljmp); \
112 ret = 1; \
113 } \
114 ret; \
115 })
116
117/* If we are the last function catching Lua errors, we
118 * must reset the panic function.
119 */
120#define RESET_SAFE_LJMP(__L) \
121 do { \
122 lua_atpanic(__L, hlua_panic_safe); \
123 } while(0)
124
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200125/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200126#define APPLET_DONE 0x01 /* applet processing is done. */
127#define APPLET_100C 0x02 /* 100 continue expected. */
128#define APPLET_HDR_SENT 0x04 /* Response header sent. */
129#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
130#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100131#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200132
133#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200134
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100135/* The main Lua execution context. */
136struct hlua gL;
137
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100138/* This is the memory pool containing all the signal structs. These
139 * struct are used to store each requiered signal between two tasks.
140 */
141struct pool_head *pool2_hlua_com;
142
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100143/* Used for Socket connection. */
144static struct proxy socket_proxy;
145static struct server socket_tcp;
146#ifdef USE_OPENSSL
147static struct server socket_ssl;
148#endif
149
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100150/* List head of the function called at the initialisation time. */
151struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
152
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100153/* The following variables contains the reference of the different
154 * Lua classes. These references are useful for identify metadata
155 * associated with an object.
156 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100157static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100158static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100159static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100160static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100161static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100162static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200163static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200164static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200165static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100166
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100167/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200168 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100169 * short timeout. Lua linked with tasks doesn't have a timeout
170 * because a task may remain alive during all the haproxy execution.
171 */
172static unsigned int hlua_timeout_session = 4000; /* session timeout. */
173static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200174static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100175
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100176/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
177 * it is used for preventing infinite loops.
178 *
179 * I test the scheer with an infinite loop containing one incrementation
180 * and one test. I run this loop between 10 seconds, I raise a ceil of
181 * 710M loops from one interrupt each 9000 instructions, so I fix the value
182 * to one interrupt each 10 000 instructions.
183 *
184 * configured | Number of
185 * instructions | loops executed
186 * between two | in milions
187 * forced yields |
188 * ---------------+---------------
189 * 10 | 160
190 * 500 | 670
191 * 1000 | 680
192 * 5000 | 700
193 * 7000 | 700
194 * 8000 | 700
195 * 9000 | 710 <- ceil
196 * 10000 | 710
197 * 100000 | 710
198 * 1000000 | 710
199 *
200 */
201static unsigned int hlua_nb_instruction = 10000;
202
Willy Tarreau32f61e22015-03-18 17:54:59 +0100203/* Descriptor for the memory allocation state. If limit is not null, it will
204 * be enforced on any memory allocation.
205 */
206struct hlua_mem_allocator {
207 size_t allocated;
208 size_t limit;
209};
210
211static struct hlua_mem_allocator hlua_global_allocator;
212
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200213static const char error_500[] =
214 "HTTP/1.0 500 Server Error\r\n"
215 "Cache-Control: no-cache\r\n"
216 "Connection: close\r\n"
217 "Content-Type: text/html\r\n"
218 "\r\n"
219 "<html><body><h1>500 Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
220
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100221/* These functions converts types between HAProxy internal args or
222 * sample and LUA types. Another function permits to check if the
223 * LUA stack contains arguments according with an required ARG_T
224 * format.
225 */
226static int hlua_arg2lua(lua_State *L, const struct arg *arg);
227static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100228__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
229 unsigned int mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100230static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100231static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100232static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
233
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200234__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
235
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200236#define SEND_ERR(__be, __fmt, __args...) \
237 do { \
238 send_log(__be, LOG_ERR, __fmt, ## __args); \
239 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
240 Alert(__fmt, ## __args); \
241 } while (0)
242
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100243/* Used to check an Lua function type in the stack. It creates and
244 * returns a reference of the function. This function throws an
245 * error if the rgument is not a "function".
246 */
247__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
248{
249 if (!lua_isfunction(L, argno)) {
250 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
251 WILL_LJMP(luaL_argerror(L, argno, msg));
252 }
253 lua_pushvalue(L, argno);
254 return luaL_ref(L, LUA_REGISTRYINDEX);
255}
256
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200257/* Return the string that is of the top of the stack. */
258const char *hlua_get_top_error_string(lua_State *L)
259{
260 if (lua_gettop(L) < 1)
261 return "unknown error";
262 if (lua_type(L, -1) != LUA_TSTRING)
263 return "unknown error";
264 return lua_tostring(L, -1);
265}
266
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100267/* The three following functions are useful for adding entries
268 * in a table. These functions takes a string and respectively an
269 * integer, a string or a function and add it to the table in the
270 * top of the stack.
271 *
272 * These functions throws an error if no more stack size is
273 * available.
274 */
275__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100276 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100277{
278 if (!lua_checkstack(L, 2))
279 WILL_LJMP(luaL_error(L, "full stack"));
280 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100281 lua_pushinteger(L, value);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200282 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100283}
284__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
285 const char *value)
286{
287 if (!lua_checkstack(L, 2))
288 WILL_LJMP(luaL_error(L, "full stack"));
289 lua_pushstring(L, name);
290 lua_pushstring(L, value);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200291 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100292}
293__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
294 int (*function)(lua_State *L))
295{
296 if (!lua_checkstack(L, 2))
297 WILL_LJMP(luaL_error(L, "full stack"));
298 lua_pushstring(L, name);
299 lua_pushcclosure(L, function, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200300 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100301}
302
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +0200303__LJMP static int hlua_dump_object(struct lua_State *L)
304{
305 const char *name = (const char *)lua_tostring(L, lua_upvalueindex(1));
306 lua_pushfstring(L, "HAProxy class %s", name);
307 return 1;
308}
309
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100310/* This function check the number of arguments available in the
311 * stack. If the number of arguments available is not the same
312 * then <nb> an error is throwed.
313 */
314__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
315{
316 if (lua_gettop(L) == nb)
317 return;
318 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
319}
320
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100321/* This fucntion push an error string prefixed by the file name
322 * and the line number where the error is encountered.
323 */
324static int hlua_pusherror(lua_State *L, const char *fmt, ...)
325{
326 va_list argp;
327 va_start(argp, fmt);
328 luaL_where(L, 1);
329 lua_pushvfstring(L, fmt, argp);
330 va_end(argp);
331 lua_concat(L, 2);
332 return 1;
333}
334
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100335/* This function register a new signal. "lua" is the current lua
336 * execution context. It contains a pointer to the associated task.
337 * "link" is a list head attached to an other task that must be wake
338 * the lua task if an event occurs. This is useful with external
339 * events like TCP I/O or sleep functions. This funcion allocate
340 * memory for the signal.
341 */
342static int hlua_com_new(struct hlua *lua, struct list *link)
343{
344 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
345 if (!com)
346 return 0;
347 LIST_ADDQ(&lua->com, &com->purge_me);
348 LIST_ADDQ(link, &com->wake_me);
349 com->task = lua->task;
350 return 1;
351}
352
353/* This function purge all the pending signals when the LUA execution
354 * is finished. This prevent than a coprocess try to wake a deleted
355 * task. This function remove the memory associated to the signal.
356 */
357static void hlua_com_purge(struct hlua *lua)
358{
359 struct hlua_com *com, *back;
360
361 /* Delete all pending communication signals. */
362 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
363 LIST_DEL(&com->purge_me);
364 LIST_DEL(&com->wake_me);
365 pool_free2(pool2_hlua_com, com);
366 }
367}
368
369/* This function sends signals. It wakes all the tasks attached
370 * to a list head, and remove the signal, and free the used
371 * memory.
372 */
373static void hlua_com_wake(struct list *wake)
374{
375 struct hlua_com *com, *back;
376
377 /* Wake task and delete all pending communication signals. */
378 list_for_each_entry_safe(com, back, wake, wake_me) {
379 LIST_DEL(&com->purge_me);
380 LIST_DEL(&com->wake_me);
381 task_wakeup(com->task, TASK_WOKEN_MSG);
382 pool_free2(pool2_hlua_com, com);
383 }
384}
385
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100386/* This functions is used with sample fetch and converters. It
387 * converts the HAProxy configuration argument in a lua stack
388 * values.
389 *
390 * It takes an array of "arg", and each entry of the array is
391 * converted and pushed in the LUA stack.
392 */
393static int hlua_arg2lua(lua_State *L, const struct arg *arg)
394{
395 switch (arg->type) {
396 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100397 case ARGT_TIME:
398 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100399 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100400 break;
401
402 case ARGT_STR:
403 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
404 break;
405
406 case ARGT_IPV4:
407 case ARGT_IPV6:
408 case ARGT_MSK4:
409 case ARGT_MSK6:
410 case ARGT_FE:
411 case ARGT_BE:
412 case ARGT_TAB:
413 case ARGT_SRV:
414 case ARGT_USR:
415 case ARGT_MAP:
416 default:
417 lua_pushnil(L);
418 break;
419 }
420 return 1;
421}
422
423/* This function take one entrie in an LUA stack at the index "ud",
424 * and try to convert it in an HAProxy argument entry. This is useful
425 * with sample fetch wrappers. The input arguments are gived to the
426 * lua wrapper and converted as arg list by thi function.
427 */
428static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
429{
430 switch (lua_type(L, ud)) {
431
432 case LUA_TNUMBER:
433 case LUA_TBOOLEAN:
434 arg->type = ARGT_SINT;
435 arg->data.sint = lua_tointeger(L, ud);
436 break;
437
438 case LUA_TSTRING:
439 arg->type = ARGT_STR;
440 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
441 break;
442
443 case LUA_TUSERDATA:
444 case LUA_TNIL:
445 case LUA_TTABLE:
446 case LUA_TFUNCTION:
447 case LUA_TTHREAD:
448 case LUA_TLIGHTUSERDATA:
449 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200450 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100451 break;
452 }
453 return 1;
454}
455
456/* the following functions are used to convert a struct sample
457 * in Lua type. This useful to convert the return of the
458 * fetchs or converters.
459 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100460static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100461{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200462 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100463 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100464 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200465 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100466 break;
467
468 case SMP_T_BIN:
469 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200470 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100471 break;
472
473 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200474 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100475 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
476 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
477 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
478 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
479 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
480 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
481 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
482 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
483 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200484 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100485 break;
486 default:
487 lua_pushnil(L);
488 break;
489 }
490 break;
491
492 case SMP_T_IPV4:
493 case SMP_T_IPV6:
494 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200495 if (sample_casts[smp->data.type][SMP_T_STR] &&
496 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200497 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100498 else
499 lua_pushnil(L);
500 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100501 default:
502 lua_pushnil(L);
503 break;
504 }
505 return 1;
506}
507
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100508/* the following functions are used to convert a struct sample
509 * in Lua strings. This is useful to convert the return of the
510 * fetchs or converters.
511 */
512static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
513{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200514 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100515
516 case SMP_T_BIN:
517 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200518 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100519 break;
520
521 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200522 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100523 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
524 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
525 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
526 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
527 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
528 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
529 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
530 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
531 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200532 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100533 break;
534 default:
535 lua_pushstring(L, "");
536 break;
537 }
538 break;
539
540 case SMP_T_SINT:
541 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100542 case SMP_T_IPV4:
543 case SMP_T_IPV6:
544 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200545 if (sample_casts[smp->data.type][SMP_T_STR] &&
546 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200547 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100548 else
549 lua_pushstring(L, "");
550 break;
551 default:
552 lua_pushstring(L, "");
553 break;
554 }
555 return 1;
556}
557
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100558/* the following functions are used to convert an Lua type in a
559 * struct sample. This is useful to provide data from a converter
560 * to the LUA code.
561 */
562static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
563{
564 switch (lua_type(L, ud)) {
565
566 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200567 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200568 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100569 break;
570
571
572 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200573 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200574 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100575 break;
576
577 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200578 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100579 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200580 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100581 break;
582
583 case LUA_TUSERDATA:
584 case LUA_TNIL:
585 case LUA_TTABLE:
586 case LUA_TFUNCTION:
587 case LUA_TTHREAD:
588 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200589 case LUA_TNONE:
590 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200591 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200592 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100593 break;
594 }
595 return 1;
596}
597
598/* This function check the "argp" builded by another conversion function
599 * is in accord with the expected argp defined by the "mask". The fucntion
600 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100601 *
602 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
603 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100604 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100605__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
606 unsigned int mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100607{
608 int min_arg;
609 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100610 struct proxy *px;
611 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100612
613 idx = 0;
614 min_arg = ARGM(mask);
615 mask >>= ARGM_BITS;
616
617 while (1) {
618
619 /* Check oversize. */
620 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100621 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100622 }
623
624 /* Check for mandatory arguments. */
625 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100626 if (idx < min_arg) {
627
628 /* If miss other argument than the first one, we return an error. */
629 if (idx > 0)
630 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
631
632 /* If first argument have a certain type, some default values
633 * may be used. See the function smp_resolve_args().
634 */
635 switch (mask & ARGT_MASK) {
636
637 case ARGT_FE:
638 if (!(p->cap & PR_CAP_FE))
639 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
640 argp[idx].data.prx = p;
641 argp[idx].type = ARGT_FE;
642 argp[idx+1].type = ARGT_STOP;
643 break;
644
645 case ARGT_BE:
646 if (!(p->cap & PR_CAP_BE))
647 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
648 argp[idx].data.prx = p;
649 argp[idx].type = ARGT_BE;
650 argp[idx+1].type = ARGT_STOP;
651 break;
652
653 case ARGT_TAB:
654 argp[idx].data.prx = p;
655 argp[idx].type = ARGT_TAB;
656 argp[idx+1].type = ARGT_STOP;
657 break;
658
659 default:
660 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
661 break;
662 }
663 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100664 return 0;
665 }
666
667 /* Check for exceed the number of requiered argument. */
668 if ((mask & ARGT_MASK) == ARGT_STOP &&
669 argp[idx].type != ARGT_STOP) {
670 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
671 }
672
673 if ((mask & ARGT_MASK) == ARGT_STOP &&
674 argp[idx].type == ARGT_STOP) {
675 return 0;
676 }
677
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100678 /* Convert some argument types. */
679 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100680 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100681 if (argp[idx].type != ARGT_SINT)
682 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
683 argp[idx].type = ARGT_SINT;
684 break;
685
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100686 case ARGT_TIME:
687 if (argp[idx].type != ARGT_SINT)
688 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200689 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100690 break;
691
692 case ARGT_SIZE:
693 if (argp[idx].type != ARGT_SINT)
694 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200695 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100696 break;
697
698 case ARGT_FE:
699 if (argp[idx].type != ARGT_STR)
700 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
701 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
702 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200703 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100704 if (!argp[idx].data.prx)
705 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
706 argp[idx].type = ARGT_FE;
707 break;
708
709 case ARGT_BE:
710 if (argp[idx].type != ARGT_STR)
711 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
712 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
713 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200714 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100715 if (!argp[idx].data.prx)
716 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
717 argp[idx].type = ARGT_BE;
718 break;
719
720 case ARGT_TAB:
721 if (argp[idx].type != ARGT_STR)
722 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
723 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
724 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200725 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100726 if (!argp[idx].data.prx)
727 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
728 argp[idx].type = ARGT_TAB;
729 break;
730
731 case ARGT_SRV:
732 if (argp[idx].type != ARGT_STR)
733 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
734 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
735 trash.str[argp[idx].data.str.len] = 0;
736 sname = strrchr(trash.str, '/');
737 if (sname) {
738 *sname++ = '\0';
739 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200740 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100741 if (!px)
742 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
743 }
744 else {
745 sname = trash.str;
746 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100747 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100748 argp[idx].data.srv = findserver(px, sname);
749 if (!argp[idx].data.srv)
750 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
751 argp[idx].type = ARGT_SRV;
752 break;
753
754 case ARGT_IPV4:
755 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
756 trash.str[argp[idx].data.str.len] = 0;
757 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
758 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
759 argp[idx].type = ARGT_IPV4;
760 break;
761
762 case ARGT_MSK4:
763 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
764 trash.str[argp[idx].data.str.len] = 0;
765 if (!str2mask(trash.str, &argp[idx].data.ipv4))
766 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
767 argp[idx].type = ARGT_MSK4;
768 break;
769
770 case ARGT_IPV6:
771 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
772 trash.str[argp[idx].data.str.len] = 0;
773 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
774 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
775 argp[idx].type = ARGT_IPV6;
776 break;
777
778 case ARGT_MSK6:
779 case ARGT_MAP:
780 case ARGT_REG:
781 case ARGT_USR:
782 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100783 break;
784 }
785
786 /* Check for type of argument. */
787 if ((mask & ARGT_MASK) != argp[idx].type) {
788 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
789 arg_type_names[(mask & ARGT_MASK)],
790 arg_type_names[argp[idx].type & ARGT_MASK]);
791 WILL_LJMP(luaL_argerror(L, first + idx, msg));
792 }
793
794 /* Next argument. */
795 mask >>= ARGT_BITS;
796 idx++;
797 }
798}
799
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100800/*
801 * The following functions are used to make correspondance between the the
802 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100803 *
804 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100805 * - hlua_sethlua : create the association between hlua context and lua_state.
806 */
807static inline struct hlua *hlua_gethlua(lua_State *L)
808{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100809 struct hlua **hlua = lua_getextraspace(L);
810 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100811}
812static inline void hlua_sethlua(struct hlua *hlua)
813{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100814 struct hlua **hlua_store = lua_getextraspace(hlua->T);
815 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100816}
817
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100818/* This function is used to send logs. It try to send on screen (stderr)
819 * and on the default syslog server.
820 */
821static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
822{
823 struct tm tm;
824 char *p;
825
826 /* Cleanup the log message. */
827 p = trash.str;
828 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200829 if (p >= trash.str + trash.size - 1) {
830 /* Break the message if exceed the buffer size. */
831 *(p-4) = ' ';
832 *(p-3) = '.';
833 *(p-2) = '.';
834 *(p-1) = '.';
835 break;
836 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100837 if (isprint(*msg))
838 *p = *msg;
839 else
840 *p = '.';
841 }
842 *p = '\0';
843
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200844 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100845 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200846 get_localtime(date.tv_sec, &tm);
847 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100848 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
849 (int)getpid(), trash.str);
850 fflush(stderr);
851 }
852}
853
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100854/* This function just ensure that the yield will be always
855 * returned with a timeout and permit to set some flags
856 */
857__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100858 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100859{
860 struct hlua *hlua = hlua_gethlua(L);
861
862 /* Set the wake timeout. If timeout is required, we set
863 * the expiration time.
864 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200865 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100866
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100867 hlua->flags |= flags;
868
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100869 /* Process the yield. */
870 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
871}
872
Willy Tarreau87b09662015-04-03 00:22:06 +0200873/* This function initialises the Lua environment stored in the stream.
874 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100875 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200876 *
877 * This function is particular. it initialises a new Lua thread. If the
878 * initialisation fails (example: out of memory error), the lua function
879 * throws an error (longjmp).
880 *
881 * This function manipulates two Lua stack: the main and the thread. Only
882 * the main stack can fail. The thread is not manipulated. This function
883 * MUST NOT manipulate the created thread stack state, because is not
884 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100885 */
886int hlua_ctx_init(struct hlua *lua, struct task *task)
887{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200888 if (!SET_SAFE_LJMP(gL.T)) {
889 lua->Tref = LUA_REFNIL;
890 return 0;
891 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100892 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100893 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100894 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100895 lua->T = lua_newthread(gL.T);
896 if (!lua->T) {
897 lua->Tref = LUA_REFNIL;
898 return 0;
899 }
900 hlua_sethlua(lua);
901 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
902 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200903 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100904 return 1;
905}
906
Willy Tarreau87b09662015-04-03 00:22:06 +0200907/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100908 * is destroyed. The destroy also the memory context. The struct "lua"
909 * is not freed.
910 */
911void hlua_ctx_destroy(struct hlua *lua)
912{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100913 if (!lua->T)
914 return;
915
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100916 /* Purge all the pending signals. */
917 hlua_com_purge(lua);
918
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100919 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
920 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200921
922 /* Forces a garbage collecting process. If the Lua program is finished
923 * without error, we run the GC on the thread pointer. Its freed all
924 * the unused memory.
925 * If the thread is finnish with an error or is currently yielded,
926 * it seems that the GC applied on the thread doesn't clean anything,
927 * so e run the GC on the main thread.
928 * NOTE: maybe this action locks all the Lua threads untiml the en of
929 * the garbage collection.
930 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200931 if (lua->flags & HLUA_MUST_GC) {
932 lua_gc(lua->T, LUA_GCCOLLECT, 0);
933 if (lua_status(lua->T) != LUA_OK)
934 lua_gc(gL.T, LUA_GCCOLLECT, 0);
935 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200936
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200937 lua->T = NULL;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100938}
939
940/* This function is used to restore the Lua context when a coroutine
941 * fails. This function copy the common memory between old coroutine
942 * and the new coroutine. The old coroutine is destroyed, and its
943 * replaced by the new coroutine.
944 * If the flag "keep_msg" is set, the last entry of the old is assumed
945 * as string error message and it is copied in the new stack.
946 */
947static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
948{
949 lua_State *T;
950 int new_ref;
951
952 /* Renew the main LUA stack doesn't have sense. */
953 if (lua == &gL)
954 return 0;
955
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100956 /* New Lua coroutine. */
957 T = lua_newthread(gL.T);
958 if (!T)
959 return 0;
960
961 /* Copy last error message. */
962 if (keep_msg)
963 lua_xmove(lua->T, T, 1);
964
965 /* Copy data between the coroutines. */
966 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
967 lua_xmove(lua->T, T, 1);
968 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
969
970 /* Destroy old data. */
971 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
972
973 /* The thread is garbage collected by Lua. */
974 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
975
976 /* Fill the struct with the new coroutine values. */
977 lua->Mref = new_ref;
978 lua->T = T;
979 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
980
981 /* Set context. */
982 hlua_sethlua(lua);
983
984 return 1;
985}
986
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100987void hlua_hook(lua_State *L, lua_Debug *ar)
988{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100989 struct hlua *hlua = hlua_gethlua(L);
990
991 /* Lua cannot yield when its returning from a function,
992 * so, we can fix the interrupt hook to 1 instruction,
993 * expecting that the function is finnished.
994 */
995 if (lua_gethookmask(L) & LUA_MASKRET) {
996 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
997 return;
998 }
999
1000 /* restore the interrupt condition. */
1001 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1002
1003 /* If we interrupt the Lua processing in yieldable state, we yield.
1004 * If the state is not yieldable, trying yield causes an error.
1005 */
1006 if (lua_isyieldable(L))
1007 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
1008
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001009 /* If we cannot yield, update the clock and check the timeout. */
1010 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001011 hlua->run_time += now_ms - hlua->start_time;
1012 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001013 lua_pushfstring(L, "execution timeout");
1014 WILL_LJMP(lua_error(L));
1015 }
1016
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001017 /* Update the start time. */
1018 hlua->start_time = now_ms;
1019
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001020 /* Try to interrupt the process at the end of the current
1021 * unyieldable function.
1022 */
1023 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001024}
1025
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001026/* This function start or resumes the Lua stack execution. If the flag
1027 * "yield_allowed" if no set and the LUA stack execution returns a yield
1028 * The function return an error.
1029 *
1030 * The function can returns 4 values:
1031 * - HLUA_E_OK : The execution is terminated without any errors.
1032 * - HLUA_E_AGAIN : The execution must continue at the next associated
1033 * task wakeup.
1034 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
1035 * the top of the stack.
1036 * - HLUA_E_ERR : An error has occured without error message.
1037 *
1038 * If an error occured, the stack is renewed and it is ready to run new
1039 * LUA code.
1040 */
1041static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1042{
1043 int ret;
1044 const char *msg;
1045
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001046 /* Initialise run time counter. */
1047 if (!HLUA_IS_RUNNING(lua))
1048 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001049
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001050resume_execution:
1051
1052 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1053 * instructions. it is used for preventing infinite loops.
1054 */
1055 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1056
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001057 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001058 HLUA_SET_RUN(lua);
1059 HLUA_CLR_CTRLYIELD(lua);
1060 HLUA_CLR_WAKERESWR(lua);
1061 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001062
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001063 /* Update the start time. */
1064 lua->start_time = now_ms;
1065
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001066 /* Call the function. */
1067 ret = lua_resume(lua->T, gL.T, lua->nargs);
1068 switch (ret) {
1069
1070 case LUA_OK:
1071 ret = HLUA_E_OK;
1072 break;
1073
1074 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001075 /* Check if the execution timeout is expired. It it is the case, we
1076 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001077 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001078 tv_update_date(0, 1);
1079 lua->run_time += now_ms - lua->start_time;
1080 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001081 lua_settop(lua->T, 0); /* Empty the stack. */
1082 if (!lua_checkstack(lua->T, 1)) {
1083 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001084 break;
1085 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001086 lua_pushfstring(lua->T, "execution timeout");
1087 ret = HLUA_E_ERRMSG;
1088 break;
1089 }
1090 /* Process the forced yield. if the general yield is not allowed or
1091 * if no task were associated this the current Lua execution
1092 * coroutine, we resume the execution. Else we want to return in the
1093 * scheduler and we want to be waked up again, to continue the
1094 * current Lua execution. So we schedule our own task.
1095 */
1096 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001097 if (!yield_allowed || !lua->task)
1098 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001099 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001100 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001101 if (!yield_allowed) {
1102 lua_settop(lua->T, 0); /* Empty the stack. */
1103 if (!lua_checkstack(lua->T, 1)) {
1104 ret = HLUA_E_ERR;
1105 break;
1106 }
1107 lua_pushfstring(lua->T, "yield not allowed");
1108 ret = HLUA_E_ERRMSG;
1109 break;
1110 }
1111 ret = HLUA_E_AGAIN;
1112 break;
1113
1114 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001115
1116 /* Special exit case. The traditionnal exit is returned as an error
1117 * because the errors ares the only one mean to return immediately
1118 * from and lua execution.
1119 */
1120 if (lua->flags & HLUA_EXIT) {
1121 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001122 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001123 break;
1124 }
1125
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001126 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001127 if (!lua_checkstack(lua->T, 1)) {
1128 ret = HLUA_E_ERR;
1129 break;
1130 }
1131 msg = lua_tostring(lua->T, -1);
1132 lua_settop(lua->T, 0); /* Empty the stack. */
1133 lua_pop(lua->T, 1);
1134 if (msg)
1135 lua_pushfstring(lua->T, "runtime error: %s", msg);
1136 else
1137 lua_pushfstring(lua->T, "unknown runtime error");
1138 ret = HLUA_E_ERRMSG;
1139 break;
1140
1141 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001142 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001143 lua_settop(lua->T, 0); /* Empty the stack. */
1144 if (!lua_checkstack(lua->T, 1)) {
1145 ret = HLUA_E_ERR;
1146 break;
1147 }
1148 lua_pushfstring(lua->T, "out of memory error");
1149 ret = HLUA_E_ERRMSG;
1150 break;
1151
1152 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001153 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001154 if (!lua_checkstack(lua->T, 1)) {
1155 ret = HLUA_E_ERR;
1156 break;
1157 }
1158 msg = lua_tostring(lua->T, -1);
1159 lua_settop(lua->T, 0); /* Empty the stack. */
1160 lua_pop(lua->T, 1);
1161 if (msg)
1162 lua_pushfstring(lua->T, "message handler error: %s", msg);
1163 else
1164 lua_pushfstring(lua->T, "message handler error");
1165 ret = HLUA_E_ERRMSG;
1166 break;
1167
1168 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001169 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001170 lua_settop(lua->T, 0); /* Empty the stack. */
1171 if (!lua_checkstack(lua->T, 1)) {
1172 ret = HLUA_E_ERR;
1173 break;
1174 }
1175 lua_pushfstring(lua->T, "unknonwn error");
1176 ret = HLUA_E_ERRMSG;
1177 break;
1178 }
1179
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001180 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001181 if (lua->flags & HLUA_MUST_GC &&
1182 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001183 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1184
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001185 switch (ret) {
1186 case HLUA_E_AGAIN:
1187 break;
1188
1189 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001190 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001191 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001192 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001193 break;
1194
1195 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001196 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001197 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001198 hlua_ctx_renew(lua, 0);
1199 break;
1200
1201 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001202 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001203 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001204 break;
1205 }
1206
1207 return ret;
1208}
1209
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001210/* This function exit the current code. */
1211__LJMP static int hlua_done(lua_State *L)
1212{
1213 struct hlua *hlua = hlua_gethlua(L);
1214
1215 hlua->flags |= HLUA_EXIT;
1216 WILL_LJMP(lua_error(L));
1217
1218 return 0;
1219}
1220
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001221/* This function is an LUA binding. It provides a function
1222 * for deleting ACL from a referenced ACL file.
1223 */
1224__LJMP static int hlua_del_acl(lua_State *L)
1225{
1226 const char *name;
1227 const char *key;
1228 struct pat_ref *ref;
1229
1230 MAY_LJMP(check_args(L, 2, "del_acl"));
1231
1232 name = MAY_LJMP(luaL_checkstring(L, 1));
1233 key = MAY_LJMP(luaL_checkstring(L, 2));
1234
1235 ref = pat_ref_lookup(name);
1236 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001237 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001238
1239 pat_ref_delete(ref, key);
1240 return 0;
1241}
1242
1243/* This function is an LUA binding. It provides a function
1244 * for deleting map entry from a referenced map file.
1245 */
1246static int hlua_del_map(lua_State *L)
1247{
1248 const char *name;
1249 const char *key;
1250 struct pat_ref *ref;
1251
1252 MAY_LJMP(check_args(L, 2, "del_map"));
1253
1254 name = MAY_LJMP(luaL_checkstring(L, 1));
1255 key = MAY_LJMP(luaL_checkstring(L, 2));
1256
1257 ref = pat_ref_lookup(name);
1258 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001259 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001260
1261 pat_ref_delete(ref, key);
1262 return 0;
1263}
1264
1265/* This function is an LUA binding. It provides a function
1266 * for adding ACL pattern from a referenced ACL file.
1267 */
1268static int hlua_add_acl(lua_State *L)
1269{
1270 const char *name;
1271 const char *key;
1272 struct pat_ref *ref;
1273
1274 MAY_LJMP(check_args(L, 2, "add_acl"));
1275
1276 name = MAY_LJMP(luaL_checkstring(L, 1));
1277 key = MAY_LJMP(luaL_checkstring(L, 2));
1278
1279 ref = pat_ref_lookup(name);
1280 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001281 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001282
1283 if (pat_ref_find_elt(ref, key) == NULL)
1284 pat_ref_add(ref, key, NULL, NULL);
1285 return 0;
1286}
1287
1288/* This function is an LUA binding. It provides a function
1289 * for setting map pattern and sample from a referenced map
1290 * file.
1291 */
1292static int hlua_set_map(lua_State *L)
1293{
1294 const char *name;
1295 const char *key;
1296 const char *value;
1297 struct pat_ref *ref;
1298
1299 MAY_LJMP(check_args(L, 3, "set_map"));
1300
1301 name = MAY_LJMP(luaL_checkstring(L, 1));
1302 key = MAY_LJMP(luaL_checkstring(L, 2));
1303 value = MAY_LJMP(luaL_checkstring(L, 3));
1304
1305 ref = pat_ref_lookup(name);
1306 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001307 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001308
1309 if (pat_ref_find_elt(ref, key) != NULL)
1310 pat_ref_set(ref, key, value, NULL);
1311 else
1312 pat_ref_add(ref, key, value, NULL);
1313 return 0;
1314}
1315
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001316/* A class is a lot of memory that contain data. This data can be a table,
1317 * an integer or user data. This data is associated with a metatable. This
1318 * metatable have an original version registred in the global context with
1319 * the name of the object (_G[<name>] = <metable> ).
1320 *
1321 * A metable is a table that modify the standard behavior of a standard
1322 * access to the associated data. The entries of this new metatable are
1323 * defined as is:
1324 *
1325 * http://lua-users.org/wiki/MetatableEvents
1326 *
1327 * __index
1328 *
1329 * we access an absent field in a table, the result is nil. This is
1330 * true, but it is not the whole truth. Actually, such access triggers
1331 * the interpreter to look for an __index metamethod: If there is no
1332 * such method, as usually happens, then the access results in nil;
1333 * otherwise, the metamethod will provide the result.
1334 *
1335 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1336 * the key does not appear in the table, but the metatable has an __index
1337 * property:
1338 *
1339 * - if the value is a function, the function is called, passing in the
1340 * table and the key; the return value of that function is returned as
1341 * the result.
1342 *
1343 * - if the value is another table, the value of the key in that table is
1344 * asked for and returned (and if it doesn't exist in that table, but that
1345 * table's metatable has an __index property, then it continues on up)
1346 *
1347 * - Use "rawget(myTable,key)" to skip this metamethod.
1348 *
1349 * http://www.lua.org/pil/13.4.1.html
1350 *
1351 * __newindex
1352 *
1353 * Like __index, but control property assignment.
1354 *
1355 * __mode - Control weak references. A string value with one or both
1356 * of the characters 'k' and 'v' which specifies that the the
1357 * keys and/or values in the table are weak references.
1358 *
1359 * __call - Treat a table like a function. When a table is followed by
1360 * parenthesis such as "myTable( 'foo' )" and the metatable has
1361 * a __call key pointing to a function, that function is invoked
1362 * (passing any specified arguments) and the return value is
1363 * returned.
1364 *
1365 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1366 * called, if the metatable for myTable has a __metatable
1367 * key, the value of that key is returned instead of the
1368 * actual metatable.
1369 *
1370 * __tostring - Control string representation. When the builtin
1371 * "tostring( myTable )" function is called, if the metatable
1372 * for myTable has a __tostring property set to a function,
1373 * that function is invoked (passing myTable to it) and the
1374 * return value is used as the string representation.
1375 *
1376 * __len - Control table length. When the table length is requested using
1377 * the length operator ( '#' ), if the metatable for myTable has
1378 * a __len key pointing to a function, that function is invoked
1379 * (passing myTable to it) and the return value used as the value
1380 * of "#myTable".
1381 *
1382 * __gc - Userdata finalizer code. When userdata is set to be garbage
1383 * collected, if the metatable has a __gc field pointing to a
1384 * function, that function is first invoked, passing the userdata
1385 * to it. The __gc metamethod is not called for tables.
1386 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1387 *
1388 * Special metamethods for redefining standard operators:
1389 * http://www.lua.org/pil/13.1.html
1390 *
1391 * __add "+"
1392 * __sub "-"
1393 * __mul "*"
1394 * __div "/"
1395 * __unm "!"
1396 * __pow "^"
1397 * __concat ".."
1398 *
1399 * Special methods for redfining standar relations
1400 * http://www.lua.org/pil/13.2.html
1401 *
1402 * __eq "=="
1403 * __lt "<"
1404 * __le "<="
1405 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001406
1407/*
1408 *
1409 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001410 * Class Map
1411 *
1412 *
1413 */
1414
1415/* Returns a struct hlua_map if the stack entry "ud" is
1416 * a class session, otherwise it throws an error.
1417 */
1418__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1419{
1420 return (struct map_descriptor *)MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
1421}
1422
1423/* This function is the map constructor. It don't need
1424 * the class Map object. It creates and return a new Map
1425 * object. It must be called only during "body" or "init"
1426 * context because it process some filesystem accesses.
1427 */
1428__LJMP static int hlua_map_new(struct lua_State *L)
1429{
1430 const char *fn;
1431 int match = PAT_MATCH_STR;
1432 struct sample_conv conv;
1433 const char *file = "";
1434 int line = 0;
1435 lua_Debug ar;
1436 char *err = NULL;
1437 struct arg args[2];
1438
1439 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1440 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1441
1442 fn = MAY_LJMP(luaL_checkstring(L, 1));
1443
1444 if (lua_gettop(L) >= 2) {
1445 match = MAY_LJMP(luaL_checkinteger(L, 2));
1446 if (match < 0 || match >= PAT_MATCH_NUM)
1447 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1448 }
1449
1450 /* Get Lua filename and line number. */
1451 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1452 lua_getinfo(L, "Sl", &ar); /* get info about it */
1453 if (ar.currentline > 0) { /* is there info? */
1454 file = ar.short_src;
1455 line = ar.currentline;
1456 }
1457 }
1458
1459 /* fill fake sample_conv struct. */
1460 conv.kw = ""; /* unused. */
1461 conv.process = NULL; /* unused. */
1462 conv.arg_mask = 0; /* unused. */
1463 conv.val_args = NULL; /* unused. */
1464 conv.out_type = SMP_T_STR;
1465 conv.private = (void *)(long)match;
1466 switch (match) {
1467 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1468 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1469 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1470 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1471 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1472 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1473 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001474 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001475 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1476 default:
1477 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1478 }
1479
1480 /* fill fake args. */
1481 args[0].type = ARGT_STR;
1482 args[0].data.str.str = (char *)fn;
1483 args[1].type = ARGT_STOP;
1484
1485 /* load the map. */
1486 if (!sample_load_map(args, &conv, file, line, &err)) {
1487 /* error case: we cant use luaL_error because we must
1488 * free the err variable.
1489 */
1490 luaL_where(L, 1);
1491 lua_pushfstring(L, "'new': %s.", err);
1492 lua_concat(L, 2);
1493 free(err);
1494 WILL_LJMP(lua_error(L));
1495 }
1496
1497 /* create the lua object. */
1498 lua_newtable(L);
1499 lua_pushlightuserdata(L, args[0].data.map);
1500 lua_rawseti(L, -2, 0);
1501
1502 /* Pop a class Map metatable and affect it to the userdata. */
1503 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1504 lua_setmetatable(L, -2);
1505
1506
1507 return 1;
1508}
1509
1510__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1511{
1512 struct map_descriptor *desc;
1513 struct pattern *pat;
1514 struct sample smp;
1515
1516 MAY_LJMP(check_args(L, 2, "lookup"));
1517 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001518 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001519 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001520 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001521 }
1522 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001523 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001524 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001525 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 +02001526 }
1527
1528 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001529 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001530 if (str)
1531 lua_pushstring(L, "");
1532 else
1533 lua_pushnil(L);
1534 return 1;
1535 }
1536
1537 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001538 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001539 return 1;
1540}
1541
1542__LJMP static int hlua_map_lookup(struct lua_State *L)
1543{
1544 return _hlua_map_lookup(L, 0);
1545}
1546
1547__LJMP static int hlua_map_slookup(struct lua_State *L)
1548{
1549 return _hlua_map_lookup(L, 1);
1550}
1551
1552/*
1553 *
1554 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001555 * Class Socket
1556 *
1557 *
1558 */
1559
1560__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1561{
1562 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1563}
1564
1565/* This function is the handler called for each I/O on the established
1566 * connection. It is used for notify space avalaible to send or data
1567 * received.
1568 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001569static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001570{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001571 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001572 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001573
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001574 /* If the connection object is not avalaible, close all the
1575 * streams and wakeup everithing waiting for.
1576 */
1577 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001578 si_shutw(si);
1579 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001580 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001581 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1582 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001583 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001584 }
1585
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001586 /* If we cant write, wakeup the pending write signals. */
1587 if (channel_output_closed(si_ic(si)))
1588 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1589
1590 /* If we cant read, wakeup the pending read signals. */
1591 if (channel_input_closed(si_oc(si)))
1592 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1593
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001594 /* if the connection is not estabkished, inform the stream that we want
1595 * to be notified whenever the connection completes.
1596 */
1597 if (!(c->flags & CO_FL_CONNECTED)) {
1598 si_applet_cant_get(si);
1599 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001600 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001601 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001602
1603 /* This function is called after the connect. */
1604 appctx->ctx.hlua.connected = 1;
1605
1606 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001607 if (channel_may_recv(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001608 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1609
1610 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001611 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001612 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1613}
1614
Willy Tarreau87b09662015-04-03 00:22:06 +02001615/* This function is called when the "struct stream" is destroyed.
1616 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001617 * Wake all the pending signals.
1618 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001619static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001620{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001621 /* Remove my link in the original object. */
1622 if (appctx->ctx.hlua.socket)
1623 appctx->ctx.hlua.socket->s = NULL;
1624
1625 /* Wake all the task waiting for me. */
1626 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1627 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1628}
1629
1630/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001631 * uses this object. If the stream does not exists, just quit.
1632 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001633 * pending signal can rest in the read and write lists. destroy
1634 * it.
1635 */
1636__LJMP static int hlua_socket_gc(lua_State *L)
1637{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001638 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001639 struct appctx *appctx;
1640
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001641 MAY_LJMP(check_args(L, 1, "__gc"));
1642
1643 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001644 if (!socket->s)
1645 return 0;
1646
Willy Tarreau87b09662015-04-03 00:22:06 +02001647 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001648 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001649 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001650 socket->s = NULL;
1651 appctx->ctx.hlua.socket = NULL;
1652
1653 return 0;
1654}
1655
1656/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001657 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001658 */
1659__LJMP static int hlua_socket_close(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, "close"));
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 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001671 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001672 appctx = objt_appctx(socket->s->si[0].end);
1673 appctx->ctx.hlua.socket = NULL;
1674 socket->s = NULL;
1675
1676 return 0;
1677}
1678
1679/* This Lua function assumes that the stack contain three parameters.
1680 * 1 - USERDATA containing a struct socket
1681 * 2 - INTEGER with values of the macro defined below
1682 * If the integer is -1, we must read at most one line.
1683 * If the integer is -2, we ust read all the data until the
1684 * end of the stream.
1685 * If the integer is positive value, we must read a number of
1686 * bytes corresponding to this value.
1687 */
1688#define HLSR_READ_LINE (-1)
1689#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001690__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001691{
1692 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1693 int wanted = lua_tointeger(L, 2);
1694 struct hlua *hlua = hlua_gethlua(L);
1695 struct appctx *appctx;
1696 int len;
1697 int nblk;
1698 char *blk1;
1699 int len1;
1700 char *blk2;
1701 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001702 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001703 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001704
1705 /* Check if this lua stack is schedulable. */
1706 if (!hlua || !hlua->task)
1707 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1708 "'frontend', 'backend' or 'task'"));
1709
1710 /* check for connection closed. If some data where read, return it. */
1711 if (!socket->s)
1712 goto connection_closed;
1713
Willy Tarreau94aa6172015-03-13 14:19:06 +01001714 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001715 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001716 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001717 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001718 if (nblk < 0) /* Connection close. */
1719 goto connection_closed;
1720 if (nblk == 0) /* No data avalaible. */
1721 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001722
1723 /* remove final \r\n. */
1724 if (nblk == 1) {
1725 if (blk1[len1-1] == '\n') {
1726 len1--;
1727 skip_at_end++;
1728 if (blk1[len1-1] == '\r') {
1729 len1--;
1730 skip_at_end++;
1731 }
1732 }
1733 }
1734 else {
1735 if (blk2[len2-1] == '\n') {
1736 len2--;
1737 skip_at_end++;
1738 if (blk2[len2-1] == '\r') {
1739 len2--;
1740 skip_at_end++;
1741 }
1742 }
1743 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001744 }
1745
1746 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001747 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001748 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001749 if (nblk < 0) /* Connection close. */
1750 goto connection_closed;
1751 if (nblk == 0) /* No data avalaible. */
1752 goto connection_empty;
1753 }
1754
1755 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001756 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001757 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001758 if (nblk < 0) /* Connection close. */
1759 goto connection_closed;
1760 if (nblk == 0) /* No data avalaible. */
1761 goto connection_empty;
1762
1763 if (len1 > wanted) {
1764 nblk = 1;
1765 len1 = wanted;
1766 } if (nblk == 2 && len1 + len2 > wanted)
1767 len2 = wanted - len1;
1768 }
1769
1770 len = len1;
1771
1772 luaL_addlstring(&socket->b, blk1, len1);
1773 if (nblk == 2) {
1774 len += len2;
1775 luaL_addlstring(&socket->b, blk2, len2);
1776 }
1777
1778 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001779 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001780
1781 /* Don't wait anything. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001782 stream_int_notify(&socket->s->si[0]);
1783 stream_int_update_applet(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001784
1785 /* If the pattern reclaim to read all the data
1786 * in the connection, got out.
1787 */
1788 if (wanted == HLSR_READ_ALL)
1789 goto connection_empty;
1790 else if (wanted >= 0 && len < wanted)
1791 goto connection_empty;
1792
1793 /* Return result. */
1794 luaL_pushresult(&socket->b);
1795 return 1;
1796
1797connection_closed:
1798
1799 /* If the buffer containds data. */
1800 if (socket->b.n > 0) {
1801 luaL_pushresult(&socket->b);
1802 return 1;
1803 }
1804 lua_pushnil(L);
1805 lua_pushstring(L, "connection closed.");
1806 return 2;
1807
1808connection_empty:
1809
1810 appctx = objt_appctx(socket->s->si[0].end);
1811 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1812 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001813 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001814 return 0;
1815}
1816
1817/* This Lus function gets two parameters. The first one can be string
1818 * or a number. If the string is "*l", the user require one line. If
1819 * the string is "*a", the user require all the content of the stream.
1820 * If the value is a number, the user require a number of bytes equal
1821 * to the value. The default value is "*l" (a line).
1822 *
1823 * This paraeter with a variable type is converted in integer. This
1824 * integer takes this values:
1825 * -1 : read a line
1826 * -2 : read all the stream
1827 * >0 : amount if bytes.
1828 *
1829 * The second parameter is optinal. It contains a string that must be
1830 * concatenated with the read data.
1831 */
1832__LJMP static int hlua_socket_receive(struct lua_State *L)
1833{
1834 int wanted = HLSR_READ_LINE;
1835 const char *pattern;
1836 int type;
1837 char *error;
1838 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001839 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001840
1841 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1842 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1843
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001844 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001845
1846 /* check for pattern. */
1847 if (lua_gettop(L) >= 2) {
1848 type = lua_type(L, 2);
1849 if (type == LUA_TSTRING) {
1850 pattern = lua_tostring(L, 2);
1851 if (strcmp(pattern, "*a") == 0)
1852 wanted = HLSR_READ_ALL;
1853 else if (strcmp(pattern, "*l") == 0)
1854 wanted = HLSR_READ_LINE;
1855 else {
1856 wanted = strtoll(pattern, &error, 10);
1857 if (*error != '\0')
1858 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1859 }
1860 }
1861 else if (type == LUA_TNUMBER) {
1862 wanted = lua_tointeger(L, 2);
1863 if (wanted < 0)
1864 WILL_LJMP(luaL_error(L, "Unsupported size."));
1865 }
1866 }
1867
1868 /* Set pattern. */
1869 lua_pushinteger(L, wanted);
1870 lua_replace(L, 2);
1871
1872 /* init bufffer, and fiil it wih prefix. */
1873 luaL_buffinit(L, &socket->b);
1874
1875 /* Check prefix. */
1876 if (lua_gettop(L) >= 3) {
1877 if (lua_type(L, 3) != LUA_TSTRING)
1878 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1879 pattern = lua_tolstring(L, 3, &len);
1880 luaL_addlstring(&socket->b, pattern, len);
1881 }
1882
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001883 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001884}
1885
1886/* Write the Lua input string in the output buffer.
1887 * This fucntion returns a yield if no space are available.
1888 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001889static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001890{
1891 struct hlua_socket *socket;
1892 struct hlua *hlua = hlua_gethlua(L);
1893 struct appctx *appctx;
1894 size_t buf_len;
1895 const char *buf;
1896 int len;
1897 int send_len;
1898 int sent;
1899
1900 /* Check if this lua stack is schedulable. */
1901 if (!hlua || !hlua->task)
1902 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1903 "'frontend', 'backend' or 'task'"));
1904
1905 /* Get object */
1906 socket = MAY_LJMP(hlua_checksocket(L, 1));
1907 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001908 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001909
1910 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001911 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001912 lua_pushinteger(L, -1);
1913 return 1;
1914 }
1915
1916 /* Update the input buffer data. */
1917 buf += sent;
1918 send_len = buf_len - sent;
1919
1920 /* All the data are sent. */
1921 if (sent >= buf_len)
1922 return 1; /* Implicitly return the length sent. */
1923
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001924 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1925 * the request buffer if its not required.
1926 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001927 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001928 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001929 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001930 goto hlua_socket_write_yield_return;
1931 }
1932 }
1933
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001934 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001935 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001936 if (len <= 0)
1937 goto hlua_socket_write_yield_return;
1938
1939 /* send data */
1940 if (len < send_len)
1941 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001942 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001943
1944 /* "Not enough space" (-1), "Buffer too little to contain
1945 * the data" (-2) are not expected because the available length
1946 * is tested.
1947 * Other unknown error are also not expected.
1948 */
1949 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001950 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001951 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001952
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001953 MAY_LJMP(hlua_socket_close(L));
1954 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001955 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001956 return 1;
1957 }
1958
1959 /* update buffers. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001960 stream_int_notify(&socket->s->si[0]);
1961 stream_int_update_applet(&socket->s->si[0]);
1962
Willy Tarreau94aa6172015-03-13 14:19:06 +01001963 socket->s->req.rex = TICK_ETERNITY;
1964 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001965
1966 /* Update length sent. */
1967 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001968 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001969
1970 /* All the data buffer is sent ? */
1971 if (sent + len >= buf_len)
1972 return 1;
1973
1974hlua_socket_write_yield_return:
1975 appctx = objt_appctx(socket->s->si[0].end);
1976 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1977 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001978 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001979 return 0;
1980}
1981
1982/* This function initiate the send of data. It just check the input
1983 * parameters and push an integer in the Lua stack that contain the
1984 * amount of data writed in the buffer. This is used by the function
1985 * "hlua_socket_write_yield" that can yield.
1986 *
1987 * The Lua function gets between 3 and 4 parameters. The first one is
1988 * the associated object. The second is a string buffer. The third is
1989 * a facultative integer that represents where is the buffer position
1990 * of the start of the data that can send. The first byte is the
1991 * position "1". The default value is "1". The fourth argument is a
1992 * facultative integer that represents where is the buffer position
1993 * of the end of the data that can send. The default is the last byte.
1994 */
1995static int hlua_socket_send(struct lua_State *L)
1996{
1997 int i;
1998 int j;
1999 const char *buf;
2000 size_t buf_len;
2001
2002 /* Check number of arguments. */
2003 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2004 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2005
2006 /* Get the string. */
2007 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2008
2009 /* Get and check j. */
2010 if (lua_gettop(L) == 4) {
2011 j = MAY_LJMP(luaL_checkinteger(L, 4));
2012 if (j < 0)
2013 j = buf_len + j + 1;
2014 if (j > buf_len)
2015 j = buf_len + 1;
2016 lua_pop(L, 1);
2017 }
2018 else
2019 j = buf_len;
2020
2021 /* Get and check i. */
2022 if (lua_gettop(L) == 3) {
2023 i = MAY_LJMP(luaL_checkinteger(L, 3));
2024 if (i < 0)
2025 i = buf_len + i + 1;
2026 if (i > buf_len)
2027 i = buf_len + 1;
2028 lua_pop(L, 1);
2029 } else
2030 i = 1;
2031
2032 /* Check bth i and j. */
2033 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002034 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002035 return 1;
2036 }
2037 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002038 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002039 return 1;
2040 }
2041 if (i == 0)
2042 i = 1;
2043 if (j == 0)
2044 j = 1;
2045
2046 /* Pop the string. */
2047 lua_pop(L, 1);
2048
2049 /* Update the buffer length. */
2050 buf += i - 1;
2051 buf_len = j - i + 1;
2052 lua_pushlstring(L, buf, buf_len);
2053
2054 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002055 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002056
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002057 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002058}
2059
Willy Tarreau22b0a682015-06-17 19:43:49 +02002060#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002061__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2062{
2063 static char buffer[SOCKET_INFO_MAX_LEN];
2064 int ret;
2065 int len;
2066 char *p;
2067
2068 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2069 if (ret <= 0) {
2070 lua_pushnil(L);
2071 return 1;
2072 }
2073
2074 if (ret == AF_UNIX) {
2075 lua_pushstring(L, buffer+1);
2076 return 1;
2077 }
2078 else if (ret == AF_INET6) {
2079 buffer[0] = '[';
2080 len = strlen(buffer);
2081 buffer[len] = ']';
2082 len++;
2083 buffer[len] = ':';
2084 len++;
2085 p = buffer;
2086 }
2087 else if (ret == AF_INET) {
2088 p = buffer + 1;
2089 len = strlen(p);
2090 p[len] = ':';
2091 len++;
2092 }
2093 else {
2094 lua_pushnil(L);
2095 return 1;
2096 }
2097
2098 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2099 lua_pushnil(L);
2100 return 1;
2101 }
2102
2103 lua_pushstring(L, p);
2104 return 1;
2105}
2106
2107/* Returns information about the peer of the connection. */
2108__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2109{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002110 struct hlua_socket *socket;
2111 struct connection *conn;
2112
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002113 MAY_LJMP(check_args(L, 1, "getpeername"));
2114
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002115 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002116
2117 /* Check if the tcp object is avalaible. */
2118 if (!socket->s) {
2119 lua_pushnil(L);
2120 return 1;
2121 }
2122
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002123 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002124 if (!conn) {
2125 lua_pushnil(L);
2126 return 1;
2127 }
2128
2129 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
2130 unsigned int salen = sizeof(conn->addr.to);
2131 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
2132 lua_pushnil(L);
2133 return 1;
2134 }
2135 conn->flags |= CO_FL_ADDR_TO_SET;
2136 }
2137
2138 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2139}
2140
2141/* Returns information about my connection side. */
2142static int hlua_socket_getsockname(struct lua_State *L)
2143{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002144 struct hlua_socket *socket;
2145 struct connection *conn;
2146
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002147 MAY_LJMP(check_args(L, 1, "getsockname"));
2148
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002149 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002150
2151 /* Check if the tcp object is avalaible. */
2152 if (!socket->s) {
2153 lua_pushnil(L);
2154 return 1;
2155 }
2156
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002157 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002158 if (!conn) {
2159 lua_pushnil(L);
2160 return 1;
2161 }
2162
2163 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2164 unsigned int salen = sizeof(conn->addr.from);
2165 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2166 lua_pushnil(L);
2167 return 1;
2168 }
2169 conn->flags |= CO_FL_ADDR_FROM_SET;
2170 }
2171
2172 return hlua_socket_info(L, &conn->addr.from);
2173}
2174
2175/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002176static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002177 .obj_type = OBJ_TYPE_APPLET,
2178 .name = "<LUA_TCP>",
2179 .fct = hlua_socket_handler,
2180 .release = hlua_socket_release,
2181};
2182
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002183__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002184{
2185 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2186 struct hlua *hlua = hlua_gethlua(L);
2187 struct appctx *appctx;
2188
2189 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002190 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002191 lua_pushnil(L);
2192 lua_pushstring(L, "Can't connect");
2193 return 2;
2194 }
2195
2196 appctx = objt_appctx(socket->s->si[0].end);
2197
2198 /* Check for connection established. */
2199 if (appctx->ctx.hlua.connected) {
2200 lua_pushinteger(L, 1);
2201 return 1;
2202 }
2203
2204 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2205 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002206 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002207 return 0;
2208}
2209
2210/* This function fail or initite the connection. */
2211__LJMP static int hlua_socket_connect(struct lua_State *L)
2212{
2213 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002214 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002215 const char *ip;
2216 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002217 struct hlua *hlua;
2218 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002219 int low, high;
2220 struct sockaddr_storage *addr;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002221
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002222 if (lua_gettop(L) < 2)
2223 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002224
2225 /* Get args. */
2226 socket = MAY_LJMP(hlua_checksocket(L, 1));
2227 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002228 if (lua_gettop(L) >= 3)
2229 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002230
Willy Tarreau973a5422015-08-05 21:47:23 +02002231 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002232 if (!conn)
2233 WILL_LJMP(luaL_error(L, "connect: internal error"));
2234
Willy Tarreau3adac082015-09-26 17:51:09 +02002235 /* needed for the connection not to be closed */
2236 conn->target = socket->s->target;
2237
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002238 /* Parse ip address. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002239 addr = str2sa_range(ip, &low, &high, NULL, NULL, NULL, 0);
2240 if (!addr)
2241 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
2242 if (low != high)
2243 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
2244 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002245
2246 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002247 if (low == 0) {
2248 if (conn->addr.to.ss_family == AF_INET) {
2249 if (port == -1)
2250 WILL_LJMP(luaL_error(L, "connect: port missing"));
2251 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2252 } else if (conn->addr.to.ss_family == AF_INET6) {
2253 if (port == -1)
2254 WILL_LJMP(luaL_error(L, "connect: port missing"));
2255 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2256 }
2257 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002258
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002259 hlua = hlua_gethlua(L);
2260 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002261
2262 /* inform the stream that we want to be notified whenever the
2263 * connection completes.
2264 */
2265 si_applet_cant_get(&socket->s->si[0]);
2266 si_applet_cant_put(&socket->s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002267 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002268
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002269 hlua->flags |= HLUA_MUST_GC;
2270
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002271 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2272 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002273 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002274
2275 return 0;
2276}
2277
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002278#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002279__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2280{
2281 struct hlua_socket *socket;
2282
2283 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2284 socket = MAY_LJMP(hlua_checksocket(L, 1));
2285 socket->s->target = &socket_ssl.obj_type;
2286 return MAY_LJMP(hlua_socket_connect(L));
2287}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002288#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002289
2290__LJMP static int hlua_socket_setoption(struct lua_State *L)
2291{
2292 return 0;
2293}
2294
2295__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2296{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002297 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002298 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002299
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002300 MAY_LJMP(check_args(L, 2, "settimeout"));
2301
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002302 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002303 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002304
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002305 socket->s->req.rto = tmout;
2306 socket->s->req.wto = tmout;
2307 socket->s->res.rto = tmout;
2308 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002309
2310 return 0;
2311}
2312
2313__LJMP static int hlua_socket_new(lua_State *L)
2314{
2315 struct hlua_socket *socket;
2316 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002317 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002318 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002319 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002320
2321 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002322 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323 hlua_pusherror(L, "socket: full stack");
2324 goto out_fail_conf;
2325 }
2326
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002327 /* Create the object: obj[0] = userdata. */
2328 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002329 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002330 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002331 memset(socket, 0, sizeof(*socket));
2332
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002333 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002334 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002335 hlua_pusherror(L, "socket: uninitialized pools.");
2336 goto out_fail_conf;
2337 }
2338
Willy Tarreau87b09662015-04-03 00:22:06 +02002339 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002340 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2341 lua_setmetatable(L, -2);
2342
Willy Tarreaud420a972015-04-06 00:39:18 +02002343 /* Create the applet context */
2344 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002345 if (!appctx) {
2346 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002347 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002348 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002349
Willy Tarreaud420a972015-04-06 00:39:18 +02002350 appctx->ctx.hlua.socket = socket;
2351 appctx->ctx.hlua.connected = 0;
2352 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2353 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002354
Willy Tarreaud420a972015-04-06 00:39:18 +02002355 /* Now create a session, task and stream for this applet */
2356 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2357 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002358 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002359 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002360 }
2361
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002362 task = task_new();
2363 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002364 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002365 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002366 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002367 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002368
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002369 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002370 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002371 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002372 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002373 }
2374
Willy Tarreaud420a972015-04-06 00:39:18 +02002375 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002376 socket->s = strm;
2377 strm->hlua.T = NULL;
2378 strm->hlua.Tref = LUA_REFNIL;
2379 strm->hlua.Mref = LUA_REFNIL;
2380 strm->hlua.nargs = 0;
2381 strm->hlua.flags = 0;
2382 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002383
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002384 /* Configure "right" stream interface. this "si" is used to connect
2385 * and retrieve data from the server. The connection is initialized
2386 * with the "struct server".
2387 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002388 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002389
2390 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002391 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2392 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002393
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002394 /* Update statistics counters. */
2395 socket_proxy.feconn++; /* beconn will be increased later */
2396 jobs++;
2397 totalconn++;
2398
2399 /* Return yield waiting for connection. */
2400 return 1;
2401
Willy Tarreaud420a972015-04-06 00:39:18 +02002402 out_fail_stream:
2403 task_free(task);
2404 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002405 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002406 out_fail_sess:
2407 appctx_free(appctx);
2408 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002409 WILL_LJMP(lua_error(L));
2410 return 0;
2411}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002412
2413/*
2414 *
2415 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002416 * Class Channel
2417 *
2418 *
2419 */
2420
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002421/* The state between the channel data and the HTTP parser state can be
2422 * unconsistent, so reset the parser and call it again. Warning, this
2423 * action not revalidate the request and not send a 400 if the modified
2424 * resuest is not valid.
2425 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002426 * This function never fails. The direction is set using dir, which equals
2427 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002428 */
2429static void hlua_resynchonize_proto(struct stream *stream, int dir)
2430{
2431 /* Protocol HTTP. */
2432 if (stream->be->mode == PR_MODE_HTTP) {
2433
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002434 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002435 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002436 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002437 http_txn_reset_res(stream->txn);
2438
2439 if (stream->txn->hdr_idx.v)
2440 hdr_idx_init(&stream->txn->hdr_idx);
2441
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002442 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002443 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002444 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002445 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2446 }
2447}
2448
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002449/* Check the protocole integrity after the Lua manipulations. Close the stream
2450 * and returns 0 if fails, otherwise returns 1. The direction is set using dir,
2451 * which equals either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002452 */
2453static int hlua_check_proto(struct stream *stream, int dir)
2454{
2455 const struct chunk msg = { .len = 0 };
2456
Willy Tarreau9af89f72015-09-26 11:50:08 +02002457 /* Protocol HTTP. The message parsing state must match the request or
2458 * response state. The problem that may happen is that Lua modifies
2459 * the request or response message *after* it was parsed, and corrupted
2460 * it so that it could not be processed anymore. We just need to verify
2461 * if the parser is still expected to run or not.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002462 */
2463 if (stream->be->mode == PR_MODE_HTTP) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002464 if (dir == SMP_OPT_DIR_REQ &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002465 !(stream->req.analysers & AN_REQ_WAIT_HTTP) &&
2466 stream->txn->req.msg_state < HTTP_MSG_BODY) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002467 stream_int_retnclose(&stream->si[0], &msg);
2468 return 0;
2469 }
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002470 else if (dir == SMP_OPT_DIR_RES &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002471 !(stream->res.analysers & AN_RES_WAIT_HTTP) &&
2472 stream->txn->rsp.msg_state < HTTP_MSG_BODY) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002473 stream_int_retnclose(&stream->si[0], &msg);
2474 return 0;
2475 }
2476 }
2477 return 1;
2478}
2479
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002480/* Returns the struct hlua_channel join to the class channel in the
2481 * stack entry "ud" or throws an argument error.
2482 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002483__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002484{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002485 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002486}
2487
Willy Tarreau47860ed2015-03-10 14:07:50 +01002488/* Pushes the channel onto the top of the stack. If the stask does not have a
2489 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002490 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002491static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002492{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002493 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002494 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002495 return 0;
2496
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002497 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002498 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002499 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002500
2501 /* Pop a class sesison metatable and affect it to the userdata. */
2502 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2503 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002504 return 1;
2505}
2506
2507/* Duplicate all the data present in the input channel and put it
2508 * in a string LUA variables. Returns -1 and push a nil value in
2509 * the stack if the channel is closed and all the data are consumed,
2510 * returns 0 if no data are available, otherwise it returns the length
2511 * of the builded string.
2512 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002513static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002514{
2515 char *blk1;
2516 char *blk2;
2517 int len1;
2518 int len2;
2519 int ret;
2520 luaL_Buffer b;
2521
Willy Tarreau47860ed2015-03-10 14:07:50 +01002522 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002523 if (unlikely(ret == 0))
2524 return 0;
2525
2526 if (unlikely(ret < 0)) {
2527 lua_pushnil(L);
2528 return -1;
2529 }
2530
2531 luaL_buffinit(L, &b);
2532 luaL_addlstring(&b, blk1, len1);
2533 if (unlikely(ret == 2))
2534 luaL_addlstring(&b, blk2, len2);
2535 luaL_pushresult(&b);
2536
2537 if (unlikely(ret == 2))
2538 return len1 + len2;
2539 return len1;
2540}
2541
2542/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2543 * a yield. This function keep the data in the buffer.
2544 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002545__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002546{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002547 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002548
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002549 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2550
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002551 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002552 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002553 return 1;
2554}
2555
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002556/* Check arguments for the function "hlua_channel_dup_yield". */
2557__LJMP static int hlua_channel_dup(lua_State *L)
2558{
2559 MAY_LJMP(check_args(L, 1, "dup"));
2560 MAY_LJMP(hlua_checkchannel(L, 1));
2561 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2562}
2563
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002564/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2565 * a yield. This function consumes the data in the buffer. It returns
2566 * a string containing the data or a nil pointer if no data are available
2567 * and the channel is closed.
2568 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002569__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002570{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002571 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002572 int ret;
2573
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002574 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002575
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002576 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002577 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002578 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002579
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002580 if (unlikely(ret == -1))
2581 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002582
Willy Tarreau47860ed2015-03-10 14:07:50 +01002583 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002584 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002585 return 1;
2586}
2587
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002588/* Check arguments for the fucntion "hlua_channel_get_yield". */
2589__LJMP static int hlua_channel_get(lua_State *L)
2590{
2591 MAY_LJMP(check_args(L, 1, "get"));
2592 MAY_LJMP(hlua_checkchannel(L, 1));
2593 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2594}
2595
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002596/* This functions consumes and returns one line. If the channel is closed,
2597 * and the last data does not contains a final '\n', the data are returned
2598 * without the final '\n'. When no more data are avalaible, it returns nil
2599 * value.
2600 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002601__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002602{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002603 char *blk1;
2604 char *blk2;
2605 int len1;
2606 int len2;
2607 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002608 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002609 int ret;
2610 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002611
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002612 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2613
Willy Tarreau47860ed2015-03-10 14:07:50 +01002614 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002615 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002616 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002617
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002618 if (ret == -1) {
2619 lua_pushnil(L);
2620 return 1;
2621 }
2622
2623 luaL_buffinit(L, &b);
2624 luaL_addlstring(&b, blk1, len1);
2625 len = len1;
2626 if (unlikely(ret == 2)) {
2627 luaL_addlstring(&b, blk2, len2);
2628 len += len2;
2629 }
2630 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002631 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002632 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002633 return 1;
2634}
2635
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002636/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2637__LJMP static int hlua_channel_getline(lua_State *L)
2638{
2639 MAY_LJMP(check_args(L, 1, "getline"));
2640 MAY_LJMP(hlua_checkchannel(L, 1));
2641 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2642}
2643
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002644/* This function takes a string as input, and append it at the
2645 * input side of channel. If the data is too big, but a space
2646 * is probably available after sending some data, the function
2647 * yield. If the data is bigger than the buffer, or if the
2648 * channel is closed, it returns -1. otherwise, it returns the
2649 * amount of data writed.
2650 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002651__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002652{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002653 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002654 size_t len;
2655 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2656 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2657 int ret;
2658 int max;
2659
Willy Tarreau47860ed2015-03-10 14:07:50 +01002660 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002661 if (max > len - l)
2662 max = len - l;
2663
Willy Tarreau47860ed2015-03-10 14:07:50 +01002664 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002665 if (ret == -2 || ret == -3) {
2666 lua_pushinteger(L, -1);
2667 return 1;
2668 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002669 if (ret == -1) {
2670 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002671 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002672 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002673 l += ret;
2674 lua_pop(L, 1);
2675 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002676 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002677
Willy Tarreau47860ed2015-03-10 14:07:50 +01002678 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2679 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002680 /* There are no space avalaible, and the output buffer is empty.
2681 * in this case, we cannot add more data, so we cannot yield,
2682 * we return the amount of copyied data.
2683 */
2684 return 1;
2685 }
2686 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002687 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002688 return 1;
2689}
2690
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002691/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002692 * of the writed string, or -1 if the channel is closed or if the
2693 * buffer size is too little for the data.
2694 */
2695__LJMP static int hlua_channel_append(lua_State *L)
2696{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002697 size_t len;
2698
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002699 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002700 MAY_LJMP(hlua_checkchannel(L, 1));
2701 MAY_LJMP(luaL_checklstring(L, 2, &len));
2702 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002703 lua_pushinteger(L, 0);
2704
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002705 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002706}
2707
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002708/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002709 * his process by cleaning the buffer. The result is a replacement
2710 * of the current data. It returns the length of the writed string,
2711 * or -1 if the channel is closed or if the buffer size is too
2712 * little for the data.
2713 */
2714__LJMP static int hlua_channel_set(lua_State *L)
2715{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002716 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002717
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002718 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002719 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002720 lua_pushinteger(L, 0);
2721
Willy Tarreau47860ed2015-03-10 14:07:50 +01002722 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002723
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002724 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002725}
2726
2727/* Append data in the output side of the buffer. This data is immediatly
2728 * sent. The fcuntion returns the ammount of data writed. If the buffer
2729 * cannot contains the data, the function yield. The function returns -1
2730 * if the channel is closed.
2731 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002732__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002733{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002734 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002735 size_t len;
2736 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2737 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2738 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002739 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002740
Willy Tarreau47860ed2015-03-10 14:07:50 +01002741 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002742 lua_pushinteger(L, -1);
2743 return 1;
2744 }
2745
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002746 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2747 * the request buffer if its not required.
2748 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002749 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002750 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002751 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002752 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002753 }
2754 }
2755
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002756 /* the writed data will be immediatly sent, so we can check
2757 * the avalaible space without taking in account the reserve.
2758 * The reserve is guaranted for the processing of incoming
2759 * data, because the buffer will be flushed.
2760 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002761 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002762
2763 /* If there are no space avalaible, and the output buffer is empty.
2764 * in this case, we cannot add more data, so we cannot yield,
2765 * we return the amount of copyied data.
2766 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002767 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002768 return 1;
2769
2770 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002771 if (max > len - l)
2772 max = len - l;
2773
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002774 /* The buffer avalaible size may be not contiguous. This test
2775 * detects a non contiguous buffer and realign it.
2776 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002777 if (bi_space_for_replace(chn->buf) < max)
2778 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002779
2780 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002781 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002782
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002783 /* buffer replace considers that the input part is filled.
2784 * so, I must forward these new data in the output part.
2785 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002786 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002787
2788 l += max;
2789 lua_pop(L, 1);
2790 lua_pushinteger(L, l);
2791
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002792 /* If there are no space avalaible, and the output buffer is empty.
2793 * in this case, we cannot add more data, so we cannot yield,
2794 * we return the amount of copyied data.
2795 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002796 max = chn->buf->size - buffer_len(chn->buf);
2797 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002798 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002799
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002800 if (l < len) {
2801 /* If we are waiting for space in the response buffer, we
2802 * must set the flag WAKERESWR. This flag required the task
2803 * wake up if any activity is detected on the response buffer.
2804 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002805 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002806 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002807 else
2808 HLUA_SET_WAKEREQWR(hlua);
2809 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002810 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002811
2812 return 1;
2813}
2814
2815/* Just a wraper of "_hlua_channel_send". This wrapper permits
2816 * yield the LUA process, and resume it without checking the
2817 * input arguments.
2818 */
2819__LJMP static int hlua_channel_send(lua_State *L)
2820{
2821 MAY_LJMP(check_args(L, 2, "send"));
2822 lua_pushinteger(L, 0);
2823
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002824 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002825}
2826
2827/* This function forward and amount of butes. The data pass from
2828 * the input side of the buffer to the output side, and can be
2829 * forwarded. This function never fails.
2830 *
2831 * The Lua function takes an amount of bytes to be forwarded in
2832 * imput. It returns the number of bytes forwarded.
2833 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002834__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002835{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002836 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002837 int len;
2838 int l;
2839 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002840 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002841
2842 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2843 len = MAY_LJMP(luaL_checkinteger(L, 2));
2844 l = MAY_LJMP(luaL_checkinteger(L, -1));
2845
2846 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002847 if (max > chn->buf->i)
2848 max = chn->buf->i;
2849 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002850 l += max;
2851
2852 lua_pop(L, 1);
2853 lua_pushinteger(L, l);
2854
2855 /* Check if it miss bytes to forward. */
2856 if (l < len) {
2857 /* The the input channel or the output channel are closed, we
2858 * must return the amount of data forwarded.
2859 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002860 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002861 return 1;
2862
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002863 /* If we are waiting for space data in the response buffer, we
2864 * must set the flag WAKERESWR. This flag required the task
2865 * wake up if any activity is detected on the response buffer.
2866 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002867 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002868 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002869 else
2870 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002871
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002872 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002873 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002874 }
2875
2876 return 1;
2877}
2878
2879/* Just check the input and prepare the stack for the previous
2880 * function "hlua_channel_forward_yield"
2881 */
2882__LJMP static int hlua_channel_forward(lua_State *L)
2883{
2884 MAY_LJMP(check_args(L, 2, "forward"));
2885 MAY_LJMP(hlua_checkchannel(L, 1));
2886 MAY_LJMP(luaL_checkinteger(L, 2));
2887
2888 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002889 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002890}
2891
2892/* Just returns the number of bytes available in the input
2893 * side of the buffer. This function never fails.
2894 */
2895__LJMP static int hlua_channel_get_in_len(lua_State *L)
2896{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002897 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002898
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002899 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002900 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002901 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002902 return 1;
2903}
2904
2905/* Just returns the number of bytes available in the output
2906 * side of the buffer. This function never fails.
2907 */
2908__LJMP static int hlua_channel_get_out_len(lua_State *L)
2909{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002910 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002911
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002912 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002913 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002914 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002915 return 1;
2916}
2917
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002918/*
2919 *
2920 *
2921 * Class Fetches
2922 *
2923 *
2924 */
2925
2926/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002927 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002928 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002929__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002930{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002931 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002932}
2933
2934/* This function creates and push in the stack a fetch object according
2935 * with a current TXN.
2936 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002937static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002938{
Willy Tarreau7073c472015-04-06 11:15:40 +02002939 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002940
2941 /* Check stack size. */
2942 if (!lua_checkstack(L, 3))
2943 return 0;
2944
2945 /* Create the object: obj[0] = userdata.
2946 * Note that the base of the Fetches object is the
2947 * transaction object.
2948 */
2949 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002950 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002951 lua_rawseti(L, -2, 0);
2952
Willy Tarreau7073c472015-04-06 11:15:40 +02002953 hsmp->s = txn->s;
2954 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01002955 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002956 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002957
2958 /* Pop a class sesison metatable and affect it to the userdata. */
2959 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2960 lua_setmetatable(L, -2);
2961
2962 return 1;
2963}
2964
2965/* This function is an LUA binding. It is called with each sample-fetch.
2966 * It uses closure argument to store the associated sample-fetch. It
2967 * returns only one argument or throws an error. An error is thrown
2968 * only if an error is encountered during the argument parsing. If
2969 * the "sample-fetch" function fails, nil is returned.
2970 */
2971__LJMP static int hlua_run_sample_fetch(lua_State *L)
2972{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002973 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002974 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002975 struct arg args[ARGM_NBARGS + 1];
2976 int i;
2977 struct sample smp;
2978
2979 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002980 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002981
2982 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002983 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002984
Thierry FOURNIERca988662015-12-20 18:43:03 +01002985 /* Check execution authorization. */
2986 if (f->use & SMP_USE_HTTP_ANY &&
2987 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
2988 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
2989 "is not available in Lua services", f->kw);
2990 WILL_LJMP(lua_error(L));
2991 }
2992
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002993 /* Get extra arguments. */
2994 for (i = 0; i < lua_gettop(L) - 1; i++) {
2995 if (i >= ARGM_NBARGS)
2996 break;
2997 hlua_lua2arg(L, i + 2, &args[i]);
2998 }
2999 args[i].type = ARGT_STOP;
3000
3001 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003002 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003003
3004 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003005 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003006 lua_pushfstring(L, "error in arguments");
3007 WILL_LJMP(lua_error(L));
3008 }
3009
3010 /* Initialise the sample. */
3011 memset(&smp, 0, sizeof(smp));
3012
3013 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003014 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003015 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003016 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003017 lua_pushstring(L, "");
3018 else
3019 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003020 return 1;
3021 }
3022
3023 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003024 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003025 hlua_smp2lua_str(L, &smp);
3026 else
3027 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003028 return 1;
3029}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003030
3031/*
3032 *
3033 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003034 * Class Converters
3035 *
3036 *
3037 */
3038
3039/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003040 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003041 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003042__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003043{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003044 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003045}
3046
3047/* This function creates and push in the stack a Converters object
3048 * according with a current TXN.
3049 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003050static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003051{
Willy Tarreau7073c472015-04-06 11:15:40 +02003052 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003053
3054 /* Check stack size. */
3055 if (!lua_checkstack(L, 3))
3056 return 0;
3057
3058 /* Create the object: obj[0] = userdata.
3059 * Note that the base of the Converters object is the
3060 * same than the TXN object.
3061 */
3062 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003063 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003064 lua_rawseti(L, -2, 0);
3065
Willy Tarreau7073c472015-04-06 11:15:40 +02003066 hsmp->s = txn->s;
3067 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003068 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003069 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003070
Willy Tarreau87b09662015-04-03 00:22:06 +02003071 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003072 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3073 lua_setmetatable(L, -2);
3074
3075 return 1;
3076}
3077
3078/* This function is an LUA binding. It is called with each converter.
3079 * It uses closure argument to store the associated converter. It
3080 * returns only one argument or throws an error. An error is thrown
3081 * only if an error is encountered during the argument parsing. If
3082 * the converter function function fails, nil is returned.
3083 */
3084__LJMP static int hlua_run_sample_conv(lua_State *L)
3085{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003086 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003087 struct sample_conv *conv;
3088 struct arg args[ARGM_NBARGS + 1];
3089 int i;
3090 struct sample smp;
3091
3092 /* Get closure arguments. */
3093 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
3094
3095 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003096 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003097
3098 /* Get extra arguments. */
3099 for (i = 0; i < lua_gettop(L) - 2; i++) {
3100 if (i >= ARGM_NBARGS)
3101 break;
3102 hlua_lua2arg(L, i + 3, &args[i]);
3103 }
3104 args[i].type = ARGT_STOP;
3105
3106 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003107 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003108
3109 /* Run the special args checker. */
3110 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3111 hlua_pusherror(L, "error in arguments");
3112 WILL_LJMP(lua_error(L));
3113 }
3114
3115 /* Initialise the sample. */
3116 if (!hlua_lua2smp(L, 2, &smp)) {
3117 hlua_pusherror(L, "error in the input argument");
3118 WILL_LJMP(lua_error(L));
3119 }
3120
Willy Tarreau1777ea62016-03-10 16:15:46 +01003121 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3122
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003123 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003124 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003125 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003126 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003127 WILL_LJMP(lua_error(L));
3128 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003129 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3130 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003131 hlua_pusherror(L, "error during the input argument casting");
3132 WILL_LJMP(lua_error(L));
3133 }
3134
3135 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003136 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003137 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003138 lua_pushstring(L, "");
3139 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003140 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003141 return 1;
3142 }
3143
3144 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003145 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003146 hlua_smp2lua_str(L, &smp);
3147 else
3148 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003149 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003150}
3151
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003152/*
3153 *
3154 *
3155 * Class AppletTCP
3156 *
3157 *
3158 */
3159
3160/* Returns a struct hlua_txn if the stack entry "ud" is
3161 * a class stream, otherwise it throws an error.
3162 */
3163__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3164{
3165 return (struct hlua_appctx *)MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
3166}
3167
3168/* This function creates and push in the stack an Applet object
3169 * according with a current TXN.
3170 */
3171static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3172{
3173 struct hlua_appctx *appctx;
3174 struct stream_interface *si = ctx->owner;
3175 struct stream *s = si_strm(si);
3176 struct proxy *p = s->be;
3177
3178 /* Check stack size. */
3179 if (!lua_checkstack(L, 3))
3180 return 0;
3181
3182 /* Create the object: obj[0] = userdata.
3183 * Note that the base of the Converters object is the
3184 * same than the TXN object.
3185 */
3186 lua_newtable(L);
3187 appctx = lua_newuserdata(L, sizeof(*appctx));
3188 lua_rawseti(L, -2, 0);
3189 appctx->appctx = ctx;
3190 appctx->htxn.s = s;
3191 appctx->htxn.p = p;
3192
3193 /* Create the "f" field that contains a list of fetches. */
3194 lua_pushstring(L, "f");
3195 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3196 return 0;
3197 lua_settable(L, -3);
3198
3199 /* Create the "sf" field that contains a list of stringsafe fetches. */
3200 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003201 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003202 return 0;
3203 lua_settable(L, -3);
3204
3205 /* Create the "c" field that contains a list of converters. */
3206 lua_pushstring(L, "c");
3207 if (!hlua_converters_new(L, &appctx->htxn, 0))
3208 return 0;
3209 lua_settable(L, -3);
3210
3211 /* Create the "sc" field that contains a list of stringsafe converters. */
3212 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003213 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003214 return 0;
3215 lua_settable(L, -3);
3216
3217 /* Pop a class stream metatable and affect it to the table. */
3218 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3219 lua_setmetatable(L, -2);
3220
3221 return 1;
3222}
3223
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003224__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3225{
3226 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3227 struct stream *s = appctx->htxn.s;
3228 struct hlua *hlua = &s->hlua;
3229
3230 MAY_LJMP(check_args(L, 2, "set_priv"));
3231
3232 /* Remove previous value. */
3233 if (hlua->Mref != -1)
3234 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3235
3236 /* Get and store new value. */
3237 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3238 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3239
3240 return 0;
3241}
3242
3243__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3244{
3245 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3246 struct stream *s = appctx->htxn.s;
3247 struct hlua *hlua = &s->hlua;
3248
3249 /* Push configuration index in the stack. */
3250 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3251
3252 return 1;
3253}
3254
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003255/* If expected data not yet available, it returns a yield. This function
3256 * consumes the data in the buffer. It returns a string containing the
3257 * data. This string can be empty.
3258 */
3259__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3260{
3261 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3262 struct stream_interface *si = appctx->appctx->owner;
3263 int ret;
3264 char *blk1;
3265 int len1;
3266 char *blk2;
3267 int len2;
3268
3269 /* Read the maximum amount of data avalaible. */
3270 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3271
3272 /* Data not yet avalaible. return yield. */
3273 if (ret == 0) {
3274 si_applet_cant_get(si);
3275 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3276 }
3277
3278 /* End of data: commit the total strings and return. */
3279 if (ret < 0) {
3280 luaL_pushresult(&appctx->b);
3281 return 1;
3282 }
3283
3284 /* Ensure that the block 2 length is usable. */
3285 if (ret == 1)
3286 len2 = 0;
3287
3288 /* dont check the max length read and dont check. */
3289 luaL_addlstring(&appctx->b, blk1, len1);
3290 luaL_addlstring(&appctx->b, blk2, len2);
3291
3292 /* Consume input channel output buffer data. */
3293 bo_skip(si_oc(si), len1 + len2);
3294 luaL_pushresult(&appctx->b);
3295 return 1;
3296}
3297
3298/* Check arguments for the fucntion "hlua_channel_get_yield". */
3299__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3300{
3301 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3302
3303 /* Initialise the string catenation. */
3304 luaL_buffinit(L, &appctx->b);
3305
3306 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3307}
3308
3309/* If expected data not yet available, it returns a yield. This function
3310 * consumes the data in the buffer. It returns a string containing the
3311 * data. This string can be empty.
3312 */
3313__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3314{
3315 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3316 struct stream_interface *si = appctx->appctx->owner;
3317 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3318 int ret;
3319 char *blk1;
3320 int len1;
3321 char *blk2;
3322 int len2;
3323
3324 /* Read the maximum amount of data avalaible. */
3325 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3326
3327 /* Data not yet avalaible. return yield. */
3328 if (ret == 0) {
3329 si_applet_cant_get(si);
3330 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3331 }
3332
3333 /* End of data: commit the total strings and return. */
3334 if (ret < 0) {
3335 luaL_pushresult(&appctx->b);
3336 return 1;
3337 }
3338
3339 /* Ensure that the block 2 length is usable. */
3340 if (ret == 1)
3341 len2 = 0;
3342
3343 if (len == -1) {
3344
3345 /* If len == -1, catenate all the data avalaile and
3346 * yield because we want to get all the data until
3347 * the end of data stream.
3348 */
3349 luaL_addlstring(&appctx->b, blk1, len1);
3350 luaL_addlstring(&appctx->b, blk2, len2);
3351 bo_skip(si_oc(si), len1 + len2);
3352 si_applet_cant_get(si);
3353 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3354
3355 } else {
3356
3357 /* Copy the fisrt block caping to the length required. */
3358 if (len1 > len)
3359 len1 = len;
3360 luaL_addlstring(&appctx->b, blk1, len1);
3361 len -= len1;
3362
3363 /* Copy the second block. */
3364 if (len2 > len)
3365 len2 = len;
3366 luaL_addlstring(&appctx->b, blk2, len2);
3367 len -= len2;
3368
3369 /* Consume input channel output buffer data. */
3370 bo_skip(si_oc(si), len1 + len2);
3371
3372 /* If we are no other data avalaible, yield waiting for new data. */
3373 if (len > 0) {
3374 lua_pushinteger(L, len);
3375 lua_replace(L, 2);
3376 si_applet_cant_get(si);
3377 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3378 }
3379
3380 /* return the result. */
3381 luaL_pushresult(&appctx->b);
3382 return 1;
3383 }
3384
3385 /* we never executes this */
3386 hlua_pusherror(L, "Lua: internal error");
3387 WILL_LJMP(lua_error(L));
3388 return 0;
3389}
3390
3391/* Check arguments for the fucntion "hlua_channel_get_yield". */
3392__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3393{
3394 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3395 int len = -1;
3396
3397 if (lua_gettop(L) > 2)
3398 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3399 if (lua_gettop(L) >= 2) {
3400 len = MAY_LJMP(luaL_checkinteger(L, 2));
3401 lua_pop(L, 1);
3402 }
3403
3404 /* Confirm or set the required length */
3405 lua_pushinteger(L, len);
3406
3407 /* Initialise the string catenation. */
3408 luaL_buffinit(L, &appctx->b);
3409
3410 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3411}
3412
3413/* Append data in the output side of the buffer. This data is immediatly
3414 * sent. The fcuntion returns the ammount of data writed. If the buffer
3415 * cannot contains the data, the function yield. The function returns -1
3416 * if the channel is closed.
3417 */
3418__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3419{
3420 size_t len;
3421 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3422 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3423 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3424 struct stream_interface *si = appctx->appctx->owner;
3425 struct channel *chn = si_ic(si);
3426 int max;
3427
3428 /* Get the max amount of data which can write as input in the channel. */
3429 max = channel_recv_max(chn);
3430 if (max > (len - l))
3431 max = len - l;
3432
3433 /* Copy data. */
3434 bi_putblk(chn, str + l, max);
3435
3436 /* update counters. */
3437 l += max;
3438 lua_pop(L, 1);
3439 lua_pushinteger(L, l);
3440
3441 /* If some data is not send, declares the situation to the
3442 * applet, and returns a yield.
3443 */
3444 if (l < len) {
3445 si_applet_cant_put(si);
3446 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3447 }
3448
3449 return 1;
3450}
3451
3452/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3453 * yield the LUA process, and resume it without checking the
3454 * input arguments.
3455 */
3456__LJMP static int hlua_applet_tcp_send(lua_State *L)
3457{
3458 MAY_LJMP(check_args(L, 2, "send"));
3459 lua_pushinteger(L, 0);
3460
3461 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3462}
3463
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003464/*
3465 *
3466 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003467 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003468 *
3469 *
3470 */
3471
3472/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003473 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003474 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003475__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003476{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003477 return (struct hlua_appctx *)MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003478}
3479
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003480/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003481 * according with a current TXN.
3482 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003483static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003484{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003485 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003486 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003487 struct stream_interface *si = ctx->owner;
3488 struct stream *s = si_strm(si);
3489 struct proxy *px = s->be;
3490 struct http_txn *txn = s->txn;
3491 const char *path;
3492 const char *end;
3493 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003494
3495 /* Check stack size. */
3496 if (!lua_checkstack(L, 3))
3497 return 0;
3498
3499 /* Create the object: obj[0] = userdata.
3500 * Note that the base of the Converters object is the
3501 * same than the TXN object.
3502 */
3503 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003504 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003505 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003506 appctx->appctx = ctx;
3507 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
3508 appctx->htxn.s = s;
3509 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003510
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003511 /* Create the "f" field that contains a list of fetches. */
3512 lua_pushstring(L, "f");
3513 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3514 return 0;
3515 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003516
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003517 /* Create the "sf" field that contains a list of stringsafe fetches. */
3518 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003519 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003520 return 0;
3521 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003522
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003523 /* Create the "c" field that contains a list of converters. */
3524 lua_pushstring(L, "c");
3525 if (!hlua_converters_new(L, &appctx->htxn, 0))
3526 return 0;
3527 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003528
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003529 /* Create the "sc" field that contains a list of stringsafe converters. */
3530 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003531 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003532 return 0;
3533 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003534
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003535 /* Stores the request method. */
3536 lua_pushstring(L, "method");
3537 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3538 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003539
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003540 /* Stores the http version. */
3541 lua_pushstring(L, "version");
3542 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3543 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003544
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003545 /* creates an array of headers. hlua_http_get_headers() crates and push
3546 * the array on the top of the stack.
3547 */
3548 lua_pushstring(L, "headers");
3549 htxn.s = s;
3550 htxn.p = px;
3551 htxn.dir = SMP_OPT_DIR_REQ;
3552 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3553 return 0;
3554 lua_settable(L, -3);
3555
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003556 /* Get path and qs */
3557 path = http_get_path(txn);
3558 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3559 p = path;
3560 while (p < end && *p != '?')
3561 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003562
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003563 /* Stores the request path. */
3564 lua_pushstring(L, "path");
3565 lua_pushlstring(L, path, p - path);
3566 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003567
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003568 /* Stores the query string. */
3569 lua_pushstring(L, "qs");
3570 if (*p == '?')
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003571 p++;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003572 lua_pushlstring(L, p, end - p);
3573 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003574
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003575 /* Stores the request path. */
3576 lua_pushstring(L, "length");
3577 lua_pushinteger(L, txn->req.body_len);
3578 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003579
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003580 /* Create an array of HTTP request headers. */
3581 lua_pushstring(L, "headers");
3582 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3583 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003584
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003585 /* Create an empty array of HTTP request headers. */
3586 lua_pushstring(L, "response");
3587 lua_newtable(L);
3588 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003589
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003590 /* Pop a class stream metatable and affect it to the table. */
3591 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3592 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003593
3594 return 1;
3595}
3596
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003597__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3598{
3599 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3600 struct stream *s = appctx->htxn.s;
3601 struct hlua *hlua = &s->hlua;
3602
3603 MAY_LJMP(check_args(L, 2, "set_priv"));
3604
3605 /* Remove previous value. */
3606 if (hlua->Mref != -1)
3607 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3608
3609 /* Get and store new value. */
3610 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3611 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3612
3613 return 0;
3614}
3615
3616__LJMP static int hlua_applet_http_get_priv(lua_State *L)
3617{
3618 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3619 struct stream *s = appctx->htxn.s;
3620 struct hlua *hlua = &s->hlua;
3621
3622 /* Push configuration index in the stack. */
3623 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3624
3625 return 1;
3626}
3627
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003628/* If expected data not yet available, it returns a yield. This function
3629 * consumes the data in the buffer. It returns a string containing the
3630 * data. This string can be empty.
3631 */
3632__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003633{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003634 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3635 struct stream_interface *si = appctx->appctx->owner;
3636 struct channel *chn = si_ic(si);
3637 int ret;
3638 char *blk1;
3639 int len1;
3640 char *blk2;
3641 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003642
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003643 /* Maybe we cant send a 100-continue ? */
3644 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3645 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3646 /* if ret == -2 or -3 the channel closed or the message si too
3647 * big for the buffers. We cant send anything. So, we ignoring
3648 * the error, considers that the 100-continue is sent, and try
3649 * to receive.
3650 * If ret is -1, we dont have room in the buffer, so we yield.
3651 */
3652 if (ret == -1) {
3653 si_applet_cant_put(si);
3654 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3655 }
3656 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3657 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003658
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003659 /* Check for the end of the data. */
3660 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3661 luaL_pushresult(&appctx->b);
3662 return 1;
3663 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003664
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003665 /* Read the maximum amount of data avalaible. */
3666 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003667
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003668 /* Data not yet avalaible. return yield. */
3669 if (ret == 0) {
3670 si_applet_cant_get(si);
3671 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3672 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003673
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003674 /* End of data: commit the total strings and return. */
3675 if (ret < 0) {
3676 luaL_pushresult(&appctx->b);
3677 return 1;
3678 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003679
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003680 /* Ensure that the block 2 length is usable. */
3681 if (ret == 1)
3682 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003683
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003684 /* Copy the fisrt block caping to the length required. */
3685 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3686 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3687 luaL_addlstring(&appctx->b, blk1, len1);
3688 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003689
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003690 /* Copy the second block. */
3691 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3692 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3693 luaL_addlstring(&appctx->b, blk2, len2);
3694 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003695
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003696 /* Consume input channel output buffer data. */
3697 bo_skip(si_oc(si), len1 + len2);
3698 luaL_pushresult(&appctx->b);
3699 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003700}
3701
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003702/* Check arguments for the fucntion "hlua_channel_get_yield". */
3703__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003704{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003705 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003706
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003707 /* Initialise the string catenation. */
3708 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003709
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003710 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003711}
3712
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003713/* If expected data not yet available, it returns a yield. This function
3714 * consumes the data in the buffer. It returns a string containing the
3715 * data. This string can be empty.
3716 */
3717__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003718{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003719 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3720 struct stream_interface *si = appctx->appctx->owner;
3721 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3722 struct channel *chn = si_ic(si);
3723 int ret;
3724 char *blk1;
3725 int len1;
3726 char *blk2;
3727 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003728
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003729 /* Maybe we cant send a 100-continue ? */
3730 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3731 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3732 /* if ret == -2 or -3 the channel closed or the message si too
3733 * big for the buffers. We cant send anything. So, we ignoring
3734 * the error, considers that the 100-continue is sent, and try
3735 * to receive.
3736 * If ret is -1, we dont have room in the buffer, so we yield.
3737 */
3738 if (ret == -1) {
3739 si_applet_cant_put(si);
3740 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3741 }
3742 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3743 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003744
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003745 /* Read the maximum amount of data avalaible. */
3746 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003747
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003748 /* Data not yet avalaible. return yield. */
3749 if (ret == 0) {
3750 si_applet_cant_get(si);
3751 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3752 }
3753
3754 /* End of data: commit the total strings and return. */
3755 if (ret < 0) {
3756 luaL_pushresult(&appctx->b);
3757 return 1;
3758 }
3759
3760 /* Ensure that the block 2 length is usable. */
3761 if (ret == 1)
3762 len2 = 0;
3763
3764 /* Copy the fisrt block caping to the length required. */
3765 if (len1 > len)
3766 len1 = len;
3767 luaL_addlstring(&appctx->b, blk1, len1);
3768 len -= len1;
3769
3770 /* Copy the second block. */
3771 if (len2 > len)
3772 len2 = len;
3773 luaL_addlstring(&appctx->b, blk2, len2);
3774 len -= len2;
3775
3776 /* Consume input channel output buffer data. */
3777 bo_skip(si_oc(si), len1 + len2);
3778 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
3779 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
3780
3781 /* If we are no other data avalaible, yield waiting for new data. */
3782 if (len > 0) {
3783 lua_pushinteger(L, len);
3784 lua_replace(L, 2);
3785 si_applet_cant_get(si);
3786 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3787 }
3788
3789 /* return the result. */
3790 luaL_pushresult(&appctx->b);
3791 return 1;
3792}
3793
3794/* Check arguments for the fucntion "hlua_channel_get_yield". */
3795__LJMP static int hlua_applet_http_recv(lua_State *L)
3796{
3797 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3798 int len = -1;
3799
3800 /* Check arguments. */
3801 if (lua_gettop(L) > 2)
3802 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3803 if (lua_gettop(L) >= 2) {
3804 len = MAY_LJMP(luaL_checkinteger(L, 2));
3805 lua_pop(L, 1);
3806 }
3807
3808 /* Check the required length */
3809 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3810 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3811 lua_pushinteger(L, len);
3812
3813 /* Initialise the string catenation. */
3814 luaL_buffinit(L, &appctx->b);
3815
3816 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
3817}
3818
3819/* Append data in the output side of the buffer. This data is immediatly
3820 * sent. The fcuntion returns the ammount of data writed. If the buffer
3821 * cannot contains the data, the function yield. The function returns -1
3822 * if the channel is closed.
3823 */
3824__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
3825{
3826 size_t len;
3827 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3828 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3829 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3830 struct stream_interface *si = appctx->appctx->owner;
3831 struct channel *chn = si_ic(si);
3832 int max;
3833
3834 /* Get the max amount of data which can write as input in the channel. */
3835 max = channel_recv_max(chn);
3836 if (max > (len - l))
3837 max = len - l;
3838
3839 /* Copy data. */
3840 bi_putblk(chn, str + l, max);
3841
3842 /* update counters. */
3843 l += max;
3844 lua_pop(L, 1);
3845 lua_pushinteger(L, l);
3846
3847 /* If some data is not send, declares the situation to the
3848 * applet, and returns a yield.
3849 */
3850 if (l < len) {
3851 si_applet_cant_put(si);
3852 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
3853 }
3854
3855 return 1;
3856}
3857
3858/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
3859 * yield the LUA process, and resume it without checking the
3860 * input arguments.
3861 */
3862__LJMP static int hlua_applet_http_send(lua_State *L)
3863{
3864 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3865 size_t len;
3866 char hex[10];
3867
3868 MAY_LJMP(luaL_checklstring(L, 2, &len));
3869
3870 /* If transfer encoding chunked is selected, we surround the data
3871 * by chunk data.
3872 */
3873 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
3874 snprintf(hex, 9, "%x", (unsigned int)len);
3875 lua_pushfstring(L, "%s\r\n", hex);
3876 lua_insert(L, 2); /* swap the last 2 entries. */
3877 lua_pushstring(L, "\r\n");
3878 lua_concat(L, 3);
3879 }
3880
3881 /* This interger is used for followinf the amount of data sent. */
3882 lua_pushinteger(L, 0);
3883
3884 /* We want to send some data. Headers must be sent. */
3885 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
3886 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
3887 WILL_LJMP(lua_error(L));
3888 }
3889
3890 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
3891}
3892
3893__LJMP static int hlua_applet_http_addheader(lua_State *L)
3894{
3895 const char *name;
3896 int ret;
3897
3898 MAY_LJMP(hlua_checkapplet_http(L, 1));
3899 name = MAY_LJMP(luaL_checkstring(L, 2));
3900 MAY_LJMP(luaL_checkstring(L, 3));
3901
3902 /* Push in the stack the "response" entry. */
3903 ret = lua_getfield(L, 1, "response");
3904 if (ret != LUA_TTABLE) {
3905 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
3906 "is expected as an array. %s found", lua_typename(L, ret));
3907 WILL_LJMP(lua_error(L));
3908 }
3909
3910 /* check if the header is already registered if it is not
3911 * the case, register it.
3912 */
3913 ret = lua_getfield(L, -1, name);
3914 if (ret == LUA_TNIL) {
3915
3916 /* Entry not found. */
3917 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
3918
3919 /* Insert the new header name in the array in the top of the stack.
3920 * It left the new array in the top of the stack.
3921 */
3922 lua_newtable(L);
3923 lua_pushvalue(L, 2);
3924 lua_pushvalue(L, -2);
3925 lua_settable(L, -4);
3926
3927 } else if (ret != LUA_TTABLE) {
3928
3929 /* corruption error. */
3930 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
3931 "is expected as an array. %s found", name, lua_typename(L, ret));
3932 WILL_LJMP(lua_error(L));
3933 }
3934
3935 /* Now the top od thestack is an array of values. We push
3936 * the header value as new entry.
3937 */
3938 lua_pushvalue(L, 3);
3939 ret = lua_rawlen(L, -2);
3940 lua_rawseti(L, -2, ret + 1);
3941 lua_pushboolean(L, 1);
3942 return 1;
3943}
3944
3945__LJMP static int hlua_applet_http_status(lua_State *L)
3946{
3947 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3948 int status = MAY_LJMP(luaL_checkinteger(L, 2));
3949
3950 if (status < 100 || status > 599) {
3951 lua_pushboolean(L, 0);
3952 return 1;
3953 }
3954
3955 appctx->appctx->ctx.hlua_apphttp.status = status;
3956 lua_pushboolean(L, 1);
3957 return 1;
3958}
3959
3960/* We will build the status line and the headers of the HTTP response.
3961 * We will try send at once if its not possible, we give back the hand
3962 * waiting for more room.
3963 */
3964__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
3965{
3966 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3967 struct stream_interface *si = appctx->appctx->owner;
3968 struct channel *chn = si_ic(si);
3969 int ret;
3970 size_t len;
3971 const char *msg;
3972
3973 /* Get the message as the first argument on the stack. */
3974 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
3975
3976 /* Send the message at once. */
3977 ret = bi_putblk(chn, msg, len);
3978
3979 /* if ret == -2 or -3 the channel closed or the message si too
3980 * big for the buffers.
3981 */
3982 if (ret == -2 || ret == -3) {
3983 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
3984 WILL_LJMP(lua_error(L));
3985 }
3986
3987 /* If ret is -1, we dont have room in the buffer, so we yield. */
3988 if (ret == -1) {
3989 si_applet_cant_put(si);
3990 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
3991 }
3992
3993 /* Headers sent, set the flag. */
3994 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
3995 return 0;
3996}
3997
3998__LJMP static int hlua_applet_http_start_response(lua_State *L)
3999{
4000 struct chunk *tmp = get_trash_chunk();
4001 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004002 const char *name;
4003 const char *value;
4004 int id;
4005 int hdr_connection = 0;
4006 int hdr_contentlength = -1;
4007 int hdr_chunked = 0;
4008
4009 /* Use the same http version than the request. */
4010 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004011 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004012 appctx->appctx->ctx.hlua_apphttp.status,
4013 get_reason(appctx->appctx->ctx.hlua_apphttp.status));
4014
4015 /* Get the array associated to the field "response" in the object AppletHTTP. */
4016 lua_pushvalue(L, 0);
4017 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4018 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4019 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4020 WILL_LJMP(lua_error(L));
4021 }
4022
4023 /* Browse the list of headers. */
4024 lua_pushnil(L);
4025 while(lua_next(L, -2) != 0) {
4026
4027 /* We expect a string as -2. */
4028 if (lua_type(L, -2) != LUA_TSTRING) {
4029 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4030 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4031 lua_typename(L, lua_type(L, -2)));
4032 WILL_LJMP(lua_error(L));
4033 }
4034 name = lua_tostring(L, -2);
4035
4036 /* We expect an array as -1. */
4037 if (lua_type(L, -1) != LUA_TTABLE) {
4038 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4039 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4040 name,
4041 lua_typename(L, lua_type(L, -1)));
4042 WILL_LJMP(lua_error(L));
4043 }
4044
4045 /* Browse the table who is on the top of the stack. */
4046 lua_pushnil(L);
4047 while(lua_next(L, -2) != 0) {
4048
4049 /* We expect a number as -2. */
4050 if (lua_type(L, -2) != LUA_TNUMBER) {
4051 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4052 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4053 name,
4054 lua_typename(L, lua_type(L, -2)));
4055 WILL_LJMP(lua_error(L));
4056 }
4057 id = lua_tointeger(L, -2);
4058
4059 /* We expect a string as -2. */
4060 if (lua_type(L, -1) != LUA_TSTRING) {
4061 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4062 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4063 name, id,
4064 lua_typename(L, lua_type(L, -1)));
4065 WILL_LJMP(lua_error(L));
4066 }
4067 value = lua_tostring(L, -1);
4068
4069 /* Catenate a new header. */
4070 chunk_appendf(tmp, "%s: %s\r\n", name, value);
4071
4072 /* Protocol checks. */
4073
4074 /* Check if the header conneciton is present. */
4075 if (strcasecmp("connection", name) == 0)
4076 hdr_connection = 1;
4077
4078 /* Copy the header content length. The length conversion
4079 * is done without control. If it contains a ad value, this
4080 * is not our problem.
4081 */
4082 if (strcasecmp("content-length", name) == 0)
4083 hdr_contentlength = atoi(value);
4084
4085 /* Check if the client annouces a transfer-encoding chunked it self. */
4086 if (strcasecmp("transfer-encoding", name) == 0 &&
4087 strcasecmp("chunked", value) == 0)
4088 hdr_chunked = 1;
4089
4090 /* Remove the array from the stack, and get next element with a remaining string. */
4091 lua_pop(L, 1);
4092 }
4093
4094 /* Remove the array from the stack, and get next element with a remaining string. */
4095 lua_pop(L, 1);
4096 }
4097
4098 /* If the http protocol version is 1.1, we expect an header "connection" set
4099 * to "close" to be HAProxy/keeplive compliant. Otherwise, we expect nothing.
4100 * If the header conneciton is present, don't change it, if it is not present,
4101 * we must set.
4102 *
4103 * we set a "connection: close" header for ensuring that the keepalive will be
4104 * respected by haproxy. HAProcy considers that the application cloe the connection
4105 * and it keep the connection from the client open.
4106 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004107 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 && !hdr_connection)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004108 chunk_appendf(tmp, "Connection: close\r\n");
4109
4110 /* If we dont have a content-length set, we must announce a transfer enconding
4111 * chunked. This is required by haproxy for the keepalive compliance.
4112 * If the applet annouce a transfer-encoding chunked itslef, don't
4113 * do anything.
4114 */
4115 if (hdr_contentlength == -1 && hdr_chunked == 0) {
4116 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4117 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4118 }
4119
4120 /* Finalize headers. */
4121 chunk_appendf(tmp, "\r\n");
4122
4123 /* Remove the last entry and the array of headers */
4124 lua_pop(L, 2);
4125
4126 /* Push the headers block. */
4127 lua_pushlstring(L, tmp->str, tmp->len);
4128
4129 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4130}
4131
4132/*
4133 *
4134 *
4135 * Class HTTP
4136 *
4137 *
4138 */
4139
4140/* Returns a struct hlua_txn if the stack entry "ud" is
4141 * a class stream, otherwise it throws an error.
4142 */
4143__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4144{
4145 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
4146}
4147
4148/* This function creates and push in the stack a HTTP object
4149 * according with a current TXN.
4150 */
4151static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4152{
4153 struct hlua_txn *htxn;
4154
4155 /* Check stack size. */
4156 if (!lua_checkstack(L, 3))
4157 return 0;
4158
4159 /* Create the object: obj[0] = userdata.
4160 * Note that the base of the Converters object is the
4161 * same than the TXN object.
4162 */
4163 lua_newtable(L);
4164 htxn = lua_newuserdata(L, sizeof(*htxn));
4165 lua_rawseti(L, -2, 0);
4166
4167 htxn->s = txn->s;
4168 htxn->p = txn->p;
4169
4170 /* Pop a class stream metatable and affect it to the table. */
4171 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4172 lua_setmetatable(L, -2);
4173
4174 return 1;
4175}
4176
4177/* This function creates ans returns an array of HTTP headers.
4178 * This function does not fails. It is used as wrapper with the
4179 * 2 following functions.
4180 */
4181__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4182{
4183 const char *cur_ptr, *cur_next, *p;
4184 int old_idx, cur_idx;
4185 struct hdr_idx_elem *cur_hdr;
4186 const char *hn, *hv;
4187 int hnl, hvl;
4188 int type;
4189 const char *in;
4190 char *out;
4191 int len;
4192
4193 /* Create the table. */
4194 lua_newtable(L);
4195
4196 if (!htxn->s->txn)
4197 return 1;
4198
4199 /* Build array of headers. */
4200 old_idx = 0;
4201 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4202
4203 while (1) {
4204 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4205 if (!cur_idx)
4206 break;
4207 old_idx = cur_idx;
4208
4209 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4210 cur_ptr = cur_next;
4211 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4212
4213 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4214 * and the next header starts at cur_next. We'll check
4215 * this header in the list as well as against the default
4216 * rule.
4217 */
4218
4219 /* look for ': *'. */
4220 hn = cur_ptr;
4221 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4222 if (p >= cur_ptr+cur_hdr->len)
4223 continue;
4224 hnl = p - hn;
4225 p++;
4226 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4227 p++;
4228 if (p >= cur_ptr+cur_hdr->len)
4229 continue;
4230 hv = p;
4231 hvl = cur_ptr+cur_hdr->len-p;
4232
4233 /* Lowercase the key. Don't check the size of trash, it have
4234 * the size of one buffer and the input data contains in one
4235 * buffer.
4236 */
4237 out = trash.str;
4238 for (in=hn; in<hn+hnl; in++, out++)
4239 *out = tolower(*in);
4240 *out = '\0';
4241
4242 /* Check for existing entry:
4243 * assume that the table is on the top of the stack, and
4244 * push the key in the stack, the function lua_gettable()
4245 * perform the lookup.
4246 */
4247 lua_pushlstring(L, trash.str, hnl);
4248 lua_gettable(L, -2);
4249 type = lua_type(L, -1);
4250
4251 switch (type) {
4252 case LUA_TNIL:
4253 /* Table not found, create it. */
4254 lua_pop(L, 1); /* remove the nil value. */
4255 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4256 lua_newtable(L); /* create and push empty table. */
4257 lua_pushlstring(L, hv, hvl); /* push header value. */
4258 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4259 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4260 break;
4261
4262 case LUA_TTABLE:
4263 /* Entry found: push the value in the table. */
4264 len = lua_rawlen(L, -1);
4265 lua_pushlstring(L, hv, hvl); /* push header value. */
4266 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4267 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4268 break;
4269
4270 default:
4271 /* Other cases are errors. */
4272 hlua_pusherror(L, "internal error during the parsing of headers.");
4273 WILL_LJMP(lua_error(L));
4274 }
4275 }
4276
4277 return 1;
4278}
4279
4280__LJMP static int hlua_http_req_get_headers(lua_State *L)
4281{
4282 struct hlua_txn *htxn;
4283
4284 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4285 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4286
4287 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4288}
4289
4290__LJMP static int hlua_http_res_get_headers(lua_State *L)
4291{
4292 struct hlua_txn *htxn;
4293
4294 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4295 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4296
4297 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4298}
4299
4300/* This function replace full header, or just a value in
4301 * the request or in the response. It is a wrapper fir the
4302 * 4 following functions.
4303 */
4304__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4305 struct http_msg *msg, int action)
4306{
4307 size_t name_len;
4308 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4309 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4310 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4311 struct my_regex re;
4312
4313 if (!regex_comp(reg, &re, 1, 1, NULL))
4314 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4315
4316 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4317 regex_free(&re);
4318 return 0;
4319}
4320
4321__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4322{
4323 struct hlua_txn *htxn;
4324
4325 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4326 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4327
4328 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4329}
4330
4331__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4332{
4333 struct hlua_txn *htxn;
4334
4335 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4336 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4337
4338 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4339}
4340
4341__LJMP static int hlua_http_req_rep_val(lua_State *L)
4342{
4343 struct hlua_txn *htxn;
4344
4345 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4346 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4347
4348 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4349}
4350
4351__LJMP static int hlua_http_res_rep_val(lua_State *L)
4352{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004353 struct hlua_txn *htxn;
4354
4355 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4356 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4357
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004358 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004359}
4360
4361/* This function deletes all the occurences of an header.
4362 * It is a wrapper for the 2 following functions.
4363 */
4364__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4365{
4366 size_t len;
4367 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4368 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004369 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004370
4371 ctx.idx = 0;
4372 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4373 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4374 return 0;
4375}
4376
4377__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4378{
4379 struct hlua_txn *htxn;
4380
4381 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4382 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4383
Willy Tarreaueee5b512015-04-03 23:46:31 +02004384 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004385}
4386
4387__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4388{
4389 struct hlua_txn *htxn;
4390
4391 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4392 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4393
Willy Tarreaueee5b512015-04-03 23:46:31 +02004394 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004395}
4396
4397/* This function adds an header. It is a wrapper used by
4398 * the 2 following functions.
4399 */
4400__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4401{
4402 size_t name_len;
4403 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4404 size_t value_len;
4405 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4406 char *p;
4407
4408 /* Check length. */
4409 trash.len = value_len + name_len + 2;
4410 if (trash.len > trash.size)
4411 return 0;
4412
4413 /* Creates the header string. */
4414 p = trash.str;
4415 memcpy(p, name, name_len);
4416 p += name_len;
4417 *p = ':';
4418 p++;
4419 *p = ' ';
4420 p++;
4421 memcpy(p, value, value_len);
4422
Willy Tarreaueee5b512015-04-03 23:46:31 +02004423 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004424 trash.str, trash.len) != 0);
4425
4426 return 0;
4427}
4428
4429__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4430{
4431 struct hlua_txn *htxn;
4432
4433 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4434 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4435
Willy Tarreaueee5b512015-04-03 23:46:31 +02004436 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004437}
4438
4439__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4440{
4441 struct hlua_txn *htxn;
4442
4443 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4444 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4445
Willy Tarreaueee5b512015-04-03 23:46:31 +02004446 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004447}
4448
4449static int hlua_http_req_set_hdr(lua_State *L)
4450{
4451 struct hlua_txn *htxn;
4452
4453 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4454 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4455
Willy Tarreaueee5b512015-04-03 23:46:31 +02004456 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4457 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004458}
4459
4460static int hlua_http_res_set_hdr(lua_State *L)
4461{
4462 struct hlua_txn *htxn;
4463
4464 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4465 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4466
Willy Tarreaueee5b512015-04-03 23:46:31 +02004467 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4468 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004469}
4470
4471/* This function set the method. */
4472static int hlua_http_req_set_meth(lua_State *L)
4473{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004474 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004475 size_t name_len;
4476 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004477
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004478 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004479 return 1;
4480}
4481
4482/* This function set the method. */
4483static int hlua_http_req_set_path(lua_State *L)
4484{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004485 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004486 size_t name_len;
4487 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004488 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004489 return 1;
4490}
4491
4492/* This function set the query-string. */
4493static int hlua_http_req_set_query(lua_State *L)
4494{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004495 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004496 size_t name_len;
4497 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004498
4499 /* Check length. */
4500 if (name_len > trash.size - 1) {
4501 lua_pushboolean(L, 0);
4502 return 1;
4503 }
4504
4505 /* Add the mark question as prefix. */
4506 chunk_reset(&trash);
4507 trash.str[trash.len++] = '?';
4508 memcpy(trash.str + trash.len, name, name_len);
4509 trash.len += name_len;
4510
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004511 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004512 return 1;
4513}
4514
4515/* This function set the uri. */
4516static int hlua_http_req_set_uri(lua_State *L)
4517{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004518 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004519 size_t name_len;
4520 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004521
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004522 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004523 return 1;
4524}
4525
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004526/* This function set the response code. */
4527static int hlua_http_res_set_status(lua_State *L)
4528{
4529 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4530 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
4531
4532 http_set_status(code, htxn->s);
4533 return 0;
4534}
4535
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004536/*
4537 *
4538 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004539 * Class TXN
4540 *
4541 *
4542 */
4543
4544/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004545 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004546 */
4547__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4548{
4549 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
4550}
4551
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004552__LJMP static int hlua_set_var(lua_State *L)
4553{
4554 struct hlua_txn *htxn;
4555 const char *name;
4556 size_t len;
4557 struct sample smp;
4558
4559 MAY_LJMP(check_args(L, 3, "set_var"));
4560
4561 /* It is useles to retrieve the stream, but this function
4562 * runs only in a stream context.
4563 */
4564 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4565 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4566
4567 /* Converts the third argument in a sample. */
4568 hlua_lua2smp(L, 3, &smp);
4569
4570 /* Store the sample in a variable. */
4571 vars_set_by_name(name, len, htxn->s, &smp);
4572 return 0;
4573}
4574
4575__LJMP static int hlua_get_var(lua_State *L)
4576{
4577 struct hlua_txn *htxn;
4578 const char *name;
4579 size_t len;
4580 struct sample smp;
4581
4582 MAY_LJMP(check_args(L, 2, "get_var"));
4583
4584 /* It is useles to retrieve the stream, but this function
4585 * runs only in a stream context.
4586 */
4587 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4588 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4589
4590 if (!vars_get_by_name(name, len, htxn->s, &smp)) {
4591 lua_pushnil(L);
4592 return 1;
4593 }
4594
4595 return hlua_smp2lua(L, &smp);
4596}
4597
Willy Tarreau59551662015-03-10 14:23:13 +01004598__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004599{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004600 struct hlua *hlua;
4601
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004602 MAY_LJMP(check_args(L, 2, "set_priv"));
4603
Willy Tarreau87b09662015-04-03 00:22:06 +02004604 /* It is useles to retrieve the stream, but this function
4605 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004606 */
4607 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004608 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004609
4610 /* Remove previous value. */
4611 if (hlua->Mref != -1)
4612 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
4613
4614 /* Get and store new value. */
4615 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4616 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4617
4618 return 0;
4619}
4620
Willy Tarreau59551662015-03-10 14:23:13 +01004621__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004622{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004623 struct hlua *hlua;
4624
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004625 MAY_LJMP(check_args(L, 1, "get_priv"));
4626
Willy Tarreau87b09662015-04-03 00:22:06 +02004627 /* It is useles to retrieve the stream, but this function
4628 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004629 */
4630 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004631 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004632
4633 /* Push configuration index in the stack. */
4634 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4635
4636 return 1;
4637}
4638
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004639/* Create stack entry containing a class TXN. This function
4640 * return 0 if the stack does not contains free slots,
4641 * otherwise it returns 1.
4642 */
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004643static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004644{
Willy Tarreaude491382015-04-06 11:04:28 +02004645 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004646
4647 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004648 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004649 return 0;
4650
4651 /* NOTE: The allocation never fails. The failure
4652 * throw an error, and the function never returns.
4653 * if the throw is not avalaible, the process is aborted.
4654 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004655 /* Create the object: obj[0] = userdata. */
4656 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004657 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004658 lua_rawseti(L, -2, 0);
4659
Willy Tarreaude491382015-04-06 11:04:28 +02004660 htxn->s = s;
4661 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004662 htxn->dir = dir;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004663
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004664 /* Create the "f" field that contains a list of fetches. */
4665 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004666 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004667 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004668 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004669
4670 /* Create the "sf" field that contains a list of stringsafe fetches. */
4671 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004672 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004673 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004674 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004675
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004676 /* Create the "c" field that contains a list of converters. */
4677 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004678 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004679 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004680 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004681
4682 /* Create the "sc" field that contains a list of stringsafe converters. */
4683 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004684 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004685 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004686 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004687
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004688 /* Create the "req" field that contains the request channel object. */
4689 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004690 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004691 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004692 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004693
4694 /* Create the "res" field that contains the response channel object. */
4695 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004696 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004697 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004698 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004699
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004700 /* Creates the HTTP object is the current proxy allows http. */
4701 lua_pushstring(L, "http");
4702 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02004703 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004704 return 0;
4705 }
4706 else
4707 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004708 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004709
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004710 /* Pop a class sesison metatable and affect it to the userdata. */
4711 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
4712 lua_setmetatable(L, -2);
4713
4714 return 1;
4715}
4716
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004717__LJMP static int hlua_txn_deflog(lua_State *L)
4718{
4719 const char *msg;
4720 struct hlua_txn *htxn;
4721
4722 MAY_LJMP(check_args(L, 2, "deflog"));
4723 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4724 msg = MAY_LJMP(luaL_checkstring(L, 2));
4725
4726 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
4727 return 0;
4728}
4729
4730__LJMP static int hlua_txn_log(lua_State *L)
4731{
4732 int level;
4733 const char *msg;
4734 struct hlua_txn *htxn;
4735
4736 MAY_LJMP(check_args(L, 3, "log"));
4737 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4738 level = MAY_LJMP(luaL_checkinteger(L, 2));
4739 msg = MAY_LJMP(luaL_checkstring(L, 3));
4740
4741 if (level < 0 || level >= NB_LOG_LEVELS)
4742 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4743
4744 hlua_sendlog(htxn->s->be, level, msg);
4745 return 0;
4746}
4747
4748__LJMP static int hlua_txn_log_debug(lua_State *L)
4749{
4750 const char *msg;
4751 struct hlua_txn *htxn;
4752
4753 MAY_LJMP(check_args(L, 2, "Debug"));
4754 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4755 msg = MAY_LJMP(luaL_checkstring(L, 2));
4756 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
4757 return 0;
4758}
4759
4760__LJMP static int hlua_txn_log_info(lua_State *L)
4761{
4762 const char *msg;
4763 struct hlua_txn *htxn;
4764
4765 MAY_LJMP(check_args(L, 2, "Info"));
4766 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4767 msg = MAY_LJMP(luaL_checkstring(L, 2));
4768 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
4769 return 0;
4770}
4771
4772__LJMP static int hlua_txn_log_warning(lua_State *L)
4773{
4774 const char *msg;
4775 struct hlua_txn *htxn;
4776
4777 MAY_LJMP(check_args(L, 2, "Warning"));
4778 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4779 msg = MAY_LJMP(luaL_checkstring(L, 2));
4780 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
4781 return 0;
4782}
4783
4784__LJMP static int hlua_txn_log_alert(lua_State *L)
4785{
4786 const char *msg;
4787 struct hlua_txn *htxn;
4788
4789 MAY_LJMP(check_args(L, 2, "Alert"));
4790 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4791 msg = MAY_LJMP(luaL_checkstring(L, 2));
4792 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
4793 return 0;
4794}
4795
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004796__LJMP static int hlua_txn_set_loglevel(lua_State *L)
4797{
4798 struct hlua_txn *htxn;
4799 int ll;
4800
4801 MAY_LJMP(check_args(L, 2, "set_loglevel"));
4802 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4803 ll = MAY_LJMP(luaL_checkinteger(L, 2));
4804
4805 if (ll < 0 || ll > 7)
4806 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
4807
4808 htxn->s->logs.level = ll;
4809 return 0;
4810}
4811
4812__LJMP static int hlua_txn_set_tos(lua_State *L)
4813{
4814 struct hlua_txn *htxn;
4815 struct connection *cli_conn;
4816 int tos;
4817
4818 MAY_LJMP(check_args(L, 2, "set_tos"));
4819 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4820 tos = MAY_LJMP(luaL_checkinteger(L, 2));
4821
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004822 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004823 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
4824
4825 return 0;
4826}
4827
4828__LJMP static int hlua_txn_set_mark(lua_State *L)
4829{
4830#ifdef SO_MARK
4831 struct hlua_txn *htxn;
4832 struct connection *cli_conn;
4833 int mark;
4834
4835 MAY_LJMP(check_args(L, 2, "set_mark"));
4836 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4837 mark = MAY_LJMP(luaL_checkinteger(L, 2));
4838
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004839 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02004840 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004841#endif
4842 return 0;
4843}
4844
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004845/* This function is an Lua binding that send pending data
4846 * to the client, and close the stream interface.
4847 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004848__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004849{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004850 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01004851 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004852
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004853 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004854 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004855
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004856 ic = &htxn->s->req;
4857 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01004858
Willy Tarreau630ef452015-08-28 10:06:15 +02004859 if (htxn->s->txn) {
4860 /* HTTP mode, let's stay in sync with the stream */
4861 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
4862 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
4863 htxn->s->txn->req.sov = 0;
4864 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
4865 oc->analysers = AN_RES_HTTP_XFER_BODY;
4866 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
4867 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
4868
Willy Tarreau630ef452015-08-28 10:06:15 +02004869 /* Note that if we want to support keep-alive, we need
4870 * to bypass the close/shutr_now calls below, but that
4871 * may only be done if the HTTP request was already
4872 * processed and the connection header is known (ie
4873 * not during TCP rules).
4874 */
4875 }
4876
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004877 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01004878 channel_abort(ic);
4879 channel_auto_close(ic);
4880 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004881
4882 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01004883 channel_auto_read(oc);
4884 channel_auto_close(oc);
4885 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004886
Willy Tarreau0458b082015-08-28 09:40:04 +02004887 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004888
4889 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004890 return 0;
4891}
4892
4893__LJMP static int hlua_log(lua_State *L)
4894{
4895 int level;
4896 const char *msg;
4897
4898 MAY_LJMP(check_args(L, 2, "log"));
4899 level = MAY_LJMP(luaL_checkinteger(L, 1));
4900 msg = MAY_LJMP(luaL_checkstring(L, 2));
4901
4902 if (level < 0 || level >= NB_LOG_LEVELS)
4903 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4904
4905 hlua_sendlog(NULL, level, msg);
4906 return 0;
4907}
4908
4909__LJMP static int hlua_log_debug(lua_State *L)
4910{
4911 const char *msg;
4912
4913 MAY_LJMP(check_args(L, 1, "debug"));
4914 msg = MAY_LJMP(luaL_checkstring(L, 1));
4915 hlua_sendlog(NULL, LOG_DEBUG, msg);
4916 return 0;
4917}
4918
4919__LJMP static int hlua_log_info(lua_State *L)
4920{
4921 const char *msg;
4922
4923 MAY_LJMP(check_args(L, 1, "info"));
4924 msg = MAY_LJMP(luaL_checkstring(L, 1));
4925 hlua_sendlog(NULL, LOG_INFO, msg);
4926 return 0;
4927}
4928
4929__LJMP static int hlua_log_warning(lua_State *L)
4930{
4931 const char *msg;
4932
4933 MAY_LJMP(check_args(L, 1, "warning"));
4934 msg = MAY_LJMP(luaL_checkstring(L, 1));
4935 hlua_sendlog(NULL, LOG_WARNING, msg);
4936 return 0;
4937}
4938
4939__LJMP static int hlua_log_alert(lua_State *L)
4940{
4941 const char *msg;
4942
4943 MAY_LJMP(check_args(L, 1, "alert"));
4944 msg = MAY_LJMP(luaL_checkstring(L, 1));
4945 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004946 return 0;
4947}
4948
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004949__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004950{
4951 int wakeup_ms = lua_tointeger(L, -1);
4952 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004953 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004954 return 0;
4955}
4956
4957__LJMP static int hlua_sleep(lua_State *L)
4958{
4959 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004960 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004961
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004962 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004963
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004964 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004965 wakeup_ms = tick_add(now_ms, delay);
4966 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004967
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004968 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
4969 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004970}
4971
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004972__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004973{
4974 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004975 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004976
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004977 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004978
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004979 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004980 wakeup_ms = tick_add(now_ms, delay);
4981 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004982
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004983 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
4984 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004985}
4986
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004987/* This functionis an LUA binding. it permits to give back
4988 * the hand at the HAProxy scheduler. It is used when the
4989 * LUA processing consumes a lot of time.
4990 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004991__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004992{
4993 return 0;
4994}
4995
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004996__LJMP static int hlua_yield(lua_State *L)
4997{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004998 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
4999 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005000}
5001
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005002/* This function change the nice of the currently executed
5003 * task. It is used set low or high priority at the current
5004 * task.
5005 */
Willy Tarreau59551662015-03-10 14:23:13 +01005006__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005007{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005008 struct hlua *hlua;
5009 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005010
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005011 MAY_LJMP(check_args(L, 1, "set_nice"));
5012 hlua = hlua_gethlua(L);
5013 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005014
5015 /* If he task is not set, I'm in a start mode. */
5016 if (!hlua || !hlua->task)
5017 return 0;
5018
5019 if (nice < -1024)
5020 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005021 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005022 nice = 1024;
5023
5024 hlua->task->nice = nice;
5025 return 0;
5026}
5027
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005028/* This function is used as a calback of a task. It is called by the
5029 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5030 * return an E_AGAIN signal, the emmiter of this signal must set a
5031 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005032 *
5033 * Task wrapper are longjmp safe because the only one Lua code
5034 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005035 */
5036static struct task *hlua_process_task(struct task *task)
5037{
5038 struct hlua *hlua = task->context;
5039 enum hlua_exec status;
5040
5041 /* We need to remove the task from the wait queue before executing
5042 * the Lua code because we don't know if it needs to wait for
5043 * another timer or not in the case of E_AGAIN.
5044 */
5045 task_delete(task);
5046
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005047 /* If it is the first call to the task, we must initialize the
5048 * execution timeouts.
5049 */
5050 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005051 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005052
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005053 /* Execute the Lua code. */
5054 status = hlua_ctx_resume(hlua, 1);
5055
5056 switch (status) {
5057 /* finished or yield */
5058 case HLUA_E_OK:
5059 hlua_ctx_destroy(hlua);
5060 task_delete(task);
5061 task_free(task);
5062 break;
5063
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005064 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5065 if (hlua->wake_time != TICK_ETERNITY)
5066 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005067 break;
5068
5069 /* finished with error. */
5070 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005071 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005072 hlua_ctx_destroy(hlua);
5073 task_delete(task);
5074 task_free(task);
5075 break;
5076
5077 case HLUA_E_ERR:
5078 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005079 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005080 hlua_ctx_destroy(hlua);
5081 task_delete(task);
5082 task_free(task);
5083 break;
5084 }
5085 return NULL;
5086}
5087
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005088/* This function is an LUA binding that register LUA function to be
5089 * executed after the HAProxy configuration parsing and before the
5090 * HAProxy scheduler starts. This function expect only one LUA
5091 * argument that is a function. This function returns nothing, but
5092 * throws if an error is encountered.
5093 */
5094__LJMP static int hlua_register_init(lua_State *L)
5095{
5096 struct hlua_init_function *init;
5097 int ref;
5098
5099 MAY_LJMP(check_args(L, 1, "register_init"));
5100
5101 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5102
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005103 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005104 if (!init)
5105 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5106
5107 init->function_ref = ref;
5108 LIST_ADDQ(&hlua_init_functions, &init->l);
5109 return 0;
5110}
5111
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005112/* This functio is an LUA binding. It permits to register a task
5113 * executed in parallel of the main HAroxy activity. The task is
5114 * created and it is set in the HAProxy scheduler. It can be called
5115 * from the "init" section, "post init" or during the runtime.
5116 *
5117 * Lua prototype:
5118 *
5119 * <none> core.register_task(<function>)
5120 */
5121static int hlua_register_task(lua_State *L)
5122{
5123 struct hlua *hlua;
5124 struct task *task;
5125 int ref;
5126
5127 MAY_LJMP(check_args(L, 1, "register_task"));
5128
5129 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5130
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005131 hlua = calloc(1, sizeof(*hlua));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005132 if (!hlua)
5133 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5134
5135 task = task_new();
5136 task->context = hlua;
5137 task->process = hlua_process_task;
5138
5139 if (!hlua_ctx_init(hlua, task))
5140 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5141
5142 /* Restore the function in the stack. */
5143 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5144 hlua->nargs = 0;
5145
5146 /* Schedule task. */
5147 task_schedule(task, now_ms);
5148
5149 return 0;
5150}
5151
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005152/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5153 * doesn't allow "yield" functions because the HAProxy engine cannot
5154 * resume converters.
5155 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005156static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005157{
5158 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005159 struct stream *stream = smp->strm;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005160
Willy Tarreaube508f12016-03-10 11:47:01 +01005161 if (!stream)
5162 return 0;
5163
Willy Tarreau87b09662015-04-03 00:22:06 +02005164 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005165 * Lua context can be not initialized. This behavior
5166 * permits to save performances because a systematic
5167 * Lua initialization cause 5% performances loss.
5168 */
Willy Tarreau87b09662015-04-03 00:22:06 +02005169 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005170 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005171 return 0;
5172 }
5173
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005174 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005175 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005176
5177 /* The following Lua calls can fail. */
5178 if (!SET_SAFE_LJMP(stream->hlua.T)) {
5179 SEND_ERR(stream->be, "Lua converter '%s': critical error.\n", fcn->name);
5180 return 0;
5181 }
5182
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005183 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005184 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005185 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005186 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005187 return 0;
5188 }
5189
5190 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005191 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005192
5193 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005194 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005195 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005196 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005197 return 0;
5198 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005199 hlua_smp2lua(stream->hlua.T, smp);
5200 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005201
5202 /* push keywords in the stack. */
5203 if (arg_p) {
5204 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02005205 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005206 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005207 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005208 return 0;
5209 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005210 hlua_arg2lua(stream->hlua.T, arg_p);
5211 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005212 }
5213 }
5214
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005215 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005216 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005217
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005218 /* At this point the execution is safe. */
5219 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005220 }
5221
5222 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005223 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005224 /* finished. */
5225 case HLUA_E_OK:
5226 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005227 hlua_lua2smp(stream->hlua.T, -1, smp);
5228 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005229 return 1;
5230
5231 /* yield. */
5232 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005233 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005234 return 0;
5235
5236 /* finished with error. */
5237 case HLUA_E_ERRMSG:
5238 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005239 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
5240 fcn->name, lua_tostring(stream->hlua.T, -1));
Willy Tarreau87b09662015-04-03 00:22:06 +02005241 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005242 return 0;
5243
5244 case HLUA_E_ERR:
5245 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005246 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005247
5248 default:
5249 return 0;
5250 }
5251}
5252
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005253/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5254 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005255 * resume sample-fetches. This function will be called by the sample
5256 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005257 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005258static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5259 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005260{
5261 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005262 struct stream *stream = smp->strm;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005263
Willy Tarreaube508f12016-03-10 11:47:01 +01005264 if (!stream)
5265 return 0;
5266
Willy Tarreau87b09662015-04-03 00:22:06 +02005267 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005268 * Lua context can be not initialized. This behavior
5269 * permits to save performances because a systematic
5270 * Lua initialization cause 5% performances loss.
5271 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005272 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005273 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005274 return 0;
5275 }
5276
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005277 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005278 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005279
5280 /* The following Lua calls can fail. */
5281 if (!SET_SAFE_LJMP(stream->hlua.T)) {
5282 SEND_ERR(smp->px, "Lua sample-fetch '%s': critical error.\n", fcn->name);
5283 return 0;
5284 }
5285
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005286 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005287 if (!lua_checkstack(stream->hlua.T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005288 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005289 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005290 return 0;
5291 }
5292
5293 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005294 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005295
5296 /* push arguments in the stack. */
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005297 if (!hlua_txn_new(stream->hlua.T, stream, smp->px, smp->opt & SMP_OPT_DIR)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005298 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005299 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005300 return 0;
5301 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005302 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005303
5304 /* push keywords in the stack. */
5305 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5306 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005307 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005308 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005309 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005310 return 0;
5311 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005312 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005313 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005314 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005315 return 0;
5316 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005317 hlua_arg2lua(stream->hlua.T, arg_p);
5318 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005319 }
5320
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005321 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005322 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005323
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005324 /* At this point the execution is safe. */
5325 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005326 }
5327
5328 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005329 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005330 /* finished. */
5331 case HLUA_E_OK:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005332 if (!hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005333 return 0;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005334 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005335 hlua_lua2smp(stream->hlua.T, -1, smp);
5336 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005337
5338 /* Set the end of execution flag. */
5339 smp->flags &= ~SMP_F_MAY_CHANGE;
5340 return 1;
5341
5342 /* yield. */
5343 case HLUA_E_AGAIN:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005344 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005345 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005346 return 0;
5347
5348 /* finished with error. */
5349 case HLUA_E_ERRMSG:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005350 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005351 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005352 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
5353 fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005354 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005355 return 0;
5356
5357 case HLUA_E_ERR:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005358 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005359 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005360 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005361
5362 default:
5363 return 0;
5364 }
5365}
5366
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005367/* This function is an LUA binding used for registering
5368 * "sample-conv" functions. It expects a converter name used
5369 * in the haproxy configuration file, and an LUA function.
5370 */
5371__LJMP static int hlua_register_converters(lua_State *L)
5372{
5373 struct sample_conv_kw_list *sck;
5374 const char *name;
5375 int ref;
5376 int len;
5377 struct hlua_function *fcn;
5378
5379 MAY_LJMP(check_args(L, 2, "register_converters"));
5380
5381 /* First argument : converter name. */
5382 name = MAY_LJMP(luaL_checkstring(L, 1));
5383
5384 /* Second argument : lua function. */
5385 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5386
5387 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005388 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005389 if (!sck)
5390 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005391 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005392 if (!fcn)
5393 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5394
5395 /* Fill fcn. */
5396 fcn->name = strdup(name);
5397 if (!fcn->name)
5398 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5399 fcn->function_ref = ref;
5400
5401 /* List head */
5402 sck->list.n = sck->list.p = NULL;
5403
5404 /* converter keyword. */
5405 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005406 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005407 if (!sck->kw[0].kw)
5408 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5409
5410 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5411 sck->kw[0].process = hlua_sample_conv_wrapper;
5412 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
5413 sck->kw[0].val_args = NULL;
5414 sck->kw[0].in_type = SMP_T_STR;
5415 sck->kw[0].out_type = SMP_T_STR;
5416 sck->kw[0].private = fcn;
5417
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005418 /* Register this new converter */
5419 sample_register_convs(sck);
5420
5421 return 0;
5422}
5423
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005424/* This fucntion is an LUA binding used for registering
5425 * "sample-fetch" functions. It expects a converter name used
5426 * in the haproxy configuration file, and an LUA function.
5427 */
5428__LJMP static int hlua_register_fetches(lua_State *L)
5429{
5430 const char *name;
5431 int ref;
5432 int len;
5433 struct sample_fetch_kw_list *sfk;
5434 struct hlua_function *fcn;
5435
5436 MAY_LJMP(check_args(L, 2, "register_fetches"));
5437
5438 /* First argument : sample-fetch name. */
5439 name = MAY_LJMP(luaL_checkstring(L, 1));
5440
5441 /* Second argument : lua function. */
5442 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5443
5444 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005445 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005446 if (!sfk)
5447 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005448 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005449 if (!fcn)
5450 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5451
5452 /* Fill fcn. */
5453 fcn->name = strdup(name);
5454 if (!fcn->name)
5455 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5456 fcn->function_ref = ref;
5457
5458 /* List head */
5459 sfk->list.n = sfk->list.p = NULL;
5460
5461 /* sample-fetch keyword. */
5462 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005463 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005464 if (!sfk->kw[0].kw)
5465 return luaL_error(L, "lua out of memory error.");
5466
5467 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5468 sfk->kw[0].process = hlua_sample_fetch_wrapper;
5469 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
5470 sfk->kw[0].val_args = NULL;
5471 sfk->kw[0].out_type = SMP_T_STR;
5472 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5473 sfk->kw[0].val = 0;
5474 sfk->kw[0].private = fcn;
5475
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005476 /* Register this new fetch. */
5477 sample_register_fetches(sfk);
5478
5479 return 0;
5480}
5481
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005482/* This function is a wrapper to execute each LUA function declared
5483 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005484 * return ACT_RET_CONT if the processing is finished (with or without
5485 * error) and return ACT_RET_YIELD if the function must be called again
5486 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005487 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005488static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005489 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005490{
5491 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005492 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005493 int dir;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005494
5495 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01005496 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
5497 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
5498 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
5499 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005500 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005501 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005502 return ACT_RET_CONT;
5503 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005504
Willy Tarreau87b09662015-04-03 00:22:06 +02005505 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005506 * Lua context can be not initialized. This behavior
5507 * permits to save performances because a systematic
5508 * Lua initialization cause 5% performances loss.
5509 */
5510 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005511 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005512 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005513 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005514 }
5515
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005516 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01005517 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005518
5519 /* The following Lua calls can fail. */
5520 if (!SET_SAFE_LJMP(s->hlua.T)) {
5521 SEND_ERR(px, "Lua function '%s': critical error.\n",
5522 rule->arg.hlua_rule->fcn.name);
5523 return ACT_RET_CONT;
5524 }
5525
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005526 /* Check stack available size. */
5527 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005528 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005529 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005530 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005531 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005532 }
5533
5534 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005535 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005536
Willy Tarreau87b09662015-04-03 00:22:06 +02005537 /* Create and and push object stream in the stack. */
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005538 if (!hlua_txn_new(s->hlua.T, s, px, dir)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005539 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005540 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005541 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005542 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005543 }
5544 s->hlua.nargs = 1;
5545
5546 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005547 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005548 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005549 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005550 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005551 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005552 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005553 }
5554 lua_pushstring(s->hlua.T, *arg);
5555 s->hlua.nargs++;
5556 }
5557
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005558 /* Now the execution is safe. */
5559 RESET_SAFE_LJMP(s->hlua.T);
5560
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005561 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005562 s->hlua.max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005563 }
5564
5565 /* Execute the function. */
Willy Tarreau528192d2015-09-27 10:48:01 +02005566 switch (hlua_ctx_resume(&s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005567 /* finished. */
5568 case HLUA_E_OK:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005569 if (!hlua_check_proto(s, dir))
5570 return ACT_RET_ERR;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005571 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005572
5573 /* yield. */
5574 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005575 /* Set timeout in the required channel. */
5576 if (s->hlua.wake_time != TICK_ETERNITY) {
5577 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005578 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005579 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005580 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005581 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005582 /* Some actions can be wake up when a "write" event
5583 * is detected on a response channel. This is useful
5584 * only for actions targetted on the requests.
5585 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01005586 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005587 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005588 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005589 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005590 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01005591 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005592 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005593 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005594
5595 /* finished with error. */
5596 case HLUA_E_ERRMSG:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005597 if (!hlua_check_proto(s, dir))
5598 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005599 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005600 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005601 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005602 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005603 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005604
5605 case HLUA_E_ERR:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005606 if (!hlua_check_proto(s, dir))
5607 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005608 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005609 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005610 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005611
5612 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005613 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005614 }
5615}
5616
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005617struct task *hlua_applet_wakeup(struct task *t)
5618{
5619 struct appctx *ctx = t->context;
5620 struct stream_interface *si = ctx->owner;
5621
5622 /* If the applet is wake up without any expected work, the sheduler
5623 * remove it from the run queue. This flag indicate that the applet
5624 * is waiting for write. If the buffer is full, the main processing
5625 * will send some data and after call the applet, otherwise it call
5626 * the applet ASAP.
5627 */
5628 si_applet_cant_put(si);
5629 appctx_wakeup(ctx);
5630 return NULL;
5631}
5632
5633static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5634{
5635 struct stream_interface *si = ctx->owner;
5636 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5637 struct task *task;
5638 char **arg;
5639
5640 HLUA_INIT(hlua);
5641 ctx->ctx.hlua_apptcp.flags = 0;
5642
5643 /* Create task used by signal to wakeup applets. */
5644 task = task_new();
5645 if (!task) {
5646 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5647 ctx->rule->arg.hlua_rule->fcn.name);
5648 return 0;
5649 }
5650 task->nice = 0;
5651 task->context = ctx;
5652 task->process = hlua_applet_wakeup;
5653 ctx->ctx.hlua_apptcp.task = task;
5654
5655 /* In the execution wrappers linked with a stream, the
5656 * Lua context can be not initialized. This behavior
5657 * permits to save performances because a systematic
5658 * Lua initialization cause 5% performances loss.
5659 */
5660 if (!hlua_ctx_init(hlua, task)) {
5661 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
5662 ctx->rule->arg.hlua_rule->fcn.name);
5663 return 0;
5664 }
5665
5666 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005667 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005668
5669 /* The following Lua calls can fail. */
5670 if (!SET_SAFE_LJMP(hlua->T)) {
5671 SEND_ERR(px, "Lua applet tcp '%s': critical error.\n",
5672 ctx->rule->arg.hlua_rule->fcn.name);
5673 RESET_SAFE_LJMP(hlua->T);
5674 return 0;
5675 }
5676
5677 /* Check stack available size. */
5678 if (!lua_checkstack(hlua->T, 1)) {
5679 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5680 ctx->rule->arg.hlua_rule->fcn.name);
5681 RESET_SAFE_LJMP(hlua->T);
5682 return 0;
5683 }
5684
5685 /* Restore the function in the stack. */
5686 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5687
5688 /* Create and and push object stream in the stack. */
5689 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
5690 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5691 ctx->rule->arg.hlua_rule->fcn.name);
5692 RESET_SAFE_LJMP(hlua->T);
5693 return 0;
5694 }
5695 hlua->nargs = 1;
5696
5697 /* push keywords in the stack. */
5698 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5699 if (!lua_checkstack(hlua->T, 1)) {
5700 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5701 ctx->rule->arg.hlua_rule->fcn.name);
5702 RESET_SAFE_LJMP(hlua->T);
5703 return 0;
5704 }
5705 lua_pushstring(hlua->T, *arg);
5706 hlua->nargs++;
5707 }
5708
5709 RESET_SAFE_LJMP(hlua->T);
5710
5711 /* Wakeup the applet ASAP. */
5712 si_applet_cant_get(si);
5713 si_applet_cant_put(si);
5714
5715 return 1;
5716}
5717
5718static void hlua_applet_tcp_fct(struct appctx *ctx)
5719{
5720 struct stream_interface *si = ctx->owner;
5721 struct stream *strm = si_strm(si);
5722 struct channel *res = si_ic(si);
5723 struct act_rule *rule = ctx->rule;
5724 struct proxy *px = strm->be;
5725 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5726
5727 /* The applet execution is already done. */
5728 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
5729 return;
5730
5731 /* If the stream is disconnect or closed, ldo nothing. */
5732 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5733 return;
5734
5735 /* Execute the function. */
5736 switch (hlua_ctx_resume(hlua, 1)) {
5737 /* finished. */
5738 case HLUA_E_OK:
5739 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5740
5741 /* log time */
5742 strm->logs.tv_request = now;
5743
5744 /* eat the whole request */
5745 bo_skip(si_oc(si), si_ob(si)->o);
5746 res->flags |= CF_READ_NULL;
5747 si_shutr(si);
5748 return;
5749
5750 /* yield. */
5751 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01005752 if (hlua->wake_time != TICK_ETERNITY)
5753 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005754 return;
5755
5756 /* finished with error. */
5757 case HLUA_E_ERRMSG:
5758 /* Display log. */
5759 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
5760 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
5761 lua_pop(hlua->T, 1);
5762 goto error;
5763
5764 case HLUA_E_ERR:
5765 /* Display log. */
5766 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
5767 rule->arg.hlua_rule->fcn.name);
5768 goto error;
5769
5770 default:
5771 goto error;
5772 }
5773
5774error:
5775
5776 /* For all other cases, just close the stream. */
5777 si_shutw(si);
5778 si_shutr(si);
5779 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5780}
5781
5782static void hlua_applet_tcp_release(struct appctx *ctx)
5783{
5784 task_free(ctx->ctx.hlua_apptcp.task);
5785 ctx->ctx.hlua_apptcp.task = NULL;
5786 hlua_ctx_destroy(&ctx->ctx.hlua_apptcp.hlua);
5787}
5788
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005789/* The function returns 1 if the initialisation is complete, 0 if
5790 * an errors occurs and -1 if more data are required for initializing
5791 * the applet.
5792 */
5793static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5794{
5795 struct stream_interface *si = ctx->owner;
5796 struct channel *req = si_oc(si);
5797 struct http_msg *msg;
5798 struct http_txn *txn;
5799 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5800 char **arg;
5801 struct hdr_ctx hdr;
5802 struct task *task;
5803 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
5804
5805 /* Wait for a full HTTP request. */
5806 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
5807 if (smp.flags & SMP_F_MAY_CHANGE)
5808 return -1;
5809 return 0;
5810 }
5811 txn = strm->txn;
5812 msg = &txn->req;
5813
Willy Tarreau0078bfc2015-10-07 20:20:28 +02005814 /* We want two things in HTTP mode :
5815 * - enforce server-close mode if we were in keep-alive, so that the
5816 * applet is released after each response ;
5817 * - enable request body transfer to the applet in order to resync
5818 * with the response body.
5819 */
5820 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
5821 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02005822
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005823 HLUA_INIT(hlua);
5824 ctx->ctx.hlua_apphttp.left_bytes = -1;
5825 ctx->ctx.hlua_apphttp.flags = 0;
5826
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01005827 if (txn->req.flags & HTTP_MSGF_VER_11)
5828 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
5829
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005830 /* Create task used by signal to wakeup applets. */
5831 task = task_new();
5832 if (!task) {
5833 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
5834 ctx->rule->arg.hlua_rule->fcn.name);
5835 return 0;
5836 }
5837 task->nice = 0;
5838 task->context = ctx;
5839 task->process = hlua_applet_wakeup;
5840 ctx->ctx.hlua_apphttp.task = task;
5841
5842 /* In the execution wrappers linked with a stream, the
5843 * Lua context can be not initialized. This behavior
5844 * permits to save performances because a systematic
5845 * Lua initialization cause 5% performances loss.
5846 */
5847 if (!hlua_ctx_init(hlua, task)) {
5848 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
5849 ctx->rule->arg.hlua_rule->fcn.name);
5850 return 0;
5851 }
5852
5853 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005854 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005855
5856 /* The following Lua calls can fail. */
5857 if (!SET_SAFE_LJMP(hlua->T)) {
5858 SEND_ERR(px, "Lua applet http '%s': critical error.\n",
5859 ctx->rule->arg.hlua_rule->fcn.name);
5860 return 0;
5861 }
5862
5863 /* Check stack available size. */
5864 if (!lua_checkstack(hlua->T, 1)) {
5865 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5866 ctx->rule->arg.hlua_rule->fcn.name);
5867 RESET_SAFE_LJMP(hlua->T);
5868 return 0;
5869 }
5870
5871 /* Restore the function in the stack. */
5872 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5873
5874 /* Create and and push object stream in the stack. */
5875 if (!hlua_applet_http_new(hlua->T, ctx)) {
5876 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5877 ctx->rule->arg.hlua_rule->fcn.name);
5878 RESET_SAFE_LJMP(hlua->T);
5879 return 0;
5880 }
5881 hlua->nargs = 1;
5882
5883 /* Look for a 100-continue expected. */
5884 if (msg->flags & HTTP_MSGF_VER_11) {
5885 hdr.idx = 0;
5886 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
5887 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
5888 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
5889 }
5890
5891 /* push keywords in the stack. */
5892 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5893 if (!lua_checkstack(hlua->T, 1)) {
5894 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5895 ctx->rule->arg.hlua_rule->fcn.name);
5896 RESET_SAFE_LJMP(hlua->T);
5897 return 0;
5898 }
5899 lua_pushstring(hlua->T, *arg);
5900 hlua->nargs++;
5901 }
5902
5903 RESET_SAFE_LJMP(hlua->T);
5904
5905 /* Wakeup the applet when data is ready for read. */
5906 si_applet_cant_get(si);
5907
5908 return 1;
5909}
5910
5911static void hlua_applet_http_fct(struct appctx *ctx)
5912{
5913 struct stream_interface *si = ctx->owner;
5914 struct stream *strm = si_strm(si);
5915 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005916 struct act_rule *rule = ctx->rule;
5917 struct proxy *px = strm->be;
5918 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5919 char *blk1;
5920 int len1;
5921 char *blk2;
5922 int len2;
5923 int ret;
5924
5925 /* If the stream is disconnect or closed, ldo nothing. */
5926 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5927 return;
5928
5929 /* Set the currently running flag. */
5930 if (!HLUA_IS_RUNNING(hlua) &&
5931 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
5932
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005933 /* Wait for full HTTP analysys. */
5934 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
5935 si_applet_cant_get(si);
5936 return;
5937 }
5938
5939 /* Store the max amount of bytes that we can read. */
5940 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
5941
5942 /* We need to flush the request header. This left the body
5943 * for the Lua.
5944 */
5945
5946 /* Read the maximum amount of data avalaible. */
5947 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
5948 if (ret == -1)
5949 return;
5950
5951 /* No data available, ask for more data. */
5952 if (ret == 1)
5953 len2 = 0;
5954 if (ret == 0)
5955 len1 = 0;
5956 if (len1 + len2 < strm->txn->req.eoh + 2) {
5957 si_applet_cant_get(si);
5958 return;
5959 }
5960
5961 /* skip the requests bytes. */
5962 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
5963 }
5964
5965 /* Executes The applet if it is not done. */
5966 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
5967
5968 /* Execute the function. */
5969 switch (hlua_ctx_resume(hlua, 1)) {
5970 /* finished. */
5971 case HLUA_E_OK:
5972 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
5973 break;
5974
5975 /* yield. */
5976 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01005977 if (hlua->wake_time != TICK_ETERNITY)
5978 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005979 return;
5980
5981 /* finished with error. */
5982 case HLUA_E_ERRMSG:
5983 /* Display log. */
5984 SEND_ERR(px, "Lua applet http '%s': %s.\n",
5985 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
5986 lua_pop(hlua->T, 1);
5987 goto error;
5988
5989 case HLUA_E_ERR:
5990 /* Display log. */
5991 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
5992 rule->arg.hlua_rule->fcn.name);
5993 goto error;
5994
5995 default:
5996 goto error;
5997 }
5998 }
5999
6000 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6001
6002 /* We must send the final chunk. */
6003 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6004 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6005
6006 /* sent last chunk at once. */
6007 ret = bi_putblk(res, "0\r\n\r\n", 5);
6008
6009 /* critical error. */
6010 if (ret == -2 || ret == -3) {
6011 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6012 rule->arg.hlua_rule->fcn.name);
6013 goto error;
6014 }
6015
6016 /* no enough space error. */
6017 if (ret == -1) {
6018 si_applet_cant_put(si);
6019 return;
6020 }
6021
6022 /* set the last chunk sent. */
6023 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6024 }
6025
6026 /* close the connection. */
6027
6028 /* status / log */
6029 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6030 strm->logs.tv_request = now;
6031
6032 /* eat the whole request */
6033 bo_skip(si_oc(si), si_ob(si)->o);
6034 res->flags |= CF_READ_NULL;
6035 si_shutr(si);
6036
6037 return;
6038 }
6039
6040error:
6041
6042 /* If we are in HTTP mode, and we are not send any
6043 * data, return a 500 server error in best effort:
6044 * if there are no room avalaible in the buffer,
6045 * just close the connection.
6046 */
6047 bi_putblk(res, error_500, strlen(error_500));
6048 if (!(strm->flags & SF_ERR_MASK))
6049 strm->flags |= SF_ERR_RESOURCE;
6050 si_shutw(si);
6051 si_shutr(si);
6052 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6053}
6054
6055static void hlua_applet_http_release(struct appctx *ctx)
6056{
6057 task_free(ctx->ctx.hlua_apphttp.task);
6058 ctx->ctx.hlua_apphttp.task = NULL;
6059 hlua_ctx_destroy(&ctx->ctx.hlua_apphttp.hlua);
6060}
6061
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006062/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6063 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006064 *
6065 * This function can fail with an abort() due to an Lua critical error.
6066 * We are in the configuration parsing process of HAProxy, this abort() is
6067 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006068 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006069static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6070 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006071{
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006072 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6073
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006074 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006075 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006076 if (!rule->arg.hlua_rule) {
6077 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006078 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006079 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006080
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006081 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006082 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006083
6084 /* TODO: later accept arguments. */
6085 rule->arg.hlua_rule->args = NULL;
6086
Thierry FOURNIER42148732015-09-02 17:17:33 +02006087 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006088 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006089 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006090}
6091
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006092static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6093 struct act_rule *rule, char **err)
6094{
6095 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6096
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006097 /* HTTP applets are forbidden in tcp-request rules.
6098 * HTTP applet request requires everything initilized by
6099 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6100 * The applet will be immediately initilized, but its before
6101 * the call of this analyzer.
6102 */
6103 if (rule->from != ACT_F_HTTP_REQ) {
6104 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6105 return ACT_RET_PRS_ERR;
6106 }
6107
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006108 /* Memory for the rule. */
6109 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6110 if (!rule->arg.hlua_rule) {
6111 memprintf(err, "out of memory error");
6112 return ACT_RET_PRS_ERR;
6113 }
6114
6115 /* Reference the Lua function and store the reference. */
6116 rule->arg.hlua_rule->fcn = *fcn;
6117
6118 /* TODO: later accept arguments. */
6119 rule->arg.hlua_rule->args = NULL;
6120
6121 /* Add applet pointer in the rule. */
6122 rule->applet.obj_type = OBJ_TYPE_APPLET;
6123 rule->applet.name = fcn->name;
6124 rule->applet.init = hlua_applet_http_init;
6125 rule->applet.fct = hlua_applet_http_fct;
6126 rule->applet.release = hlua_applet_http_release;
6127 rule->applet.timeout = hlua_timeout_applet;
6128
6129 return ACT_RET_PRS_OK;
6130}
6131
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006132/* This function is an LUA binding used for registering
6133 * "sample-conv" functions. It expects a converter name used
6134 * in the haproxy configuration file, and an LUA function.
6135 */
6136__LJMP static int hlua_register_action(lua_State *L)
6137{
6138 struct action_kw_list *akl;
6139 const char *name;
6140 int ref;
6141 int len;
6142 struct hlua_function *fcn;
6143
Thierry FOURNIERed0bdaa2015-12-20 19:51:06 +01006144 MAY_LJMP(check_args(L, 3, "register_action"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006145
6146 /* First argument : converter name. */
6147 name = MAY_LJMP(luaL_checkstring(L, 1));
6148
6149 /* Second argument : environment. */
6150 if (lua_type(L, 2) != LUA_TTABLE)
6151 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6152
6153 /* Third argument : lua function. */
6154 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6155
6156 /* browse the second argulent as an array. */
6157 lua_pushnil(L);
6158 while (lua_next(L, 2) != 0) {
6159 if (lua_type(L, -1) != LUA_TSTRING)
6160 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6161
6162 /* Check required environment. Only accepted "http" or "tcp". */
6163 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006164 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006165 if (!akl)
6166 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006167 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006168 if (!fcn)
6169 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6170
6171 /* Fill fcn. */
6172 fcn->name = strdup(name);
6173 if (!fcn->name)
6174 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6175 fcn->function_ref = ref;
6176
6177 /* List head */
6178 akl->list.n = akl->list.p = NULL;
6179
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006180 /* action keyword. */
6181 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006182 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006183 if (!akl->kw[0].kw)
6184 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6185
6186 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6187
6188 akl->kw[0].match_pfx = 0;
6189 akl->kw[0].private = fcn;
6190 akl->kw[0].parse = action_register_lua;
6191
6192 /* select the action registering point. */
6193 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6194 tcp_req_cont_keywords_register(akl);
6195 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6196 tcp_res_cont_keywords_register(akl);
6197 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6198 http_req_keywords_register(akl);
6199 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6200 http_res_keywords_register(akl);
6201 else
6202 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6203 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6204 "are expected.", lua_tostring(L, -1)));
6205
6206 /* pop the environment string. */
6207 lua_pop(L, 1);
6208 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006209 return ACT_RET_PRS_OK;
6210}
6211
6212static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6213 struct act_rule *rule, char **err)
6214{
6215 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6216
6217 /* Memory for the rule. */
6218 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6219 if (!rule->arg.hlua_rule) {
6220 memprintf(err, "out of memory error");
6221 return ACT_RET_PRS_ERR;
6222 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006223
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006224 /* Reference the Lua function and store the reference. */
6225 rule->arg.hlua_rule->fcn = *fcn;
6226
6227 /* TODO: later accept arguments. */
6228 rule->arg.hlua_rule->args = NULL;
6229
6230 /* Add applet pointer in the rule. */
6231 rule->applet.obj_type = OBJ_TYPE_APPLET;
6232 rule->applet.name = fcn->name;
6233 rule->applet.init = hlua_applet_tcp_init;
6234 rule->applet.fct = hlua_applet_tcp_fct;
6235 rule->applet.release = hlua_applet_tcp_release;
6236 rule->applet.timeout = hlua_timeout_applet;
6237
6238 return 0;
6239}
6240
6241/* This function is an LUA binding used for registering
6242 * "sample-conv" functions. It expects a converter name used
6243 * in the haproxy configuration file, and an LUA function.
6244 */
6245__LJMP static int hlua_register_service(lua_State *L)
6246{
6247 struct action_kw_list *akl;
6248 const char *name;
6249 const char *env;
6250 int ref;
6251 int len;
6252 struct hlua_function *fcn;
6253
6254 MAY_LJMP(check_args(L, 3, "register_service"));
6255
6256 /* First argument : converter name. */
6257 name = MAY_LJMP(luaL_checkstring(L, 1));
6258
6259 /* Second argument : environment. */
6260 env = MAY_LJMP(luaL_checkstring(L, 2));
6261
6262 /* Third argument : lua function. */
6263 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6264
6265 /* Check required environment. Only accepted "http" or "tcp". */
6266 /* Allocate and fill the sample fetch keyword struct. */
6267 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6268 if (!akl)
6269 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6270 fcn = calloc(1, sizeof(*fcn));
6271 if (!fcn)
6272 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6273
6274 /* Fill fcn. */
6275 len = strlen("<lua.>") + strlen(name) + 1;
6276 fcn->name = calloc(1, len);
6277 if (!fcn->name)
6278 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6279 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6280 fcn->function_ref = ref;
6281
6282 /* List head */
6283 akl->list.n = akl->list.p = NULL;
6284
6285 /* converter keyword. */
6286 len = strlen("lua.") + strlen(name) + 1;
6287 akl->kw[0].kw = calloc(1, len);
6288 if (!akl->kw[0].kw)
6289 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6290
6291 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6292
6293 if (strcmp(env, "tcp") == 0)
6294 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006295 else if (strcmp(env, "http") == 0)
6296 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006297 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006298 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6299 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006300
6301 akl->kw[0].match_pfx = 0;
6302 akl->kw[0].private = fcn;
6303
6304 /* End of array. */
6305 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6306
6307 /* Register this new converter */
6308 service_keywords_register(akl);
6309
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006310 return 0;
6311}
6312
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006313static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
6314 struct proxy *defpx, const char *file, int line,
6315 char **err, unsigned int *timeout)
6316{
6317 const char *error;
6318
6319 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
6320 if (error && *error != '\0') {
6321 memprintf(err, "%s: invalid timeout", args[0]);
6322 return -1;
6323 }
6324 return 0;
6325}
6326
6327static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
6328 struct proxy *defpx, const char *file, int line,
6329 char **err)
6330{
6331 return hlua_read_timeout(args, section_type, curpx, defpx,
6332 file, line, err, &hlua_timeout_session);
6333}
6334
6335static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
6336 struct proxy *defpx, const char *file, int line,
6337 char **err)
6338{
6339 return hlua_read_timeout(args, section_type, curpx, defpx,
6340 file, line, err, &hlua_timeout_task);
6341}
6342
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006343static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
6344 struct proxy *defpx, const char *file, int line,
6345 char **err)
6346{
6347 return hlua_read_timeout(args, section_type, curpx, defpx,
6348 file, line, err, &hlua_timeout_applet);
6349}
6350
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006351static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
6352 struct proxy *defpx, const char *file, int line,
6353 char **err)
6354{
6355 char *error;
6356
6357 hlua_nb_instruction = strtoll(args[1], &error, 10);
6358 if (*error != '\0') {
6359 memprintf(err, "%s: invalid number", args[0]);
6360 return -1;
6361 }
6362 return 0;
6363}
6364
Willy Tarreau32f61e22015-03-18 17:54:59 +01006365static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
6366 struct proxy *defpx, const char *file, int line,
6367 char **err)
6368{
6369 char *error;
6370
6371 if (*(args[1]) == 0) {
6372 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
6373 return -1;
6374 }
6375 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
6376 if (*error != '\0') {
6377 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
6378 return -1;
6379 }
6380 return 0;
6381}
6382
6383
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006384/* This function is called by the main configuration key "lua-load". It loads and
6385 * execute an lua file during the parsing of the HAProxy configuration file. It is
6386 * the main lua entry point.
6387 *
6388 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
6389 * occured, otherwise it returns 0.
6390 *
6391 * In some error case, LUA set an error message in top of the stack. This function
6392 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006393 *
6394 * This function can fail with an abort() due to an Lua critical error.
6395 * We are in the configuration parsing process of HAProxy, this abort() is
6396 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006397 */
6398static int hlua_load(char **args, int section_type, struct proxy *curpx,
6399 struct proxy *defpx, const char *file, int line,
6400 char **err)
6401{
6402 int error;
6403
6404 /* Just load and compile the file. */
6405 error = luaL_loadfile(gL.T, args[1]);
6406 if (error) {
6407 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
6408 lua_pop(gL.T, 1);
6409 return -1;
6410 }
6411
6412 /* If no syntax error where detected, execute the code. */
6413 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
6414 switch (error) {
6415 case LUA_OK:
6416 break;
6417 case LUA_ERRRUN:
6418 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
6419 lua_pop(gL.T, 1);
6420 return -1;
6421 case LUA_ERRMEM:
6422 memprintf(err, "lua out of memory error\n");
6423 return -1;
6424 case LUA_ERRERR:
6425 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
6426 lua_pop(gL.T, 1);
6427 return -1;
6428 case LUA_ERRGCMM:
6429 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
6430 lua_pop(gL.T, 1);
6431 return -1;
6432 default:
6433 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
6434 lua_pop(gL.T, 1);
6435 return -1;
6436 }
6437
6438 return 0;
6439}
6440
6441/* configuration keywords declaration */
6442static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006443 { CFG_GLOBAL, "lua-load", hlua_load },
6444 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
6445 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02006446 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006447 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01006448 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006449 { 0, NULL, NULL },
6450}};
6451
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006452/* This function can fail with an abort() due to an Lua critical error.
6453 * We are in the initialisation process of HAProxy, this abort() is
6454 * tolerated.
6455 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006456int hlua_post_init()
6457{
6458 struct hlua_init_function *init;
6459 const char *msg;
6460 enum hlua_exec ret;
6461
6462 list_for_each_entry(init, &hlua_init_functions, l) {
6463 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
6464 ret = hlua_ctx_resume(&gL, 0);
6465 switch (ret) {
6466 case HLUA_E_OK:
6467 lua_pop(gL.T, -1);
6468 return 1;
6469 case HLUA_E_AGAIN:
6470 Alert("lua init: yield not allowed.\n");
6471 return 0;
6472 case HLUA_E_ERRMSG:
6473 msg = lua_tostring(gL.T, -1);
6474 Alert("lua init: %s.\n", msg);
6475 return 0;
6476 case HLUA_E_ERR:
6477 default:
6478 Alert("lua init: unknown runtime error.\n");
6479 return 0;
6480 }
6481 }
6482 return 1;
6483}
6484
Willy Tarreau32f61e22015-03-18 17:54:59 +01006485/* The memory allocator used by the Lua stack. <ud> is a pointer to the
6486 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
6487 * is the previously allocated size or the kind of object in case of a new
6488 * allocation. <nsize> is the requested new size.
6489 */
6490static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
6491{
6492 struct hlua_mem_allocator *zone = ud;
6493
6494 if (nsize == 0) {
6495 /* it's a free */
6496 if (ptr)
6497 zone->allocated -= osize;
6498 free(ptr);
6499 return NULL;
6500 }
6501
6502 if (!ptr) {
6503 /* it's a new allocation */
6504 if (zone->limit && zone->allocated + nsize > zone->limit)
6505 return NULL;
6506
6507 ptr = malloc(nsize);
6508 if (ptr)
6509 zone->allocated += nsize;
6510 return ptr;
6511 }
6512
6513 /* it's a realloc */
6514 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
6515 return NULL;
6516
6517 ptr = realloc(ptr, nsize);
6518 if (ptr)
6519 zone->allocated += nsize - osize;
6520 return ptr;
6521}
6522
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006523/* Ithis function can fail with an abort() due to an Lua critical error.
6524 * We are in the initialisation process of HAProxy, this abort() is
6525 * tolerated.
6526 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01006527void hlua_init(void)
6528{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006529 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006530 int idx;
6531 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006532 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006533 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006534#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006535 struct srv_kw *kw;
6536 int tmp_error;
6537 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01006538 char *args[] = { /* SSL client configuration. */
6539 "ssl",
6540 "verify",
6541 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01006542 NULL
6543 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006544#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006545
Willy Tarreau87b09662015-04-03 00:22:06 +02006546 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006547 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
6548
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006549 /* Register configuration keywords. */
6550 cfg_register_keywords(&cfg_kws);
6551
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006552 /* Init main lua stack. */
6553 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01006554 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006555 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006556 gL.T = luaL_newstate();
6557 hlua_sethlua(&gL);
6558 gL.Tref = LUA_REFNIL;
6559 gL.task = NULL;
6560
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006561 /* From this point, until the end of the initialisation fucntion,
6562 * the Lua function can fail with an abort. We are in the initialisation
6563 * process of HAProxy, this abort() is tolerated.
6564 */
6565
Willy Tarreau32f61e22015-03-18 17:54:59 +01006566 /* change the memory allocators to track memory usage */
6567 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
6568
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006569 /* Initialise lua. */
6570 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006571
Thierry Fournier75933d42016-01-21 09:30:18 +01006572 /* Set safe environment for the initialisation. */
6573 if (!SET_SAFE_LJMP(gL.T)) {
6574 fprintf(stderr, "Lua init: critical error.\n");
6575 exit(1);
6576 }
6577
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006578 /*
6579 *
6580 * Create "core" object.
6581 *
6582 */
6583
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01006584 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006585 lua_newtable(gL.T);
6586
6587 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006588 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006589 hlua_class_const_int(gL.T, log_levels[i], i);
6590
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006591 /* Register special functions. */
6592 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006593 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006594 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006595 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006596 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006597 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006598 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01006599 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006600 hlua_class_function(gL.T, "sleep", hlua_sleep);
6601 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01006602 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
6603 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
6604 hlua_class_function(gL.T, "set_map", hlua_set_map);
6605 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006606 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006607 hlua_class_function(gL.T, "log", hlua_log);
6608 hlua_class_function(gL.T, "Debug", hlua_log_debug);
6609 hlua_class_function(gL.T, "Info", hlua_log_info);
6610 hlua_class_function(gL.T, "Warning", hlua_log_warning);
6611 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02006612 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01006613 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006614
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006615 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006616
6617 /*
6618 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006619 * Register class Map
6620 *
6621 */
6622
6623 /* This table entry is the object "Map" base. */
6624 lua_newtable(gL.T);
6625
6626 /* register pattern types. */
6627 for (i=0; i<PAT_MATCH_NUM; i++)
6628 hlua_class_const_int(gL.T, pat_match_names[i], i);
6629
6630 /* register constructor. */
6631 hlua_class_function(gL.T, "new", hlua_map_new);
6632
6633 /* Create and fill the metatable. */
6634 lua_newtable(gL.T);
6635
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006636 /* Create the __tostring identifier */
6637 lua_pushstring(gL.T, "__tostring");
6638 lua_pushstring(gL.T, CLASS_MAP);
6639 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6640 lua_rawset(gL.T, -3);
6641
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006642 /* Create and fille the __index entry. */
6643 lua_pushstring(gL.T, "__index");
6644 lua_newtable(gL.T);
6645
6646 /* Register . */
6647 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
6648 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
6649
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006650 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006651
6652 /* Register previous table in the registry with reference and named entry. */
6653 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6654 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6655 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
6656 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6657
6658 /* Assign the metatable to the mai Map object. */
6659 lua_setmetatable(gL.T, -2);
6660
6661 /* Set a name to the table. */
6662 lua_setglobal(gL.T, "Map");
6663
6664 /*
6665 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006666 * Register class Channel
6667 *
6668 */
6669
6670 /* Create and fill the metatable. */
6671 lua_newtable(gL.T);
6672
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006673 /* Create the __tostring identifier */
6674 lua_pushstring(gL.T, "__tostring");
6675 lua_pushstring(gL.T, CLASS_CHANNEL);
6676 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6677 lua_rawset(gL.T, -3);
6678
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006679 /* Create and fille the __index entry. */
6680 lua_pushstring(gL.T, "__index");
6681 lua_newtable(gL.T);
6682
6683 /* Register . */
6684 hlua_class_function(gL.T, "get", hlua_channel_get);
6685 hlua_class_function(gL.T, "dup", hlua_channel_dup);
6686 hlua_class_function(gL.T, "getline", hlua_channel_getline);
6687 hlua_class_function(gL.T, "set", hlua_channel_set);
6688 hlua_class_function(gL.T, "append", hlua_channel_append);
6689 hlua_class_function(gL.T, "send", hlua_channel_send);
6690 hlua_class_function(gL.T, "forward", hlua_channel_forward);
6691 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
6692 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
6693
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006694 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006695
6696 /* Register previous table in the registry with reference and named entry. */
6697 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6698 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
6699 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6700
6701 /*
6702 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006703 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006704 *
6705 */
6706
6707 /* Create and fill the metatable. */
6708 lua_newtable(gL.T);
6709
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006710 /* Create the __tostring identifier */
6711 lua_pushstring(gL.T, "__tostring");
6712 lua_pushstring(gL.T, CLASS_FETCHES);
6713 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6714 lua_rawset(gL.T, -3);
6715
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006716 /* Create and fille the __index entry. */
6717 lua_pushstring(gL.T, "__index");
6718 lua_newtable(gL.T);
6719
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006720 /* Browse existing fetches and create the associated
6721 * object method.
6722 */
6723 sf = NULL;
6724 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
6725
6726 /* Dont register the keywork if the arguments check function are
6727 * not safe during the runtime.
6728 */
6729 if ((sf->val_args != NULL) &&
6730 (sf->val_args != val_payload_lv) &&
6731 (sf->val_args != val_hdr))
6732 continue;
6733
6734 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
6735 * by an underscore.
6736 */
6737 strncpy(trash.str, sf->kw, trash.size);
6738 trash.str[trash.size - 1] = '\0';
6739 for (p = trash.str; *p; p++)
6740 if (*p == '.' || *p == '-' || *p == '+')
6741 *p = '_';
6742
6743 /* Register the function. */
6744 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01006745 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006746 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006747 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006748 }
6749
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006750 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006751
6752 /* Register previous table in the registry with reference and named entry. */
6753 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6754 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
6755 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6756
6757 /*
6758 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006759 * Register class Converters
6760 *
6761 */
6762
6763 /* Create and fill the metatable. */
6764 lua_newtable(gL.T);
6765
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006766 /* Create the __tostring identifier */
6767 lua_pushstring(gL.T, "__tostring");
6768 lua_pushstring(gL.T, CLASS_CONVERTERS);
6769 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6770 lua_rawset(gL.T, -3);
6771
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006772 /* Create and fill the __index entry. */
6773 lua_pushstring(gL.T, "__index");
6774 lua_newtable(gL.T);
6775
6776 /* Browse existing converters and create the associated
6777 * object method.
6778 */
6779 sc = NULL;
6780 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
6781 /* Dont register the keywork if the arguments check function are
6782 * not safe during the runtime.
6783 */
6784 if (sc->val_args != NULL)
6785 continue;
6786
6787 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
6788 * by an underscore.
6789 */
6790 strncpy(trash.str, sc->kw, trash.size);
6791 trash.str[trash.size - 1] = '\0';
6792 for (p = trash.str; *p; p++)
6793 if (*p == '.' || *p == '-' || *p == '+')
6794 *p = '_';
6795
6796 /* Register the function. */
6797 lua_pushstring(gL.T, trash.str);
6798 lua_pushlightuserdata(gL.T, sc);
6799 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006800 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006801 }
6802
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006803 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006804
6805 /* Register previous table in the registry with reference and named entry. */
6806 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6807 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
6808 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6809
6810 /*
6811 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006812 * Register class HTTP
6813 *
6814 */
6815
6816 /* Create and fill the metatable. */
6817 lua_newtable(gL.T);
6818
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006819 /* Create the __tostring identifier */
6820 lua_pushstring(gL.T, "__tostring");
6821 lua_pushstring(gL.T, CLASS_HTTP);
6822 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6823 lua_rawset(gL.T, -3);
6824
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006825 /* Create and fille the __index entry. */
6826 lua_pushstring(gL.T, "__index");
6827 lua_newtable(gL.T);
6828
6829 /* Register Lua functions. */
6830 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
6831 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
6832 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
6833 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
6834 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
6835 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
6836 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
6837 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
6838 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
6839 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
6840
6841 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
6842 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
6843 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
6844 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
6845 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
6846 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006847 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006848
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006849 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006850
6851 /* Register previous table in the registry with reference and named entry. */
6852 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6853 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
6854 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6855
6856 /*
6857 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006858 * Register class AppletTCP
6859 *
6860 */
6861
6862 /* Create and fill the metatable. */
6863 lua_newtable(gL.T);
6864
6865 /* Create the __tostring identifier */
6866 lua_pushstring(gL.T, "__tostring");
6867 lua_pushstring(gL.T, CLASS_APPLET_TCP);
6868 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6869 lua_rawset(gL.T, -3);
6870
6871 /* Create and fille the __index entry. */
6872 lua_pushstring(gL.T, "__index");
6873 lua_newtable(gL.T);
6874
6875 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01006876 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
6877 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
6878 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
6879 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
6880 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006881
6882 lua_settable(gL.T, -3);
6883
6884 /* Register previous table in the registry with reference and named entry. */
6885 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6886 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_APPLET_TCP); /* register class session. */
6887 class_applet_tcp_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6888
6889 /*
6890 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006891 * Register class AppletHTTP
6892 *
6893 */
6894
6895 /* Create and fill the metatable. */
6896 lua_newtable(gL.T);
6897
6898 /* Create the __tostring identifier */
6899 lua_pushstring(gL.T, "__tostring");
6900 lua_pushstring(gL.T, CLASS_APPLET_HTTP);
6901 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6902 lua_rawset(gL.T, -3);
6903
6904 /* Create and fille the __index entry. */
6905 lua_pushstring(gL.T, "__index");
6906 lua_newtable(gL.T);
6907
6908 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01006909 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
6910 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006911 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
6912 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
6913 hlua_class_function(gL.T, "send", hlua_applet_http_send);
6914 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
6915 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
6916 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
6917
6918 lua_settable(gL.T, -3);
6919
6920 /* Register previous table in the registry with reference and named entry. */
6921 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6922 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_APPLET_HTTP); /* register class session. */
6923 class_applet_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6924
6925 /*
6926 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006927 * Register class TXN
6928 *
6929 */
6930
6931 /* Create and fill the metatable. */
6932 lua_newtable(gL.T);
6933
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006934 /* Create the __tostring identifier */
6935 lua_pushstring(gL.T, "__tostring");
6936 lua_pushstring(gL.T, CLASS_TXN);
6937 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6938 lua_rawset(gL.T, -3);
6939
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006940 /* Create and fille the __index entry. */
6941 lua_pushstring(gL.T, "__index");
6942 lua_newtable(gL.T);
6943
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006944 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01006945 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
6946 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006947 hlua_class_function(gL.T, "set_var", hlua_set_var);
6948 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006949 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006950 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
6951 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
6952 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006953 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
6954 hlua_class_function(gL.T, "log", hlua_txn_log);
6955 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
6956 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
6957 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
6958 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006959
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006960 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006961
6962 /* Register previous table in the registry with reference and named entry. */
6963 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6964 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
6965 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006966
6967 /*
6968 *
6969 * Register class Socket
6970 *
6971 */
6972
6973 /* Create and fill the metatable. */
6974 lua_newtable(gL.T);
6975
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006976 /* Create the __tostring identifier */
6977 lua_pushstring(gL.T, "__tostring");
6978 lua_pushstring(gL.T, CLASS_SOCKET);
6979 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6980 lua_rawset(gL.T, -3);
6981
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006982 /* Create and fille the __index entry. */
6983 lua_pushstring(gL.T, "__index");
6984 lua_newtable(gL.T);
6985
Baptiste Assmann84bb4932015-03-02 21:40:06 +01006986#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006987 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01006988#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006989 hlua_class_function(gL.T, "connect", hlua_socket_connect);
6990 hlua_class_function(gL.T, "send", hlua_socket_send);
6991 hlua_class_function(gL.T, "receive", hlua_socket_receive);
6992 hlua_class_function(gL.T, "close", hlua_socket_close);
6993 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
6994 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
6995 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
6996 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
6997
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006998 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006999
7000 /* Register the garbage collector entry. */
7001 lua_pushstring(gL.T, "__gc");
7002 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007003 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007004
7005 /* Register previous table in the registry with reference and named entry. */
7006 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007007 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
7008 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
7009
7010 /* Proxy and server configuration initialisation. */
7011 memset(&socket_proxy, 0, sizeof(socket_proxy));
7012 init_new_proxy(&socket_proxy);
7013 socket_proxy.parent = NULL;
7014 socket_proxy.last_change = now.tv_sec;
7015 socket_proxy.id = "LUA-SOCKET";
7016 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7017 socket_proxy.maxconn = 0;
7018 socket_proxy.accept = NULL;
7019 socket_proxy.options2 |= PR_O2_INDEPSTR;
7020 socket_proxy.srv = NULL;
7021 socket_proxy.conn_retries = 0;
7022 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7023
7024 /* Init TCP server: unchanged parameters */
7025 memset(&socket_tcp, 0, sizeof(socket_tcp));
7026 socket_tcp.next = NULL;
7027 socket_tcp.proxy = &socket_proxy;
7028 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7029 LIST_INIT(&socket_tcp.actconns);
7030 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007031 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007032 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007033 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007034 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
7035 socket_tcp.last_change = 0;
7036 socket_tcp.id = "LUA-TCP-CONN";
7037 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7038 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7039 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7040
7041 /* XXX: Copy default parameter from default server,
7042 * but the default server is not initialized.
7043 */
7044 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7045 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7046 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7047 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7048 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7049 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7050 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7051 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7052 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7053 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7054
7055 socket_tcp.check.status = HCHK_STATUS_INI;
7056 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7057 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7058 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7059 socket_tcp.check.server = &socket_tcp;
7060
7061 socket_tcp.agent.status = HCHK_STATUS_INI;
7062 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7063 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7064 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7065 socket_tcp.agent.server = &socket_tcp;
7066
7067 socket_tcp.xprt = &raw_sock;
7068
7069#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007070 /* Init TCP server: unchanged parameters */
7071 memset(&socket_ssl, 0, sizeof(socket_ssl));
7072 socket_ssl.next = NULL;
7073 socket_ssl.proxy = &socket_proxy;
7074 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7075 LIST_INIT(&socket_ssl.actconns);
7076 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007077 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007078 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007079 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007080 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
7081 socket_ssl.last_change = 0;
7082 socket_ssl.id = "LUA-SSL-CONN";
7083 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7084 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7085 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7086
7087 /* XXX: Copy default parameter from default server,
7088 * but the default server is not initialized.
7089 */
7090 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7091 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7092 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7093 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7094 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7095 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7096 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7097 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7098 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7099 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7100
7101 socket_ssl.check.status = HCHK_STATUS_INI;
7102 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7103 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7104 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7105 socket_ssl.check.server = &socket_ssl;
7106
7107 socket_ssl.agent.status = HCHK_STATUS_INI;
7108 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7109 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7110 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7111 socket_ssl.agent.server = &socket_ssl;
7112
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007113 socket_ssl.use_ssl = 1;
7114 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007115
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007116 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007117 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7118 /*
7119 *
7120 * If the keyword is not known, we can search in the registered
7121 * server keywords. This is usefull to configure special SSL
7122 * features like client certificates and ssl_verify.
7123 *
7124 */
7125 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7126 if (tmp_error != 0) {
7127 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7128 abort(); /* This must be never arrives because the command line
7129 not editable by the user. */
7130 }
7131 idx += kw->skip;
7132 }
7133 }
7134
7135 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007136 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007137#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007138
7139 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007140}