blob: 5cf23203fc6e40bfc8de5101e122f32e88eca35d [file] [log] [blame]
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001#include <sys/socket.h>
2
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01006#include <lauxlib.h>
7#include <lua.h>
8#include <lualib.h>
9
Thierry FOURNIER463119c2015-03-10 00:35:36 +010010#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
11#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010012#endif
13
Thierry FOURNIER380d0932015-01-23 14:27:52 +010014#include <ebpttree.h>
15
16#include <common/cfgparse.h>
17
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010018#include <types/connection.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010019#include <types/hlua.h>
20#include <types/proxy.h>
21
Thierry FOURNIER55da1652015-01-23 11:36:30 +010022#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020023#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010024#include <proto/channel.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010025#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010026#include <proto/hlua.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020027#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010028#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010029#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010030#include <proto/payload.h>
31#include <proto/proto_http.h>
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010032#include <proto/proto_tcp.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010033#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010034#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010035#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020036#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020037#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010038#include <proto/ssl_sock.h>
39#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010040#include <proto/task.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020041#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010042
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010043/* Lua uses longjmp to perform yield or throwing errors. This
44 * macro is used only for identifying the function that can
45 * not return because a longjmp is executed.
46 * __LJMP marks a prototype of hlua file that can use longjmp.
47 * WILL_LJMP() marks an lua function that will use longjmp.
48 * MAY_LJMP() marks an lua function that may use longjmp.
49 */
50#define __LJMP
51#define WILL_LJMP(func) func
52#define MAY_LJMP(func) func
53
Thierry FOURNIERbabae282015-09-17 11:36:37 +020054/* This couple of function executes securely some Lua calls outside of
55 * the lua runtime environment. Each Lua call can return a longjmp
56 * if it encounter a memory error.
57 *
58 * Lua documentation extract:
59 *
60 * If an error happens outside any protected environment, Lua calls
61 * a panic function (see lua_atpanic) and then calls abort, thus
62 * exiting the host application. Your panic function can avoid this
63 * exit by never returning (e.g., doing a long jump to your own
64 * recovery point outside Lua).
65 *
66 * The panic function runs as if it were a message handler (see
67 * §2.3); in particular, the error message is at the top of the
68 * stack. However, there is no guarantee about stack space. To push
69 * anything on the stack, the panic function must first check the
70 * available space (see §4.2).
71 *
72 * We must check all the Lua entry point. This includes:
73 * - The include/proto/hlua.h exported functions
74 * - the task wrapper function
75 * - The action wrapper function
76 * - The converters wrapper function
77 * - The sample-fetch wrapper functions
78 *
79 * It is tolerated that the initilisation function returns an abort.
80 * Before each Lua abort, an error message is writed on stderr.
81 *
82 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
83 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
84 * because they must be exists in the program stack when the longjmp
85 * is called.
86 */
87jmp_buf safe_ljmp_env;
88static int hlua_panic_safe(lua_State *L) { return 0; }
89static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
90
91#define SET_SAFE_LJMP(__L) \
92 ({ \
93 int ret; \
94 if (setjmp(safe_ljmp_env) != 0) { \
95 lua_atpanic(__L, hlua_panic_safe); \
96 ret = 0; \
97 } else { \
98 lua_atpanic(__L, hlua_panic_ljmp); \
99 ret = 1; \
100 } \
101 ret; \
102 })
103
104/* If we are the last function catching Lua errors, we
105 * must reset the panic function.
106 */
107#define RESET_SAFE_LJMP(__L) \
108 do { \
109 lua_atpanic(__L, hlua_panic_safe); \
110 } while(0)
111
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200112/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200113#define APPLET_DONE 0x01 /* applet processing is done. */
114#define APPLET_100C 0x02 /* 100 continue expected. */
115#define APPLET_HDR_SENT 0x04 /* Response header sent. */
116#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
117#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100118#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200119
120#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200121
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100122/* The main Lua execution context. */
123struct hlua gL;
124
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100125/* This is the memory pool containing all the signal structs. These
126 * struct are used to store each requiered signal between two tasks.
127 */
128struct pool_head *pool2_hlua_com;
129
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100130/* Used for Socket connection. */
131static struct proxy socket_proxy;
132static struct server socket_tcp;
133#ifdef USE_OPENSSL
134static struct server socket_ssl;
135#endif
136
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100137/* List head of the function called at the initialisation time. */
138struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
139
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100140/* The following variables contains the reference of the different
141 * Lua classes. These references are useful for identify metadata
142 * associated with an object.
143 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100144static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100145static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100146static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100147static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100148static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100149static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200150static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200151static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200152static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100153
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100154/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200155 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100156 * short timeout. Lua linked with tasks doesn't have a timeout
157 * because a task may remain alive during all the haproxy execution.
158 */
159static unsigned int hlua_timeout_session = 4000; /* session timeout. */
160static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200161static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100162
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100163/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
164 * it is used for preventing infinite loops.
165 *
166 * I test the scheer with an infinite loop containing one incrementation
167 * and one test. I run this loop between 10 seconds, I raise a ceil of
168 * 710M loops from one interrupt each 9000 instructions, so I fix the value
169 * to one interrupt each 10 000 instructions.
170 *
171 * configured | Number of
172 * instructions | loops executed
173 * between two | in milions
174 * forced yields |
175 * ---------------+---------------
176 * 10 | 160
177 * 500 | 670
178 * 1000 | 680
179 * 5000 | 700
180 * 7000 | 700
181 * 8000 | 700
182 * 9000 | 710 <- ceil
183 * 10000 | 710
184 * 100000 | 710
185 * 1000000 | 710
186 *
187 */
188static unsigned int hlua_nb_instruction = 10000;
189
Willy Tarreau32f61e22015-03-18 17:54:59 +0100190/* Descriptor for the memory allocation state. If limit is not null, it will
191 * be enforced on any memory allocation.
192 */
193struct hlua_mem_allocator {
194 size_t allocated;
195 size_t limit;
196};
197
198static struct hlua_mem_allocator hlua_global_allocator;
199
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200200static const char error_500[] =
201 "HTTP/1.0 500 Server Error\r\n"
202 "Cache-Control: no-cache\r\n"
203 "Connection: close\r\n"
204 "Content-Type: text/html\r\n"
205 "\r\n"
206 "<html><body><h1>500 Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
207
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100208/* These functions converts types between HAProxy internal args or
209 * sample and LUA types. Another function permits to check if the
210 * LUA stack contains arguments according with an required ARG_T
211 * format.
212 */
213static int hlua_arg2lua(lua_State *L, const struct arg *arg);
214static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100215__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
216 unsigned int mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100217static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100218static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100219static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
220
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200221__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
222
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200223#define SEND_ERR(__be, __fmt, __args...) \
224 do { \
225 send_log(__be, LOG_ERR, __fmt, ## __args); \
226 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
227 Alert(__fmt, ## __args); \
228 } while (0)
229
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100230/* Used to check an Lua function type in the stack. It creates and
231 * returns a reference of the function. This function throws an
232 * error if the rgument is not a "function".
233 */
234__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
235{
236 if (!lua_isfunction(L, argno)) {
237 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
238 WILL_LJMP(luaL_argerror(L, argno, msg));
239 }
240 lua_pushvalue(L, argno);
241 return luaL_ref(L, LUA_REGISTRYINDEX);
242}
243
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200244/* Return the string that is of the top of the stack. */
245const char *hlua_get_top_error_string(lua_State *L)
246{
247 if (lua_gettop(L) < 1)
248 return "unknown error";
249 if (lua_type(L, -1) != LUA_TSTRING)
250 return "unknown error";
251 return lua_tostring(L, -1);
252}
253
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100254/* The three following functions are useful for adding entries
255 * in a table. These functions takes a string and respectively an
256 * integer, a string or a function and add it to the table in the
257 * top of the stack.
258 *
259 * These functions throws an error if no more stack size is
260 * available.
261 */
262__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100263 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100264{
265 if (!lua_checkstack(L, 2))
266 WILL_LJMP(luaL_error(L, "full stack"));
267 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100268 lua_pushinteger(L, value);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200269 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100270}
271__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
272 const char *value)
273{
274 if (!lua_checkstack(L, 2))
275 WILL_LJMP(luaL_error(L, "full stack"));
276 lua_pushstring(L, name);
277 lua_pushstring(L, value);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200278 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100279}
280__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
281 int (*function)(lua_State *L))
282{
283 if (!lua_checkstack(L, 2))
284 WILL_LJMP(luaL_error(L, "full stack"));
285 lua_pushstring(L, name);
286 lua_pushcclosure(L, function, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200287 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100288}
289
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +0200290__LJMP static int hlua_dump_object(struct lua_State *L)
291{
292 const char *name = (const char *)lua_tostring(L, lua_upvalueindex(1));
293 lua_pushfstring(L, "HAProxy class %s", name);
294 return 1;
295}
296
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100297/* This function check the number of arguments available in the
298 * stack. If the number of arguments available is not the same
299 * then <nb> an error is throwed.
300 */
301__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
302{
303 if (lua_gettop(L) == nb)
304 return;
305 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
306}
307
308/* Return true if the data in stack[<ud>] is an object of
309 * type <class_ref>.
310 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100311static int hlua_metaistype(lua_State *L, int ud, int class_ref)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100312{
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100313 if (!lua_getmetatable(L, ud))
314 return 0;
315
316 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
317 if (!lua_rawequal(L, -1, -2)) {
318 lua_pop(L, 2);
319 return 0;
320 }
321
322 lua_pop(L, 2);
323 return 1;
324}
325
326/* Return an object of the expected type, or throws an error. */
327__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
328{
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100329 void *p;
330
331 /* Check if the stack entry is an array. */
332 if (!lua_istable(L, ud))
333 WILL_LJMP(luaL_argerror(L, ud, NULL));
334 /* Check if the metadata have the expected type. */
335 if (!hlua_metaistype(L, ud, class_ref))
336 WILL_LJMP(luaL_argerror(L, ud, NULL));
337 /* Push on the stack at the entry [0] of the table. */
338 lua_rawgeti(L, ud, 0);
339 /* Check if this entry is userdata. */
340 p = lua_touserdata(L, -1);
341 if (!p)
342 WILL_LJMP(luaL_argerror(L, ud, NULL));
343 /* Remove the entry returned by lua_rawgeti(). */
344 lua_pop(L, 1);
345 /* Return the associated struct. */
346 return p;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100347}
348
349/* This fucntion push an error string prefixed by the file name
350 * and the line number where the error is encountered.
351 */
352static int hlua_pusherror(lua_State *L, const char *fmt, ...)
353{
354 va_list argp;
355 va_start(argp, fmt);
356 luaL_where(L, 1);
357 lua_pushvfstring(L, fmt, argp);
358 va_end(argp);
359 lua_concat(L, 2);
360 return 1;
361}
362
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100363/* This function register a new signal. "lua" is the current lua
364 * execution context. It contains a pointer to the associated task.
365 * "link" is a list head attached to an other task that must be wake
366 * the lua task if an event occurs. This is useful with external
367 * events like TCP I/O or sleep functions. This funcion allocate
368 * memory for the signal.
369 */
370static int hlua_com_new(struct hlua *lua, struct list *link)
371{
372 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
373 if (!com)
374 return 0;
375 LIST_ADDQ(&lua->com, &com->purge_me);
376 LIST_ADDQ(link, &com->wake_me);
377 com->task = lua->task;
378 return 1;
379}
380
381/* This function purge all the pending signals when the LUA execution
382 * is finished. This prevent than a coprocess try to wake a deleted
383 * task. This function remove the memory associated to the signal.
384 */
385static void hlua_com_purge(struct hlua *lua)
386{
387 struct hlua_com *com, *back;
388
389 /* Delete all pending communication signals. */
390 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
391 LIST_DEL(&com->purge_me);
392 LIST_DEL(&com->wake_me);
393 pool_free2(pool2_hlua_com, com);
394 }
395}
396
397/* This function sends signals. It wakes all the tasks attached
398 * to a list head, and remove the signal, and free the used
399 * memory.
400 */
401static void hlua_com_wake(struct list *wake)
402{
403 struct hlua_com *com, *back;
404
405 /* Wake task and delete all pending communication signals. */
406 list_for_each_entry_safe(com, back, wake, wake_me) {
407 LIST_DEL(&com->purge_me);
408 LIST_DEL(&com->wake_me);
409 task_wakeup(com->task, TASK_WOKEN_MSG);
410 pool_free2(pool2_hlua_com, com);
411 }
412}
413
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100414/* This functions is used with sample fetch and converters. It
415 * converts the HAProxy configuration argument in a lua stack
416 * values.
417 *
418 * It takes an array of "arg", and each entry of the array is
419 * converted and pushed in the LUA stack.
420 */
421static int hlua_arg2lua(lua_State *L, const struct arg *arg)
422{
423 switch (arg->type) {
424 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100425 case ARGT_TIME:
426 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100427 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100428 break;
429
430 case ARGT_STR:
431 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
432 break;
433
434 case ARGT_IPV4:
435 case ARGT_IPV6:
436 case ARGT_MSK4:
437 case ARGT_MSK6:
438 case ARGT_FE:
439 case ARGT_BE:
440 case ARGT_TAB:
441 case ARGT_SRV:
442 case ARGT_USR:
443 case ARGT_MAP:
444 default:
445 lua_pushnil(L);
446 break;
447 }
448 return 1;
449}
450
451/* This function take one entrie in an LUA stack at the index "ud",
452 * and try to convert it in an HAProxy argument entry. This is useful
453 * with sample fetch wrappers. The input arguments are gived to the
454 * lua wrapper and converted as arg list by thi function.
455 */
456static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
457{
458 switch (lua_type(L, ud)) {
459
460 case LUA_TNUMBER:
461 case LUA_TBOOLEAN:
462 arg->type = ARGT_SINT;
463 arg->data.sint = lua_tointeger(L, ud);
464 break;
465
466 case LUA_TSTRING:
467 arg->type = ARGT_STR;
468 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
469 break;
470
471 case LUA_TUSERDATA:
472 case LUA_TNIL:
473 case LUA_TTABLE:
474 case LUA_TFUNCTION:
475 case LUA_TTHREAD:
476 case LUA_TLIGHTUSERDATA:
477 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200478 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100479 break;
480 }
481 return 1;
482}
483
484/* the following functions are used to convert a struct sample
485 * in Lua type. This useful to convert the return of the
486 * fetchs or converters.
487 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100488static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100489{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200490 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100491 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100492 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200493 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100494 break;
495
496 case SMP_T_BIN:
497 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200498 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100499 break;
500
501 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200502 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100503 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
504 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
505 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
506 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
507 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
508 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
509 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
510 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
511 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200512 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100513 break;
514 default:
515 lua_pushnil(L);
516 break;
517 }
518 break;
519
520 case SMP_T_IPV4:
521 case SMP_T_IPV6:
522 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200523 if (sample_casts[smp->data.type][SMP_T_STR] &&
524 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200525 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100526 else
527 lua_pushnil(L);
528 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100529 default:
530 lua_pushnil(L);
531 break;
532 }
533 return 1;
534}
535
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100536/* the following functions are used to convert a struct sample
537 * in Lua strings. This is useful to convert the return of the
538 * fetchs or converters.
539 */
540static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
541{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200542 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100543
544 case SMP_T_BIN:
545 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200546 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100547 break;
548
549 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200550 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100551 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
552 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
553 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
554 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
555 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
556 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
557 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
558 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
559 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200560 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100561 break;
562 default:
563 lua_pushstring(L, "");
564 break;
565 }
566 break;
567
568 case SMP_T_SINT:
569 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100570 case SMP_T_IPV4:
571 case SMP_T_IPV6:
572 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200573 if (sample_casts[smp->data.type][SMP_T_STR] &&
574 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200575 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100576 else
577 lua_pushstring(L, "");
578 break;
579 default:
580 lua_pushstring(L, "");
581 break;
582 }
583 return 1;
584}
585
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100586/* the following functions are used to convert an Lua type in a
587 * struct sample. This is useful to provide data from a converter
588 * to the LUA code.
589 */
590static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
591{
592 switch (lua_type(L, ud)) {
593
594 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200595 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200596 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100597 break;
598
599
600 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200601 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200602 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100603 break;
604
605 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200606 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100607 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200608 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100609 break;
610
611 case LUA_TUSERDATA:
612 case LUA_TNIL:
613 case LUA_TTABLE:
614 case LUA_TFUNCTION:
615 case LUA_TTHREAD:
616 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200617 case LUA_TNONE:
618 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200619 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200620 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100621 break;
622 }
623 return 1;
624}
625
626/* This function check the "argp" builded by another conversion function
627 * is in accord with the expected argp defined by the "mask". The fucntion
628 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100629 *
630 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
631 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100632 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100633__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
634 unsigned int mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100635{
636 int min_arg;
637 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100638 struct proxy *px;
639 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100640
641 idx = 0;
642 min_arg = ARGM(mask);
643 mask >>= ARGM_BITS;
644
645 while (1) {
646
647 /* Check oversize. */
648 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100649 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100650 }
651
652 /* Check for mandatory arguments. */
653 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100654 if (idx < min_arg) {
655
656 /* If miss other argument than the first one, we return an error. */
657 if (idx > 0)
658 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
659
660 /* If first argument have a certain type, some default values
661 * may be used. See the function smp_resolve_args().
662 */
663 switch (mask & ARGT_MASK) {
664
665 case ARGT_FE:
666 if (!(p->cap & PR_CAP_FE))
667 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
668 argp[idx].data.prx = p;
669 argp[idx].type = ARGT_FE;
670 argp[idx+1].type = ARGT_STOP;
671 break;
672
673 case ARGT_BE:
674 if (!(p->cap & PR_CAP_BE))
675 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
676 argp[idx].data.prx = p;
677 argp[idx].type = ARGT_BE;
678 argp[idx+1].type = ARGT_STOP;
679 break;
680
681 case ARGT_TAB:
682 argp[idx].data.prx = p;
683 argp[idx].type = ARGT_TAB;
684 argp[idx+1].type = ARGT_STOP;
685 break;
686
687 default:
688 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
689 break;
690 }
691 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100692 return 0;
693 }
694
695 /* Check for exceed the number of requiered argument. */
696 if ((mask & ARGT_MASK) == ARGT_STOP &&
697 argp[idx].type != ARGT_STOP) {
698 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
699 }
700
701 if ((mask & ARGT_MASK) == ARGT_STOP &&
702 argp[idx].type == ARGT_STOP) {
703 return 0;
704 }
705
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100706 /* Convert some argument types. */
707 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100708 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100709 if (argp[idx].type != ARGT_SINT)
710 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
711 argp[idx].type = ARGT_SINT;
712 break;
713
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100714 case ARGT_TIME:
715 if (argp[idx].type != ARGT_SINT)
716 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200717 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100718 break;
719
720 case ARGT_SIZE:
721 if (argp[idx].type != ARGT_SINT)
722 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200723 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100724 break;
725
726 case ARGT_FE:
727 if (argp[idx].type != ARGT_STR)
728 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
729 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
730 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200731 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100732 if (!argp[idx].data.prx)
733 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
734 argp[idx].type = ARGT_FE;
735 break;
736
737 case ARGT_BE:
738 if (argp[idx].type != ARGT_STR)
739 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
740 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
741 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200742 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100743 if (!argp[idx].data.prx)
744 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
745 argp[idx].type = ARGT_BE;
746 break;
747
748 case ARGT_TAB:
749 if (argp[idx].type != ARGT_STR)
750 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
751 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
752 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200753 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100754 if (!argp[idx].data.prx)
755 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
756 argp[idx].type = ARGT_TAB;
757 break;
758
759 case ARGT_SRV:
760 if (argp[idx].type != ARGT_STR)
761 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
762 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
763 trash.str[argp[idx].data.str.len] = 0;
764 sname = strrchr(trash.str, '/');
765 if (sname) {
766 *sname++ = '\0';
767 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200768 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100769 if (!px)
770 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
771 }
772 else {
773 sname = trash.str;
774 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100775 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100776 argp[idx].data.srv = findserver(px, sname);
777 if (!argp[idx].data.srv)
778 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
779 argp[idx].type = ARGT_SRV;
780 break;
781
782 case ARGT_IPV4:
783 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
784 trash.str[argp[idx].data.str.len] = 0;
785 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
786 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
787 argp[idx].type = ARGT_IPV4;
788 break;
789
790 case ARGT_MSK4:
791 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
792 trash.str[argp[idx].data.str.len] = 0;
793 if (!str2mask(trash.str, &argp[idx].data.ipv4))
794 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
795 argp[idx].type = ARGT_MSK4;
796 break;
797
798 case ARGT_IPV6:
799 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
800 trash.str[argp[idx].data.str.len] = 0;
801 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
802 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
803 argp[idx].type = ARGT_IPV6;
804 break;
805
806 case ARGT_MSK6:
807 case ARGT_MAP:
808 case ARGT_REG:
809 case ARGT_USR:
810 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100811 break;
812 }
813
814 /* Check for type of argument. */
815 if ((mask & ARGT_MASK) != argp[idx].type) {
816 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
817 arg_type_names[(mask & ARGT_MASK)],
818 arg_type_names[argp[idx].type & ARGT_MASK]);
819 WILL_LJMP(luaL_argerror(L, first + idx, msg));
820 }
821
822 /* Next argument. */
823 mask >>= ARGT_BITS;
824 idx++;
825 }
826}
827
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100828/*
829 * The following functions are used to make correspondance between the the
830 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100831 *
832 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100833 * - hlua_sethlua : create the association between hlua context and lua_state.
834 */
835static inline struct hlua *hlua_gethlua(lua_State *L)
836{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100837 struct hlua **hlua = lua_getextraspace(L);
838 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100839}
840static inline void hlua_sethlua(struct hlua *hlua)
841{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100842 struct hlua **hlua_store = lua_getextraspace(hlua->T);
843 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100844}
845
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100846/* This function is used to send logs. It try to send on screen (stderr)
847 * and on the default syslog server.
848 */
849static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
850{
851 struct tm tm;
852 char *p;
853
854 /* Cleanup the log message. */
855 p = trash.str;
856 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200857 if (p >= trash.str + trash.size - 1) {
858 /* Break the message if exceed the buffer size. */
859 *(p-4) = ' ';
860 *(p-3) = '.';
861 *(p-2) = '.';
862 *(p-1) = '.';
863 break;
864 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100865 if (isprint(*msg))
866 *p = *msg;
867 else
868 *p = '.';
869 }
870 *p = '\0';
871
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200872 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100873 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200874 get_localtime(date.tv_sec, &tm);
875 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100876 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
877 (int)getpid(), trash.str);
878 fflush(stderr);
879 }
880}
881
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100882/* This function just ensure that the yield will be always
883 * returned with a timeout and permit to set some flags
884 */
885__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100886 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100887{
888 struct hlua *hlua = hlua_gethlua(L);
889
890 /* Set the wake timeout. If timeout is required, we set
891 * the expiration time.
892 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200893 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100894
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100895 hlua->flags |= flags;
896
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100897 /* Process the yield. */
898 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
899}
900
Willy Tarreau87b09662015-04-03 00:22:06 +0200901/* This function initialises the Lua environment stored in the stream.
902 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100903 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200904 *
905 * This function is particular. it initialises a new Lua thread. If the
906 * initialisation fails (example: out of memory error), the lua function
907 * throws an error (longjmp).
908 *
909 * This function manipulates two Lua stack: the main and the thread. Only
910 * the main stack can fail. The thread is not manipulated. This function
911 * MUST NOT manipulate the created thread stack state, because is not
912 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100913 */
914int hlua_ctx_init(struct hlua *lua, struct task *task)
915{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200916 if (!SET_SAFE_LJMP(gL.T)) {
917 lua->Tref = LUA_REFNIL;
918 return 0;
919 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100920 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100921 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100922 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100923 lua->T = lua_newthread(gL.T);
924 if (!lua->T) {
925 lua->Tref = LUA_REFNIL;
926 return 0;
927 }
928 hlua_sethlua(lua);
929 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
930 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200931 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100932 return 1;
933}
934
Willy Tarreau87b09662015-04-03 00:22:06 +0200935/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100936 * is destroyed. The destroy also the memory context. The struct "lua"
937 * is not freed.
938 */
939void hlua_ctx_destroy(struct hlua *lua)
940{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100941 if (!lua->T)
942 return;
943
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100944 /* Purge all the pending signals. */
945 hlua_com_purge(lua);
946
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100947 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
948 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200949
950 /* Forces a garbage collecting process. If the Lua program is finished
951 * without error, we run the GC on the thread pointer. Its freed all
952 * the unused memory.
953 * If the thread is finnish with an error or is currently yielded,
954 * it seems that the GC applied on the thread doesn't clean anything,
955 * so e run the GC on the main thread.
956 * NOTE: maybe this action locks all the Lua threads untiml the en of
957 * the garbage collection.
958 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200959 if (lua->flags & HLUA_MUST_GC) {
960 lua_gc(lua->T, LUA_GCCOLLECT, 0);
961 if (lua_status(lua->T) != LUA_OK)
962 lua_gc(gL.T, LUA_GCCOLLECT, 0);
963 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200964
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200965 lua->T = NULL;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100966}
967
968/* This function is used to restore the Lua context when a coroutine
969 * fails. This function copy the common memory between old coroutine
970 * and the new coroutine. The old coroutine is destroyed, and its
971 * replaced by the new coroutine.
972 * If the flag "keep_msg" is set, the last entry of the old is assumed
973 * as string error message and it is copied in the new stack.
974 */
975static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
976{
977 lua_State *T;
978 int new_ref;
979
980 /* Renew the main LUA stack doesn't have sense. */
981 if (lua == &gL)
982 return 0;
983
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100984 /* New Lua coroutine. */
985 T = lua_newthread(gL.T);
986 if (!T)
987 return 0;
988
989 /* Copy last error message. */
990 if (keep_msg)
991 lua_xmove(lua->T, T, 1);
992
993 /* Copy data between the coroutines. */
994 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
995 lua_xmove(lua->T, T, 1);
996 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
997
998 /* Destroy old data. */
999 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1000
1001 /* The thread is garbage collected by Lua. */
1002 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
1003
1004 /* Fill the struct with the new coroutine values. */
1005 lua->Mref = new_ref;
1006 lua->T = T;
1007 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
1008
1009 /* Set context. */
1010 hlua_sethlua(lua);
1011
1012 return 1;
1013}
1014
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001015void hlua_hook(lua_State *L, lua_Debug *ar)
1016{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001017 struct hlua *hlua = hlua_gethlua(L);
1018
1019 /* Lua cannot yield when its returning from a function,
1020 * so, we can fix the interrupt hook to 1 instruction,
1021 * expecting that the function is finnished.
1022 */
1023 if (lua_gethookmask(L) & LUA_MASKRET) {
1024 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1025 return;
1026 }
1027
1028 /* restore the interrupt condition. */
1029 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1030
1031 /* If we interrupt the Lua processing in yieldable state, we yield.
1032 * If the state is not yieldable, trying yield causes an error.
1033 */
1034 if (lua_isyieldable(L))
1035 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
1036
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001037 /* If we cannot yield, update the clock and check the timeout. */
1038 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001039 hlua->run_time += now_ms - hlua->start_time;
1040 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001041 lua_pushfstring(L, "execution timeout");
1042 WILL_LJMP(lua_error(L));
1043 }
1044
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001045 /* Update the start time. */
1046 hlua->start_time = now_ms;
1047
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001048 /* Try to interrupt the process at the end of the current
1049 * unyieldable function.
1050 */
1051 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001052}
1053
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001054/* This function start or resumes the Lua stack execution. If the flag
1055 * "yield_allowed" if no set and the LUA stack execution returns a yield
1056 * The function return an error.
1057 *
1058 * The function can returns 4 values:
1059 * - HLUA_E_OK : The execution is terminated without any errors.
1060 * - HLUA_E_AGAIN : The execution must continue at the next associated
1061 * task wakeup.
1062 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
1063 * the top of the stack.
1064 * - HLUA_E_ERR : An error has occured without error message.
1065 *
1066 * If an error occured, the stack is renewed and it is ready to run new
1067 * LUA code.
1068 */
1069static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1070{
1071 int ret;
1072 const char *msg;
1073
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001074 /* Initialise run time counter. */
1075 if (!HLUA_IS_RUNNING(lua))
1076 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001077
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001078resume_execution:
1079
1080 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1081 * instructions. it is used for preventing infinite loops.
1082 */
1083 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1084
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001085 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001086 HLUA_SET_RUN(lua);
1087 HLUA_CLR_CTRLYIELD(lua);
1088 HLUA_CLR_WAKERESWR(lua);
1089 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001090
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001091 /* Update the start time. */
1092 lua->start_time = now_ms;
1093
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001094 /* Call the function. */
1095 ret = lua_resume(lua->T, gL.T, lua->nargs);
1096 switch (ret) {
1097
1098 case LUA_OK:
1099 ret = HLUA_E_OK;
1100 break;
1101
1102 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001103 /* Check if the execution timeout is expired. It it is the case, we
1104 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001105 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001106 tv_update_date(0, 1);
1107 lua->run_time += now_ms - lua->start_time;
1108 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001109 lua_settop(lua->T, 0); /* Empty the stack. */
1110 if (!lua_checkstack(lua->T, 1)) {
1111 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001112 break;
1113 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001114 lua_pushfstring(lua->T, "execution timeout");
1115 ret = HLUA_E_ERRMSG;
1116 break;
1117 }
1118 /* Process the forced yield. if the general yield is not allowed or
1119 * if no task were associated this the current Lua execution
1120 * coroutine, we resume the execution. Else we want to return in the
1121 * scheduler and we want to be waked up again, to continue the
1122 * current Lua execution. So we schedule our own task.
1123 */
1124 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001125 if (!yield_allowed || !lua->task)
1126 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001127 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001128 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001129 if (!yield_allowed) {
1130 lua_settop(lua->T, 0); /* Empty the stack. */
1131 if (!lua_checkstack(lua->T, 1)) {
1132 ret = HLUA_E_ERR;
1133 break;
1134 }
1135 lua_pushfstring(lua->T, "yield not allowed");
1136 ret = HLUA_E_ERRMSG;
1137 break;
1138 }
1139 ret = HLUA_E_AGAIN;
1140 break;
1141
1142 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001143
1144 /* Special exit case. The traditionnal exit is returned as an error
1145 * because the errors ares the only one mean to return immediately
1146 * from and lua execution.
1147 */
1148 if (lua->flags & HLUA_EXIT) {
1149 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001150 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001151 break;
1152 }
1153
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001154 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001155 if (!lua_checkstack(lua->T, 1)) {
1156 ret = HLUA_E_ERR;
1157 break;
1158 }
1159 msg = lua_tostring(lua->T, -1);
1160 lua_settop(lua->T, 0); /* Empty the stack. */
1161 lua_pop(lua->T, 1);
1162 if (msg)
1163 lua_pushfstring(lua->T, "runtime error: %s", msg);
1164 else
1165 lua_pushfstring(lua->T, "unknown runtime error");
1166 ret = HLUA_E_ERRMSG;
1167 break;
1168
1169 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001170 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001171 lua_settop(lua->T, 0); /* Empty the stack. */
1172 if (!lua_checkstack(lua->T, 1)) {
1173 ret = HLUA_E_ERR;
1174 break;
1175 }
1176 lua_pushfstring(lua->T, "out of memory error");
1177 ret = HLUA_E_ERRMSG;
1178 break;
1179
1180 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001181 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001182 if (!lua_checkstack(lua->T, 1)) {
1183 ret = HLUA_E_ERR;
1184 break;
1185 }
1186 msg = lua_tostring(lua->T, -1);
1187 lua_settop(lua->T, 0); /* Empty the stack. */
1188 lua_pop(lua->T, 1);
1189 if (msg)
1190 lua_pushfstring(lua->T, "message handler error: %s", msg);
1191 else
1192 lua_pushfstring(lua->T, "message handler error");
1193 ret = HLUA_E_ERRMSG;
1194 break;
1195
1196 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001197 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001198 lua_settop(lua->T, 0); /* Empty the stack. */
1199 if (!lua_checkstack(lua->T, 1)) {
1200 ret = HLUA_E_ERR;
1201 break;
1202 }
1203 lua_pushfstring(lua->T, "unknonwn error");
1204 ret = HLUA_E_ERRMSG;
1205 break;
1206 }
1207
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001208 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001209 if (lua->flags & HLUA_MUST_GC &&
1210 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001211 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1212
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001213 switch (ret) {
1214 case HLUA_E_AGAIN:
1215 break;
1216
1217 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001218 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001219 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001220 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001221 break;
1222
1223 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001224 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001225 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001226 hlua_ctx_renew(lua, 0);
1227 break;
1228
1229 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001230 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001231 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001232 break;
1233 }
1234
1235 return ret;
1236}
1237
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001238/* This function exit the current code. */
1239__LJMP static int hlua_done(lua_State *L)
1240{
1241 struct hlua *hlua = hlua_gethlua(L);
1242
1243 hlua->flags |= HLUA_EXIT;
1244 WILL_LJMP(lua_error(L));
1245
1246 return 0;
1247}
1248
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001249/* This function is an LUA binding. It provides a function
1250 * for deleting ACL from a referenced ACL file.
1251 */
1252__LJMP static int hlua_del_acl(lua_State *L)
1253{
1254 const char *name;
1255 const char *key;
1256 struct pat_ref *ref;
1257
1258 MAY_LJMP(check_args(L, 2, "del_acl"));
1259
1260 name = MAY_LJMP(luaL_checkstring(L, 1));
1261 key = MAY_LJMP(luaL_checkstring(L, 2));
1262
1263 ref = pat_ref_lookup(name);
1264 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001265 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001266
1267 pat_ref_delete(ref, key);
1268 return 0;
1269}
1270
1271/* This function is an LUA binding. It provides a function
1272 * for deleting map entry from a referenced map file.
1273 */
1274static int hlua_del_map(lua_State *L)
1275{
1276 const char *name;
1277 const char *key;
1278 struct pat_ref *ref;
1279
1280 MAY_LJMP(check_args(L, 2, "del_map"));
1281
1282 name = MAY_LJMP(luaL_checkstring(L, 1));
1283 key = MAY_LJMP(luaL_checkstring(L, 2));
1284
1285 ref = pat_ref_lookup(name);
1286 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001287 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001288
1289 pat_ref_delete(ref, key);
1290 return 0;
1291}
1292
1293/* This function is an LUA binding. It provides a function
1294 * for adding ACL pattern from a referenced ACL file.
1295 */
1296static int hlua_add_acl(lua_State *L)
1297{
1298 const char *name;
1299 const char *key;
1300 struct pat_ref *ref;
1301
1302 MAY_LJMP(check_args(L, 2, "add_acl"));
1303
1304 name = MAY_LJMP(luaL_checkstring(L, 1));
1305 key = MAY_LJMP(luaL_checkstring(L, 2));
1306
1307 ref = pat_ref_lookup(name);
1308 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001309 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001310
1311 if (pat_ref_find_elt(ref, key) == NULL)
1312 pat_ref_add(ref, key, NULL, NULL);
1313 return 0;
1314}
1315
1316/* This function is an LUA binding. It provides a function
1317 * for setting map pattern and sample from a referenced map
1318 * file.
1319 */
1320static int hlua_set_map(lua_State *L)
1321{
1322 const char *name;
1323 const char *key;
1324 const char *value;
1325 struct pat_ref *ref;
1326
1327 MAY_LJMP(check_args(L, 3, "set_map"));
1328
1329 name = MAY_LJMP(luaL_checkstring(L, 1));
1330 key = MAY_LJMP(luaL_checkstring(L, 2));
1331 value = MAY_LJMP(luaL_checkstring(L, 3));
1332
1333 ref = pat_ref_lookup(name);
1334 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001335 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001336
1337 if (pat_ref_find_elt(ref, key) != NULL)
1338 pat_ref_set(ref, key, value, NULL);
1339 else
1340 pat_ref_add(ref, key, value, NULL);
1341 return 0;
1342}
1343
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001344/* A class is a lot of memory that contain data. This data can be a table,
1345 * an integer or user data. This data is associated with a metatable. This
1346 * metatable have an original version registred in the global context with
1347 * the name of the object (_G[<name>] = <metable> ).
1348 *
1349 * A metable is a table that modify the standard behavior of a standard
1350 * access to the associated data. The entries of this new metatable are
1351 * defined as is:
1352 *
1353 * http://lua-users.org/wiki/MetatableEvents
1354 *
1355 * __index
1356 *
1357 * we access an absent field in a table, the result is nil. This is
1358 * true, but it is not the whole truth. Actually, such access triggers
1359 * the interpreter to look for an __index metamethod: If there is no
1360 * such method, as usually happens, then the access results in nil;
1361 * otherwise, the metamethod will provide the result.
1362 *
1363 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1364 * the key does not appear in the table, but the metatable has an __index
1365 * property:
1366 *
1367 * - if the value is a function, the function is called, passing in the
1368 * table and the key; the return value of that function is returned as
1369 * the result.
1370 *
1371 * - if the value is another table, the value of the key in that table is
1372 * asked for and returned (and if it doesn't exist in that table, but that
1373 * table's metatable has an __index property, then it continues on up)
1374 *
1375 * - Use "rawget(myTable,key)" to skip this metamethod.
1376 *
1377 * http://www.lua.org/pil/13.4.1.html
1378 *
1379 * __newindex
1380 *
1381 * Like __index, but control property assignment.
1382 *
1383 * __mode - Control weak references. A string value with one or both
1384 * of the characters 'k' and 'v' which specifies that the the
1385 * keys and/or values in the table are weak references.
1386 *
1387 * __call - Treat a table like a function. When a table is followed by
1388 * parenthesis such as "myTable( 'foo' )" and the metatable has
1389 * a __call key pointing to a function, that function is invoked
1390 * (passing any specified arguments) and the return value is
1391 * returned.
1392 *
1393 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1394 * called, if the metatable for myTable has a __metatable
1395 * key, the value of that key is returned instead of the
1396 * actual metatable.
1397 *
1398 * __tostring - Control string representation. When the builtin
1399 * "tostring( myTable )" function is called, if the metatable
1400 * for myTable has a __tostring property set to a function,
1401 * that function is invoked (passing myTable to it) and the
1402 * return value is used as the string representation.
1403 *
1404 * __len - Control table length. When the table length is requested using
1405 * the length operator ( '#' ), if the metatable for myTable has
1406 * a __len key pointing to a function, that function is invoked
1407 * (passing myTable to it) and the return value used as the value
1408 * of "#myTable".
1409 *
1410 * __gc - Userdata finalizer code. When userdata is set to be garbage
1411 * collected, if the metatable has a __gc field pointing to a
1412 * function, that function is first invoked, passing the userdata
1413 * to it. The __gc metamethod is not called for tables.
1414 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1415 *
1416 * Special metamethods for redefining standard operators:
1417 * http://www.lua.org/pil/13.1.html
1418 *
1419 * __add "+"
1420 * __sub "-"
1421 * __mul "*"
1422 * __div "/"
1423 * __unm "!"
1424 * __pow "^"
1425 * __concat ".."
1426 *
1427 * Special methods for redfining standar relations
1428 * http://www.lua.org/pil/13.2.html
1429 *
1430 * __eq "=="
1431 * __lt "<"
1432 * __le "<="
1433 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001434
1435/*
1436 *
1437 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001438 * Class Map
1439 *
1440 *
1441 */
1442
1443/* Returns a struct hlua_map if the stack entry "ud" is
1444 * a class session, otherwise it throws an error.
1445 */
1446__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1447{
1448 return (struct map_descriptor *)MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
1449}
1450
1451/* This function is the map constructor. It don't need
1452 * the class Map object. It creates and return a new Map
1453 * object. It must be called only during "body" or "init"
1454 * context because it process some filesystem accesses.
1455 */
1456__LJMP static int hlua_map_new(struct lua_State *L)
1457{
1458 const char *fn;
1459 int match = PAT_MATCH_STR;
1460 struct sample_conv conv;
1461 const char *file = "";
1462 int line = 0;
1463 lua_Debug ar;
1464 char *err = NULL;
1465 struct arg args[2];
1466
1467 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1468 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1469
1470 fn = MAY_LJMP(luaL_checkstring(L, 1));
1471
1472 if (lua_gettop(L) >= 2) {
1473 match = MAY_LJMP(luaL_checkinteger(L, 2));
1474 if (match < 0 || match >= PAT_MATCH_NUM)
1475 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1476 }
1477
1478 /* Get Lua filename and line number. */
1479 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1480 lua_getinfo(L, "Sl", &ar); /* get info about it */
1481 if (ar.currentline > 0) { /* is there info? */
1482 file = ar.short_src;
1483 line = ar.currentline;
1484 }
1485 }
1486
1487 /* fill fake sample_conv struct. */
1488 conv.kw = ""; /* unused. */
1489 conv.process = NULL; /* unused. */
1490 conv.arg_mask = 0; /* unused. */
1491 conv.val_args = NULL; /* unused. */
1492 conv.out_type = SMP_T_STR;
1493 conv.private = (void *)(long)match;
1494 switch (match) {
1495 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1496 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1497 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1498 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1499 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1500 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1501 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001502 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001503 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1504 default:
1505 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1506 }
1507
1508 /* fill fake args. */
1509 args[0].type = ARGT_STR;
1510 args[0].data.str.str = (char *)fn;
1511 args[1].type = ARGT_STOP;
1512
1513 /* load the map. */
1514 if (!sample_load_map(args, &conv, file, line, &err)) {
1515 /* error case: we cant use luaL_error because we must
1516 * free the err variable.
1517 */
1518 luaL_where(L, 1);
1519 lua_pushfstring(L, "'new': %s.", err);
1520 lua_concat(L, 2);
1521 free(err);
1522 WILL_LJMP(lua_error(L));
1523 }
1524
1525 /* create the lua object. */
1526 lua_newtable(L);
1527 lua_pushlightuserdata(L, args[0].data.map);
1528 lua_rawseti(L, -2, 0);
1529
1530 /* Pop a class Map metatable and affect it to the userdata. */
1531 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1532 lua_setmetatable(L, -2);
1533
1534
1535 return 1;
1536}
1537
1538__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1539{
1540 struct map_descriptor *desc;
1541 struct pattern *pat;
1542 struct sample smp;
1543
1544 MAY_LJMP(check_args(L, 2, "lookup"));
1545 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001546 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001547 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001548 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001549 }
1550 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001551 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001552 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001553 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 +02001554 }
1555
1556 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001557 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001558 if (str)
1559 lua_pushstring(L, "");
1560 else
1561 lua_pushnil(L);
1562 return 1;
1563 }
1564
1565 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001566 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001567 return 1;
1568}
1569
1570__LJMP static int hlua_map_lookup(struct lua_State *L)
1571{
1572 return _hlua_map_lookup(L, 0);
1573}
1574
1575__LJMP static int hlua_map_slookup(struct lua_State *L)
1576{
1577 return _hlua_map_lookup(L, 1);
1578}
1579
1580/*
1581 *
1582 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001583 * Class Socket
1584 *
1585 *
1586 */
1587
1588__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1589{
1590 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1591}
1592
1593/* This function is the handler called for each I/O on the established
1594 * connection. It is used for notify space avalaible to send or data
1595 * received.
1596 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001597static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001598{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001599 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001600 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001601
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001602 /* If the connection object is not avalaible, close all the
1603 * streams and wakeup everithing waiting for.
1604 */
1605 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001606 si_shutw(si);
1607 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001608 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001609 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1610 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001611 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001612 }
1613
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001614 /* If we cant write, wakeup the pending write signals. */
1615 if (channel_output_closed(si_ic(si)))
1616 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1617
1618 /* If we cant read, wakeup the pending read signals. */
1619 if (channel_input_closed(si_oc(si)))
1620 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1621
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001622 /* if the connection is not estabkished, inform the stream that we want
1623 * to be notified whenever the connection completes.
1624 */
1625 if (!(c->flags & CO_FL_CONNECTED)) {
1626 si_applet_cant_get(si);
1627 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001628 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001629 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001630
1631 /* This function is called after the connect. */
1632 appctx->ctx.hlua.connected = 1;
1633
1634 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001635 if (channel_may_recv(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001636 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1637
1638 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001639 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001640 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1641}
1642
Willy Tarreau87b09662015-04-03 00:22:06 +02001643/* This function is called when the "struct stream" is destroyed.
1644 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001645 * Wake all the pending signals.
1646 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001647static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001648{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001649 /* Remove my link in the original object. */
1650 if (appctx->ctx.hlua.socket)
1651 appctx->ctx.hlua.socket->s = NULL;
1652
1653 /* Wake all the task waiting for me. */
1654 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1655 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1656}
1657
1658/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001659 * uses this object. If the stream does not exists, just quit.
1660 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001661 * pending signal can rest in the read and write lists. destroy
1662 * it.
1663 */
1664__LJMP static int hlua_socket_gc(lua_State *L)
1665{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001666 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001667 struct appctx *appctx;
1668
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001669 MAY_LJMP(check_args(L, 1, "__gc"));
1670
1671 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001672 if (!socket->s)
1673 return 0;
1674
Willy Tarreau87b09662015-04-03 00:22:06 +02001675 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001676 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001677 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001678 socket->s = NULL;
1679 appctx->ctx.hlua.socket = NULL;
1680
1681 return 0;
1682}
1683
1684/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001685 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001686 */
1687__LJMP static int hlua_socket_close(lua_State *L)
1688{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001689 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001690 struct appctx *appctx;
1691
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001692 MAY_LJMP(check_args(L, 1, "close"));
1693
1694 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001695 if (!socket->s)
1696 return 0;
1697
Willy Tarreau87b09662015-04-03 00:22:06 +02001698 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001699 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001700 appctx = objt_appctx(socket->s->si[0].end);
1701 appctx->ctx.hlua.socket = NULL;
1702 socket->s = NULL;
1703
1704 return 0;
1705}
1706
1707/* This Lua function assumes that the stack contain three parameters.
1708 * 1 - USERDATA containing a struct socket
1709 * 2 - INTEGER with values of the macro defined below
1710 * If the integer is -1, we must read at most one line.
1711 * If the integer is -2, we ust read all the data until the
1712 * end of the stream.
1713 * If the integer is positive value, we must read a number of
1714 * bytes corresponding to this value.
1715 */
1716#define HLSR_READ_LINE (-1)
1717#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001718__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001719{
1720 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1721 int wanted = lua_tointeger(L, 2);
1722 struct hlua *hlua = hlua_gethlua(L);
1723 struct appctx *appctx;
1724 int len;
1725 int nblk;
1726 char *blk1;
1727 int len1;
1728 char *blk2;
1729 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001730 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001731 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001732
1733 /* Check if this lua stack is schedulable. */
1734 if (!hlua || !hlua->task)
1735 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1736 "'frontend', 'backend' or 'task'"));
1737
1738 /* check for connection closed. If some data where read, return it. */
1739 if (!socket->s)
1740 goto connection_closed;
1741
Willy Tarreau94aa6172015-03-13 14:19:06 +01001742 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001743 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001744 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001745 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001746 if (nblk < 0) /* Connection close. */
1747 goto connection_closed;
1748 if (nblk == 0) /* No data avalaible. */
1749 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001750
1751 /* remove final \r\n. */
1752 if (nblk == 1) {
1753 if (blk1[len1-1] == '\n') {
1754 len1--;
1755 skip_at_end++;
1756 if (blk1[len1-1] == '\r') {
1757 len1--;
1758 skip_at_end++;
1759 }
1760 }
1761 }
1762 else {
1763 if (blk2[len2-1] == '\n') {
1764 len2--;
1765 skip_at_end++;
1766 if (blk2[len2-1] == '\r') {
1767 len2--;
1768 skip_at_end++;
1769 }
1770 }
1771 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001772 }
1773
1774 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001775 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001776 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001777 if (nblk < 0) /* Connection close. */
1778 goto connection_closed;
1779 if (nblk == 0) /* No data avalaible. */
1780 goto connection_empty;
1781 }
1782
1783 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001784 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001785 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001786 if (nblk < 0) /* Connection close. */
1787 goto connection_closed;
1788 if (nblk == 0) /* No data avalaible. */
1789 goto connection_empty;
1790
1791 if (len1 > wanted) {
1792 nblk = 1;
1793 len1 = wanted;
1794 } if (nblk == 2 && len1 + len2 > wanted)
1795 len2 = wanted - len1;
1796 }
1797
1798 len = len1;
1799
1800 luaL_addlstring(&socket->b, blk1, len1);
1801 if (nblk == 2) {
1802 len += len2;
1803 luaL_addlstring(&socket->b, blk2, len2);
1804 }
1805
1806 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001807 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001808
1809 /* Don't wait anything. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001810 stream_int_notify(&socket->s->si[0]);
1811 stream_int_update_applet(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001812
1813 /* If the pattern reclaim to read all the data
1814 * in the connection, got out.
1815 */
1816 if (wanted == HLSR_READ_ALL)
1817 goto connection_empty;
1818 else if (wanted >= 0 && len < wanted)
1819 goto connection_empty;
1820
1821 /* Return result. */
1822 luaL_pushresult(&socket->b);
1823 return 1;
1824
1825connection_closed:
1826
1827 /* If the buffer containds data. */
1828 if (socket->b.n > 0) {
1829 luaL_pushresult(&socket->b);
1830 return 1;
1831 }
1832 lua_pushnil(L);
1833 lua_pushstring(L, "connection closed.");
1834 return 2;
1835
1836connection_empty:
1837
1838 appctx = objt_appctx(socket->s->si[0].end);
1839 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1840 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001841 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001842 return 0;
1843}
1844
1845/* This Lus function gets two parameters. The first one can be string
1846 * or a number. If the string is "*l", the user require one line. If
1847 * the string is "*a", the user require all the content of the stream.
1848 * If the value is a number, the user require a number of bytes equal
1849 * to the value. The default value is "*l" (a line).
1850 *
1851 * This paraeter with a variable type is converted in integer. This
1852 * integer takes this values:
1853 * -1 : read a line
1854 * -2 : read all the stream
1855 * >0 : amount if bytes.
1856 *
1857 * The second parameter is optinal. It contains a string that must be
1858 * concatenated with the read data.
1859 */
1860__LJMP static int hlua_socket_receive(struct lua_State *L)
1861{
1862 int wanted = HLSR_READ_LINE;
1863 const char *pattern;
1864 int type;
1865 char *error;
1866 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001867 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001868
1869 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1870 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1871
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001872 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001873
1874 /* check for pattern. */
1875 if (lua_gettop(L) >= 2) {
1876 type = lua_type(L, 2);
1877 if (type == LUA_TSTRING) {
1878 pattern = lua_tostring(L, 2);
1879 if (strcmp(pattern, "*a") == 0)
1880 wanted = HLSR_READ_ALL;
1881 else if (strcmp(pattern, "*l") == 0)
1882 wanted = HLSR_READ_LINE;
1883 else {
1884 wanted = strtoll(pattern, &error, 10);
1885 if (*error != '\0')
1886 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1887 }
1888 }
1889 else if (type == LUA_TNUMBER) {
1890 wanted = lua_tointeger(L, 2);
1891 if (wanted < 0)
1892 WILL_LJMP(luaL_error(L, "Unsupported size."));
1893 }
1894 }
1895
1896 /* Set pattern. */
1897 lua_pushinteger(L, wanted);
1898 lua_replace(L, 2);
1899
1900 /* init bufffer, and fiil it wih prefix. */
1901 luaL_buffinit(L, &socket->b);
1902
1903 /* Check prefix. */
1904 if (lua_gettop(L) >= 3) {
1905 if (lua_type(L, 3) != LUA_TSTRING)
1906 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1907 pattern = lua_tolstring(L, 3, &len);
1908 luaL_addlstring(&socket->b, pattern, len);
1909 }
1910
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001911 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001912}
1913
1914/* Write the Lua input string in the output buffer.
1915 * This fucntion returns a yield if no space are available.
1916 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001917static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001918{
1919 struct hlua_socket *socket;
1920 struct hlua *hlua = hlua_gethlua(L);
1921 struct appctx *appctx;
1922 size_t buf_len;
1923 const char *buf;
1924 int len;
1925 int send_len;
1926 int sent;
1927
1928 /* Check if this lua stack is schedulable. */
1929 if (!hlua || !hlua->task)
1930 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1931 "'frontend', 'backend' or 'task'"));
1932
1933 /* Get object */
1934 socket = MAY_LJMP(hlua_checksocket(L, 1));
1935 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001936 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001937
1938 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001939 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001940 lua_pushinteger(L, -1);
1941 return 1;
1942 }
1943
1944 /* Update the input buffer data. */
1945 buf += sent;
1946 send_len = buf_len - sent;
1947
1948 /* All the data are sent. */
1949 if (sent >= buf_len)
1950 return 1; /* Implicitly return the length sent. */
1951
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001952 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1953 * the request buffer if its not required.
1954 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001955 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001956 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001957 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001958 goto hlua_socket_write_yield_return;
1959 }
1960 }
1961
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001962 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001963 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001964 if (len <= 0)
1965 goto hlua_socket_write_yield_return;
1966
1967 /* send data */
1968 if (len < send_len)
1969 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001970 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001971
1972 /* "Not enough space" (-1), "Buffer too little to contain
1973 * the data" (-2) are not expected because the available length
1974 * is tested.
1975 * Other unknown error are also not expected.
1976 */
1977 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001978 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001979 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001980
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001981 MAY_LJMP(hlua_socket_close(L));
1982 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001983 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001984 return 1;
1985 }
1986
1987 /* update buffers. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001988 stream_int_notify(&socket->s->si[0]);
1989 stream_int_update_applet(&socket->s->si[0]);
1990
Willy Tarreau94aa6172015-03-13 14:19:06 +01001991 socket->s->req.rex = TICK_ETERNITY;
1992 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001993
1994 /* Update length sent. */
1995 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001996 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001997
1998 /* All the data buffer is sent ? */
1999 if (sent + len >= buf_len)
2000 return 1;
2001
2002hlua_socket_write_yield_return:
2003 appctx = objt_appctx(socket->s->si[0].end);
2004 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2005 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002006 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002007 return 0;
2008}
2009
2010/* This function initiate the send of data. It just check the input
2011 * parameters and push an integer in the Lua stack that contain the
2012 * amount of data writed in the buffer. This is used by the function
2013 * "hlua_socket_write_yield" that can yield.
2014 *
2015 * The Lua function gets between 3 and 4 parameters. The first one is
2016 * the associated object. The second is a string buffer. The third is
2017 * a facultative integer that represents where is the buffer position
2018 * of the start of the data that can send. The first byte is the
2019 * position "1". The default value is "1". The fourth argument is a
2020 * facultative integer that represents where is the buffer position
2021 * of the end of the data that can send. The default is the last byte.
2022 */
2023static int hlua_socket_send(struct lua_State *L)
2024{
2025 int i;
2026 int j;
2027 const char *buf;
2028 size_t buf_len;
2029
2030 /* Check number of arguments. */
2031 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2032 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2033
2034 /* Get the string. */
2035 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2036
2037 /* Get and check j. */
2038 if (lua_gettop(L) == 4) {
2039 j = MAY_LJMP(luaL_checkinteger(L, 4));
2040 if (j < 0)
2041 j = buf_len + j + 1;
2042 if (j > buf_len)
2043 j = buf_len + 1;
2044 lua_pop(L, 1);
2045 }
2046 else
2047 j = buf_len;
2048
2049 /* Get and check i. */
2050 if (lua_gettop(L) == 3) {
2051 i = MAY_LJMP(luaL_checkinteger(L, 3));
2052 if (i < 0)
2053 i = buf_len + i + 1;
2054 if (i > buf_len)
2055 i = buf_len + 1;
2056 lua_pop(L, 1);
2057 } else
2058 i = 1;
2059
2060 /* Check bth i and j. */
2061 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002062 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002063 return 1;
2064 }
2065 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002066 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002067 return 1;
2068 }
2069 if (i == 0)
2070 i = 1;
2071 if (j == 0)
2072 j = 1;
2073
2074 /* Pop the string. */
2075 lua_pop(L, 1);
2076
2077 /* Update the buffer length. */
2078 buf += i - 1;
2079 buf_len = j - i + 1;
2080 lua_pushlstring(L, buf, buf_len);
2081
2082 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002083 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002084
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002085 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002086}
2087
Willy Tarreau22b0a682015-06-17 19:43:49 +02002088#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002089__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2090{
2091 static char buffer[SOCKET_INFO_MAX_LEN];
2092 int ret;
2093 int len;
2094 char *p;
2095
2096 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2097 if (ret <= 0) {
2098 lua_pushnil(L);
2099 return 1;
2100 }
2101
2102 if (ret == AF_UNIX) {
2103 lua_pushstring(L, buffer+1);
2104 return 1;
2105 }
2106 else if (ret == AF_INET6) {
2107 buffer[0] = '[';
2108 len = strlen(buffer);
2109 buffer[len] = ']';
2110 len++;
2111 buffer[len] = ':';
2112 len++;
2113 p = buffer;
2114 }
2115 else if (ret == AF_INET) {
2116 p = buffer + 1;
2117 len = strlen(p);
2118 p[len] = ':';
2119 len++;
2120 }
2121 else {
2122 lua_pushnil(L);
2123 return 1;
2124 }
2125
2126 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2127 lua_pushnil(L);
2128 return 1;
2129 }
2130
2131 lua_pushstring(L, p);
2132 return 1;
2133}
2134
2135/* Returns information about the peer of the connection. */
2136__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2137{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002138 struct hlua_socket *socket;
2139 struct connection *conn;
2140
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002141 MAY_LJMP(check_args(L, 1, "getpeername"));
2142
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002143 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002144
2145 /* Check if the tcp object is avalaible. */
2146 if (!socket->s) {
2147 lua_pushnil(L);
2148 return 1;
2149 }
2150
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002151 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002152 if (!conn) {
2153 lua_pushnil(L);
2154 return 1;
2155 }
2156
2157 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
2158 unsigned int salen = sizeof(conn->addr.to);
2159 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
2160 lua_pushnil(L);
2161 return 1;
2162 }
2163 conn->flags |= CO_FL_ADDR_TO_SET;
2164 }
2165
2166 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2167}
2168
2169/* Returns information about my connection side. */
2170static int hlua_socket_getsockname(struct lua_State *L)
2171{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002172 struct hlua_socket *socket;
2173 struct connection *conn;
2174
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002175 MAY_LJMP(check_args(L, 1, "getsockname"));
2176
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002177 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002178
2179 /* Check if the tcp object is avalaible. */
2180 if (!socket->s) {
2181 lua_pushnil(L);
2182 return 1;
2183 }
2184
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002185 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186 if (!conn) {
2187 lua_pushnil(L);
2188 return 1;
2189 }
2190
2191 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2192 unsigned int salen = sizeof(conn->addr.from);
2193 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2194 lua_pushnil(L);
2195 return 1;
2196 }
2197 conn->flags |= CO_FL_ADDR_FROM_SET;
2198 }
2199
2200 return hlua_socket_info(L, &conn->addr.from);
2201}
2202
2203/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002204static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002205 .obj_type = OBJ_TYPE_APPLET,
2206 .name = "<LUA_TCP>",
2207 .fct = hlua_socket_handler,
2208 .release = hlua_socket_release,
2209};
2210
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002211__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002212{
2213 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2214 struct hlua *hlua = hlua_gethlua(L);
2215 struct appctx *appctx;
2216
2217 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002218 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002219 lua_pushnil(L);
2220 lua_pushstring(L, "Can't connect");
2221 return 2;
2222 }
2223
2224 appctx = objt_appctx(socket->s->si[0].end);
2225
2226 /* Check for connection established. */
2227 if (appctx->ctx.hlua.connected) {
2228 lua_pushinteger(L, 1);
2229 return 1;
2230 }
2231
2232 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2233 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002234 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002235 return 0;
2236}
2237
2238/* This function fail or initite the connection. */
2239__LJMP static int hlua_socket_connect(struct lua_State *L)
2240{
2241 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002242 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002243 const char *ip;
2244 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002245 struct hlua *hlua;
2246 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002247 int low, high;
2248 struct sockaddr_storage *addr;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002249
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002250 if (lua_gettop(L) < 2)
2251 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002252
2253 /* Get args. */
2254 socket = MAY_LJMP(hlua_checksocket(L, 1));
2255 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002256 if (lua_gettop(L) >= 3)
2257 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002258
Willy Tarreau973a5422015-08-05 21:47:23 +02002259 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002260 if (!conn)
2261 WILL_LJMP(luaL_error(L, "connect: internal error"));
2262
Willy Tarreau3adac082015-09-26 17:51:09 +02002263 /* needed for the connection not to be closed */
2264 conn->target = socket->s->target;
2265
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002266 /* Parse ip address. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002267 addr = str2sa_range(ip, &low, &high, NULL, NULL, NULL, 0);
2268 if (!addr)
2269 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
2270 if (low != high)
2271 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
2272 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002273
2274 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002275 if (low == 0) {
2276 if (conn->addr.to.ss_family == AF_INET) {
2277 if (port == -1)
2278 WILL_LJMP(luaL_error(L, "connect: port missing"));
2279 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2280 } else if (conn->addr.to.ss_family == AF_INET6) {
2281 if (port == -1)
2282 WILL_LJMP(luaL_error(L, "connect: port missing"));
2283 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2284 }
2285 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002286
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002287 hlua = hlua_gethlua(L);
2288 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002289
2290 /* inform the stream that we want to be notified whenever the
2291 * connection completes.
2292 */
2293 si_applet_cant_get(&socket->s->si[0]);
2294 si_applet_cant_put(&socket->s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002295 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002296
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002297 hlua->flags |= HLUA_MUST_GC;
2298
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002299 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2300 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002301 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002302
2303 return 0;
2304}
2305
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002306#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002307__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2308{
2309 struct hlua_socket *socket;
2310
2311 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2312 socket = MAY_LJMP(hlua_checksocket(L, 1));
2313 socket->s->target = &socket_ssl.obj_type;
2314 return MAY_LJMP(hlua_socket_connect(L));
2315}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002316#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002317
2318__LJMP static int hlua_socket_setoption(struct lua_State *L)
2319{
2320 return 0;
2321}
2322
2323__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2324{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002325 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002326 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002327
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002328 MAY_LJMP(check_args(L, 2, "settimeout"));
2329
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002330 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002331 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002332
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002333 socket->s->req.rto = tmout;
2334 socket->s->req.wto = tmout;
2335 socket->s->res.rto = tmout;
2336 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002337
2338 return 0;
2339}
2340
2341__LJMP static int hlua_socket_new(lua_State *L)
2342{
2343 struct hlua_socket *socket;
2344 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002345 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002346 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002347 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002348
2349 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002350 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002351 hlua_pusherror(L, "socket: full stack");
2352 goto out_fail_conf;
2353 }
2354
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002355 /* Create the object: obj[0] = userdata. */
2356 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002357 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002358 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002359 memset(socket, 0, sizeof(*socket));
2360
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002361 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002362 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002363 hlua_pusherror(L, "socket: uninitialized pools.");
2364 goto out_fail_conf;
2365 }
2366
Willy Tarreau87b09662015-04-03 00:22:06 +02002367 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002368 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2369 lua_setmetatable(L, -2);
2370
Willy Tarreaud420a972015-04-06 00:39:18 +02002371 /* Create the applet context */
2372 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002373 if (!appctx) {
2374 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002375 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002376 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002377
Willy Tarreaud420a972015-04-06 00:39:18 +02002378 appctx->ctx.hlua.socket = socket;
2379 appctx->ctx.hlua.connected = 0;
2380 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2381 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002382
Willy Tarreaud420a972015-04-06 00:39:18 +02002383 /* Now create a session, task and stream for this applet */
2384 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2385 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002386 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002387 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002388 }
2389
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002390 task = task_new();
2391 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002392 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002393 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002394 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002395 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002396
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002397 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002398 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002399 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002400 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002401 }
2402
Willy Tarreaud420a972015-04-06 00:39:18 +02002403 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002404 socket->s = strm;
2405 strm->hlua.T = NULL;
2406 strm->hlua.Tref = LUA_REFNIL;
2407 strm->hlua.Mref = LUA_REFNIL;
2408 strm->hlua.nargs = 0;
2409 strm->hlua.flags = 0;
2410 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002411
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002412 /* Configure "right" stream interface. this "si" is used to connect
2413 * and retrieve data from the server. The connection is initialized
2414 * with the "struct server".
2415 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002416 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002417
2418 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002419 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2420 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002421
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002422 /* Update statistics counters. */
2423 socket_proxy.feconn++; /* beconn will be increased later */
2424 jobs++;
2425 totalconn++;
2426
2427 /* Return yield waiting for connection. */
2428 return 1;
2429
Willy Tarreaud420a972015-04-06 00:39:18 +02002430 out_fail_stream:
2431 task_free(task);
2432 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002433 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002434 out_fail_sess:
2435 appctx_free(appctx);
2436 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002437 WILL_LJMP(lua_error(L));
2438 return 0;
2439}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002440
2441/*
2442 *
2443 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002444 * Class Channel
2445 *
2446 *
2447 */
2448
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002449/* The state between the channel data and the HTTP parser state can be
2450 * unconsistent, so reset the parser and call it again. Warning, this
2451 * action not revalidate the request and not send a 400 if the modified
2452 * resuest is not valid.
2453 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002454 * This function never fails. The direction is set using dir, which equals
2455 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002456 */
2457static void hlua_resynchonize_proto(struct stream *stream, int dir)
2458{
2459 /* Protocol HTTP. */
2460 if (stream->be->mode == PR_MODE_HTTP) {
2461
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002462 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002463 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002464 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002465 http_txn_reset_res(stream->txn);
2466
2467 if (stream->txn->hdr_idx.v)
2468 hdr_idx_init(&stream->txn->hdr_idx);
2469
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002470 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002471 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002472 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002473 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2474 }
2475}
2476
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002477/* Check the protocole integrity after the Lua manipulations. Close the stream
2478 * and returns 0 if fails, otherwise returns 1. The direction is set using dir,
2479 * which equals either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002480 */
2481static int hlua_check_proto(struct stream *stream, int dir)
2482{
2483 const struct chunk msg = { .len = 0 };
2484
Willy Tarreau9af89f72015-09-26 11:50:08 +02002485 /* Protocol HTTP. The message parsing state must match the request or
2486 * response state. The problem that may happen is that Lua modifies
2487 * the request or response message *after* it was parsed, and corrupted
2488 * it so that it could not be processed anymore. We just need to verify
2489 * if the parser is still expected to run or not.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002490 */
2491 if (stream->be->mode == PR_MODE_HTTP) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002492 if (dir == SMP_OPT_DIR_REQ &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002493 !(stream->req.analysers & AN_REQ_WAIT_HTTP) &&
2494 stream->txn->req.msg_state < HTTP_MSG_BODY) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002495 stream_int_retnclose(&stream->si[0], &msg);
2496 return 0;
2497 }
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002498 else if (dir == SMP_OPT_DIR_RES &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002499 !(stream->res.analysers & AN_RES_WAIT_HTTP) &&
2500 stream->txn->rsp.msg_state < HTTP_MSG_BODY) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002501 stream_int_retnclose(&stream->si[0], &msg);
2502 return 0;
2503 }
2504 }
2505 return 1;
2506}
2507
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002508/* Returns the struct hlua_channel join to the class channel in the
2509 * stack entry "ud" or throws an argument error.
2510 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002511__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002512{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002513 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002514}
2515
Willy Tarreau47860ed2015-03-10 14:07:50 +01002516/* Pushes the channel onto the top of the stack. If the stask does not have a
2517 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002518 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002519static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002520{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002521 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002522 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002523 return 0;
2524
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002525 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002526 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002527 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002528
2529 /* Pop a class sesison metatable and affect it to the userdata. */
2530 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2531 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002532 return 1;
2533}
2534
2535/* Duplicate all the data present in the input channel and put it
2536 * in a string LUA variables. Returns -1 and push a nil value in
2537 * the stack if the channel is closed and all the data are consumed,
2538 * returns 0 if no data are available, otherwise it returns the length
2539 * of the builded string.
2540 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002541static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002542{
2543 char *blk1;
2544 char *blk2;
2545 int len1;
2546 int len2;
2547 int ret;
2548 luaL_Buffer b;
2549
Willy Tarreau47860ed2015-03-10 14:07:50 +01002550 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002551 if (unlikely(ret == 0))
2552 return 0;
2553
2554 if (unlikely(ret < 0)) {
2555 lua_pushnil(L);
2556 return -1;
2557 }
2558
2559 luaL_buffinit(L, &b);
2560 luaL_addlstring(&b, blk1, len1);
2561 if (unlikely(ret == 2))
2562 luaL_addlstring(&b, blk2, len2);
2563 luaL_pushresult(&b);
2564
2565 if (unlikely(ret == 2))
2566 return len1 + len2;
2567 return len1;
2568}
2569
2570/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2571 * a yield. This function keep the data in the buffer.
2572 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002573__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002574{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002575 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002576
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002577 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2578
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002579 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002580 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002581 return 1;
2582}
2583
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002584/* Check arguments for the function "hlua_channel_dup_yield". */
2585__LJMP static int hlua_channel_dup(lua_State *L)
2586{
2587 MAY_LJMP(check_args(L, 1, "dup"));
2588 MAY_LJMP(hlua_checkchannel(L, 1));
2589 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2590}
2591
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002592/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2593 * a yield. This function consumes the data in the buffer. It returns
2594 * a string containing the data or a nil pointer if no data are available
2595 * and the channel is closed.
2596 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002597__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002598{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002599 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002600 int ret;
2601
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002602 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002603
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002604 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002605 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002606 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002607
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002608 if (unlikely(ret == -1))
2609 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002610
Willy Tarreau47860ed2015-03-10 14:07:50 +01002611 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002612 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002613 return 1;
2614}
2615
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002616/* Check arguments for the fucntion "hlua_channel_get_yield". */
2617__LJMP static int hlua_channel_get(lua_State *L)
2618{
2619 MAY_LJMP(check_args(L, 1, "get"));
2620 MAY_LJMP(hlua_checkchannel(L, 1));
2621 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2622}
2623
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002624/* This functions consumes and returns one line. If the channel is closed,
2625 * and the last data does not contains a final '\n', the data are returned
2626 * without the final '\n'. When no more data are avalaible, it returns nil
2627 * value.
2628 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002629__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002630{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002631 char *blk1;
2632 char *blk2;
2633 int len1;
2634 int len2;
2635 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002636 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002637 int ret;
2638 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002639
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002640 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2641
Willy Tarreau47860ed2015-03-10 14:07:50 +01002642 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002643 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002644 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002645
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002646 if (ret == -1) {
2647 lua_pushnil(L);
2648 return 1;
2649 }
2650
2651 luaL_buffinit(L, &b);
2652 luaL_addlstring(&b, blk1, len1);
2653 len = len1;
2654 if (unlikely(ret == 2)) {
2655 luaL_addlstring(&b, blk2, len2);
2656 len += len2;
2657 }
2658 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002659 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002660 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002661 return 1;
2662}
2663
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002664/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2665__LJMP static int hlua_channel_getline(lua_State *L)
2666{
2667 MAY_LJMP(check_args(L, 1, "getline"));
2668 MAY_LJMP(hlua_checkchannel(L, 1));
2669 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2670}
2671
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002672/* This function takes a string as input, and append it at the
2673 * input side of channel. If the data is too big, but a space
2674 * is probably available after sending some data, the function
2675 * yield. If the data is bigger than the buffer, or if the
2676 * channel is closed, it returns -1. otherwise, it returns the
2677 * amount of data writed.
2678 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002679__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002680{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002681 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002682 size_t len;
2683 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2684 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2685 int ret;
2686 int max;
2687
Willy Tarreau47860ed2015-03-10 14:07:50 +01002688 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002689 if (max > len - l)
2690 max = len - l;
2691
Willy Tarreau47860ed2015-03-10 14:07:50 +01002692 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002693 if (ret == -2 || ret == -3) {
2694 lua_pushinteger(L, -1);
2695 return 1;
2696 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002697 if (ret == -1) {
2698 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002699 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002700 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002701 l += ret;
2702 lua_pop(L, 1);
2703 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002704 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002705
Willy Tarreau47860ed2015-03-10 14:07:50 +01002706 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2707 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002708 /* There are no space avalaible, and the output buffer is empty.
2709 * in this case, we cannot add more data, so we cannot yield,
2710 * we return the amount of copyied data.
2711 */
2712 return 1;
2713 }
2714 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002715 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002716 return 1;
2717}
2718
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002719/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002720 * of the writed string, or -1 if the channel is closed or if the
2721 * buffer size is too little for the data.
2722 */
2723__LJMP static int hlua_channel_append(lua_State *L)
2724{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002725 size_t len;
2726
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002727 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002728 MAY_LJMP(hlua_checkchannel(L, 1));
2729 MAY_LJMP(luaL_checklstring(L, 2, &len));
2730 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002731 lua_pushinteger(L, 0);
2732
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002733 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002734}
2735
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002736/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002737 * his process by cleaning the buffer. The result is a replacement
2738 * of the current data. It returns the length of the writed string,
2739 * or -1 if the channel is closed or if the buffer size is too
2740 * little for the data.
2741 */
2742__LJMP static int hlua_channel_set(lua_State *L)
2743{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002744 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002745
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002746 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002747 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002748 lua_pushinteger(L, 0);
2749
Willy Tarreau47860ed2015-03-10 14:07:50 +01002750 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002751
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002752 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002753}
2754
2755/* Append data in the output side of the buffer. This data is immediatly
2756 * sent. The fcuntion returns the ammount of data writed. If the buffer
2757 * cannot contains the data, the function yield. The function returns -1
2758 * if the channel is closed.
2759 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002760__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002761{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002762 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002763 size_t len;
2764 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2765 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2766 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002767 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002768
Willy Tarreau47860ed2015-03-10 14:07:50 +01002769 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002770 lua_pushinteger(L, -1);
2771 return 1;
2772 }
2773
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002774 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2775 * the request buffer if its not required.
2776 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002777 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002778 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002779 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002780 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002781 }
2782 }
2783
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002784 /* the writed data will be immediatly sent, so we can check
2785 * the avalaible space without taking in account the reserve.
2786 * The reserve is guaranted for the processing of incoming
2787 * data, because the buffer will be flushed.
2788 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002789 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002790
2791 /* If there are no space avalaible, and the output buffer is empty.
2792 * in this case, we cannot add more data, so we cannot yield,
2793 * we return the amount of copyied data.
2794 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002795 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002796 return 1;
2797
2798 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002799 if (max > len - l)
2800 max = len - l;
2801
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002802 /* The buffer avalaible size may be not contiguous. This test
2803 * detects a non contiguous buffer and realign it.
2804 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002805 if (bi_space_for_replace(chn->buf) < max)
2806 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002807
2808 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002809 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002810
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002811 /* buffer replace considers that the input part is filled.
2812 * so, I must forward these new data in the output part.
2813 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002814 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002815
2816 l += max;
2817 lua_pop(L, 1);
2818 lua_pushinteger(L, l);
2819
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002820 /* If there are no space avalaible, and the output buffer is empty.
2821 * in this case, we cannot add more data, so we cannot yield,
2822 * we return the amount of copyied data.
2823 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002824 max = chn->buf->size - buffer_len(chn->buf);
2825 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002826 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002827
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002828 if (l < len) {
2829 /* If we are waiting for space in the response buffer, we
2830 * must set the flag WAKERESWR. This flag required the task
2831 * wake up if any activity is detected on the response buffer.
2832 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002833 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002834 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002835 else
2836 HLUA_SET_WAKEREQWR(hlua);
2837 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002838 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002839
2840 return 1;
2841}
2842
2843/* Just a wraper of "_hlua_channel_send". This wrapper permits
2844 * yield the LUA process, and resume it without checking the
2845 * input arguments.
2846 */
2847__LJMP static int hlua_channel_send(lua_State *L)
2848{
2849 MAY_LJMP(check_args(L, 2, "send"));
2850 lua_pushinteger(L, 0);
2851
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002852 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002853}
2854
2855/* This function forward and amount of butes. The data pass from
2856 * the input side of the buffer to the output side, and can be
2857 * forwarded. This function never fails.
2858 *
2859 * The Lua function takes an amount of bytes to be forwarded in
2860 * imput. It returns the number of bytes forwarded.
2861 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002862__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002863{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002864 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002865 int len;
2866 int l;
2867 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002868 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002869
2870 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2871 len = MAY_LJMP(luaL_checkinteger(L, 2));
2872 l = MAY_LJMP(luaL_checkinteger(L, -1));
2873
2874 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002875 if (max > chn->buf->i)
2876 max = chn->buf->i;
2877 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002878 l += max;
2879
2880 lua_pop(L, 1);
2881 lua_pushinteger(L, l);
2882
2883 /* Check if it miss bytes to forward. */
2884 if (l < len) {
2885 /* The the input channel or the output channel are closed, we
2886 * must return the amount of data forwarded.
2887 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002888 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002889 return 1;
2890
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002891 /* If we are waiting for space data in the response buffer, we
2892 * must set the flag WAKERESWR. This flag required the task
2893 * wake up if any activity is detected on the response buffer.
2894 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002895 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002896 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002897 else
2898 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002899
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002900 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002901 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002902 }
2903
2904 return 1;
2905}
2906
2907/* Just check the input and prepare the stack for the previous
2908 * function "hlua_channel_forward_yield"
2909 */
2910__LJMP static int hlua_channel_forward(lua_State *L)
2911{
2912 MAY_LJMP(check_args(L, 2, "forward"));
2913 MAY_LJMP(hlua_checkchannel(L, 1));
2914 MAY_LJMP(luaL_checkinteger(L, 2));
2915
2916 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002917 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002918}
2919
2920/* Just returns the number of bytes available in the input
2921 * side of the buffer. This function never fails.
2922 */
2923__LJMP static int hlua_channel_get_in_len(lua_State *L)
2924{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002925 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002926
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002927 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002928 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002929 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002930 return 1;
2931}
2932
2933/* Just returns the number of bytes available in the output
2934 * side of the buffer. This function never fails.
2935 */
2936__LJMP static int hlua_channel_get_out_len(lua_State *L)
2937{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002938 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002939
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002940 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002941 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002942 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002943 return 1;
2944}
2945
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002946/*
2947 *
2948 *
2949 * Class Fetches
2950 *
2951 *
2952 */
2953
2954/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002955 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002956 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002957__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002958{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002959 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002960}
2961
2962/* This function creates and push in the stack a fetch object according
2963 * with a current TXN.
2964 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002965static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002966{
Willy Tarreau7073c472015-04-06 11:15:40 +02002967 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002968
2969 /* Check stack size. */
2970 if (!lua_checkstack(L, 3))
2971 return 0;
2972
2973 /* Create the object: obj[0] = userdata.
2974 * Note that the base of the Fetches object is the
2975 * transaction object.
2976 */
2977 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002978 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002979 lua_rawseti(L, -2, 0);
2980
Willy Tarreau7073c472015-04-06 11:15:40 +02002981 hsmp->s = txn->s;
2982 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01002983 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002984 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002985
2986 /* Pop a class sesison metatable and affect it to the userdata. */
2987 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2988 lua_setmetatable(L, -2);
2989
2990 return 1;
2991}
2992
2993/* This function is an LUA binding. It is called with each sample-fetch.
2994 * It uses closure argument to store the associated sample-fetch. It
2995 * returns only one argument or throws an error. An error is thrown
2996 * only if an error is encountered during the argument parsing. If
2997 * the "sample-fetch" function fails, nil is returned.
2998 */
2999__LJMP static int hlua_run_sample_fetch(lua_State *L)
3000{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003001 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003002 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003003 struct arg args[ARGM_NBARGS + 1];
3004 int i;
3005 struct sample smp;
3006
3007 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003008 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003009
3010 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003011 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003012
Thierry FOURNIERca988662015-12-20 18:43:03 +01003013 /* Check execution authorization. */
3014 if (f->use & SMP_USE_HTTP_ANY &&
3015 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3016 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3017 "is not available in Lua services", f->kw);
3018 WILL_LJMP(lua_error(L));
3019 }
3020
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003021 /* Get extra arguments. */
3022 for (i = 0; i < lua_gettop(L) - 1; i++) {
3023 if (i >= ARGM_NBARGS)
3024 break;
3025 hlua_lua2arg(L, i + 2, &args[i]);
3026 }
3027 args[i].type = ARGT_STOP;
3028
3029 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003030 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003031
3032 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003033 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003034 lua_pushfstring(L, "error in arguments");
3035 WILL_LJMP(lua_error(L));
3036 }
3037
3038 /* Initialise the sample. */
3039 memset(&smp, 0, sizeof(smp));
3040
3041 /* Run the sample fetch process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02003042 smp.px = hsmp->p;
3043 smp.sess = hsmp->s->sess;
3044 smp.strm = hsmp->s;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003045 smp.opt = hsmp->dir & SMP_OPT_DIR;
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003046 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003047 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003048 lua_pushstring(L, "");
3049 else
3050 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003051 return 1;
3052 }
3053
3054 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003055 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003056 hlua_smp2lua_str(L, &smp);
3057 else
3058 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003059 return 1;
3060}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003061
3062/*
3063 *
3064 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003065 * Class Converters
3066 *
3067 *
3068 */
3069
3070/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003071 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003072 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003073__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003074{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003075 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003076}
3077
3078/* This function creates and push in the stack a Converters object
3079 * according with a current TXN.
3080 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003081static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003082{
Willy Tarreau7073c472015-04-06 11:15:40 +02003083 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003084
3085 /* Check stack size. */
3086 if (!lua_checkstack(L, 3))
3087 return 0;
3088
3089 /* Create the object: obj[0] = userdata.
3090 * Note that the base of the Converters object is the
3091 * same than the TXN object.
3092 */
3093 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003094 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003095 lua_rawseti(L, -2, 0);
3096
Willy Tarreau7073c472015-04-06 11:15:40 +02003097 hsmp->s = txn->s;
3098 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003099 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003100 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003101
Willy Tarreau87b09662015-04-03 00:22:06 +02003102 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003103 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3104 lua_setmetatable(L, -2);
3105
3106 return 1;
3107}
3108
3109/* This function is an LUA binding. It is called with each converter.
3110 * It uses closure argument to store the associated converter. It
3111 * returns only one argument or throws an error. An error is thrown
3112 * only if an error is encountered during the argument parsing. If
3113 * the converter function function fails, nil is returned.
3114 */
3115__LJMP static int hlua_run_sample_conv(lua_State *L)
3116{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003117 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003118 struct sample_conv *conv;
3119 struct arg args[ARGM_NBARGS + 1];
3120 int i;
3121 struct sample smp;
3122
3123 /* Get closure arguments. */
3124 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
3125
3126 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003127 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003128
3129 /* Get extra arguments. */
3130 for (i = 0; i < lua_gettop(L) - 2; i++) {
3131 if (i >= ARGM_NBARGS)
3132 break;
3133 hlua_lua2arg(L, i + 3, &args[i]);
3134 }
3135 args[i].type = ARGT_STOP;
3136
3137 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003138 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003139
3140 /* Run the special args checker. */
3141 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3142 hlua_pusherror(L, "error in arguments");
3143 WILL_LJMP(lua_error(L));
3144 }
3145
3146 /* Initialise the sample. */
3147 if (!hlua_lua2smp(L, 2, &smp)) {
3148 hlua_pusherror(L, "error in the input argument");
3149 WILL_LJMP(lua_error(L));
3150 }
3151
3152 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003153 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003154 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003155 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003156 WILL_LJMP(lua_error(L));
3157 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003158 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3159 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003160 hlua_pusherror(L, "error during the input argument casting");
3161 WILL_LJMP(lua_error(L));
3162 }
3163
3164 /* Run the sample conversion process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02003165 smp.px = hsmp->p;
3166 smp.sess = hsmp->s->sess;
3167 smp.strm = hsmp->s;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003168 smp.opt = hsmp->dir & SMP_OPT_DIR;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003169 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003170 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003171 lua_pushstring(L, "");
3172 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003173 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003174 return 1;
3175 }
3176
3177 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003178 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003179 hlua_smp2lua_str(L, &smp);
3180 else
3181 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003182 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003183}
3184
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003185/*
3186 *
3187 *
3188 * Class AppletTCP
3189 *
3190 *
3191 */
3192
3193/* Returns a struct hlua_txn if the stack entry "ud" is
3194 * a class stream, otherwise it throws an error.
3195 */
3196__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3197{
3198 return (struct hlua_appctx *)MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
3199}
3200
3201/* This function creates and push in the stack an Applet object
3202 * according with a current TXN.
3203 */
3204static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3205{
3206 struct hlua_appctx *appctx;
3207 struct stream_interface *si = ctx->owner;
3208 struct stream *s = si_strm(si);
3209 struct proxy *p = s->be;
3210
3211 /* Check stack size. */
3212 if (!lua_checkstack(L, 3))
3213 return 0;
3214
3215 /* Create the object: obj[0] = userdata.
3216 * Note that the base of the Converters object is the
3217 * same than the TXN object.
3218 */
3219 lua_newtable(L);
3220 appctx = lua_newuserdata(L, sizeof(*appctx));
3221 lua_rawseti(L, -2, 0);
3222 appctx->appctx = ctx;
3223 appctx->htxn.s = s;
3224 appctx->htxn.p = p;
3225
3226 /* Create the "f" field that contains a list of fetches. */
3227 lua_pushstring(L, "f");
3228 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3229 return 0;
3230 lua_settable(L, -3);
3231
3232 /* Create the "sf" field that contains a list of stringsafe fetches. */
3233 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003234 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003235 return 0;
3236 lua_settable(L, -3);
3237
3238 /* Create the "c" field that contains a list of converters. */
3239 lua_pushstring(L, "c");
3240 if (!hlua_converters_new(L, &appctx->htxn, 0))
3241 return 0;
3242 lua_settable(L, -3);
3243
3244 /* Create the "sc" field that contains a list of stringsafe converters. */
3245 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003246 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003247 return 0;
3248 lua_settable(L, -3);
3249
3250 /* Pop a class stream metatable and affect it to the table. */
3251 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3252 lua_setmetatable(L, -2);
3253
3254 return 1;
3255}
3256
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003257__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3258{
3259 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3260 struct stream *s = appctx->htxn.s;
3261 struct hlua *hlua = &s->hlua;
3262
3263 MAY_LJMP(check_args(L, 2, "set_priv"));
3264
3265 /* Remove previous value. */
3266 if (hlua->Mref != -1)
3267 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3268
3269 /* Get and store new value. */
3270 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3271 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3272
3273 return 0;
3274}
3275
3276__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3277{
3278 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3279 struct stream *s = appctx->htxn.s;
3280 struct hlua *hlua = &s->hlua;
3281
3282 /* Push configuration index in the stack. */
3283 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3284
3285 return 1;
3286}
3287
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003288/* If expected data not yet available, it returns a yield. This function
3289 * consumes the data in the buffer. It returns a string containing the
3290 * data. This string can be empty.
3291 */
3292__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3293{
3294 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3295 struct stream_interface *si = appctx->appctx->owner;
3296 int ret;
3297 char *blk1;
3298 int len1;
3299 char *blk2;
3300 int len2;
3301
3302 /* Read the maximum amount of data avalaible. */
3303 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3304
3305 /* Data not yet avalaible. return yield. */
3306 if (ret == 0) {
3307 si_applet_cant_get(si);
3308 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3309 }
3310
3311 /* End of data: commit the total strings and return. */
3312 if (ret < 0) {
3313 luaL_pushresult(&appctx->b);
3314 return 1;
3315 }
3316
3317 /* Ensure that the block 2 length is usable. */
3318 if (ret == 1)
3319 len2 = 0;
3320
3321 /* dont check the max length read and dont check. */
3322 luaL_addlstring(&appctx->b, blk1, len1);
3323 luaL_addlstring(&appctx->b, blk2, len2);
3324
3325 /* Consume input channel output buffer data. */
3326 bo_skip(si_oc(si), len1 + len2);
3327 luaL_pushresult(&appctx->b);
3328 return 1;
3329}
3330
3331/* Check arguments for the fucntion "hlua_channel_get_yield". */
3332__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3333{
3334 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3335
3336 /* Initialise the string catenation. */
3337 luaL_buffinit(L, &appctx->b);
3338
3339 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3340}
3341
3342/* If expected data not yet available, it returns a yield. This function
3343 * consumes the data in the buffer. It returns a string containing the
3344 * data. This string can be empty.
3345 */
3346__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3347{
3348 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3349 struct stream_interface *si = appctx->appctx->owner;
3350 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3351 int ret;
3352 char *blk1;
3353 int len1;
3354 char *blk2;
3355 int len2;
3356
3357 /* Read the maximum amount of data avalaible. */
3358 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3359
3360 /* Data not yet avalaible. return yield. */
3361 if (ret == 0) {
3362 si_applet_cant_get(si);
3363 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3364 }
3365
3366 /* End of data: commit the total strings and return. */
3367 if (ret < 0) {
3368 luaL_pushresult(&appctx->b);
3369 return 1;
3370 }
3371
3372 /* Ensure that the block 2 length is usable. */
3373 if (ret == 1)
3374 len2 = 0;
3375
3376 if (len == -1) {
3377
3378 /* If len == -1, catenate all the data avalaile and
3379 * yield because we want to get all the data until
3380 * the end of data stream.
3381 */
3382 luaL_addlstring(&appctx->b, blk1, len1);
3383 luaL_addlstring(&appctx->b, blk2, len2);
3384 bo_skip(si_oc(si), len1 + len2);
3385 si_applet_cant_get(si);
3386 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3387
3388 } else {
3389
3390 /* Copy the fisrt block caping to the length required. */
3391 if (len1 > len)
3392 len1 = len;
3393 luaL_addlstring(&appctx->b, blk1, len1);
3394 len -= len1;
3395
3396 /* Copy the second block. */
3397 if (len2 > len)
3398 len2 = len;
3399 luaL_addlstring(&appctx->b, blk2, len2);
3400 len -= len2;
3401
3402 /* Consume input channel output buffer data. */
3403 bo_skip(si_oc(si), len1 + len2);
3404
3405 /* If we are no other data avalaible, yield waiting for new data. */
3406 if (len > 0) {
3407 lua_pushinteger(L, len);
3408 lua_replace(L, 2);
3409 si_applet_cant_get(si);
3410 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3411 }
3412
3413 /* return the result. */
3414 luaL_pushresult(&appctx->b);
3415 return 1;
3416 }
3417
3418 /* we never executes this */
3419 hlua_pusherror(L, "Lua: internal error");
3420 WILL_LJMP(lua_error(L));
3421 return 0;
3422}
3423
3424/* Check arguments for the fucntion "hlua_channel_get_yield". */
3425__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3426{
3427 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3428 int len = -1;
3429
3430 if (lua_gettop(L) > 2)
3431 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3432 if (lua_gettop(L) >= 2) {
3433 len = MAY_LJMP(luaL_checkinteger(L, 2));
3434 lua_pop(L, 1);
3435 }
3436
3437 /* Confirm or set the required length */
3438 lua_pushinteger(L, len);
3439
3440 /* Initialise the string catenation. */
3441 luaL_buffinit(L, &appctx->b);
3442
3443 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3444}
3445
3446/* Append data in the output side of the buffer. This data is immediatly
3447 * sent. The fcuntion returns the ammount of data writed. If the buffer
3448 * cannot contains the data, the function yield. The function returns -1
3449 * if the channel is closed.
3450 */
3451__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3452{
3453 size_t len;
3454 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3455 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3456 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3457 struct stream_interface *si = appctx->appctx->owner;
3458 struct channel *chn = si_ic(si);
3459 int max;
3460
3461 /* Get the max amount of data which can write as input in the channel. */
3462 max = channel_recv_max(chn);
3463 if (max > (len - l))
3464 max = len - l;
3465
3466 /* Copy data. */
3467 bi_putblk(chn, str + l, max);
3468
3469 /* update counters. */
3470 l += max;
3471 lua_pop(L, 1);
3472 lua_pushinteger(L, l);
3473
3474 /* If some data is not send, declares the situation to the
3475 * applet, and returns a yield.
3476 */
3477 if (l < len) {
3478 si_applet_cant_put(si);
3479 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3480 }
3481
3482 return 1;
3483}
3484
3485/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3486 * yield the LUA process, and resume it without checking the
3487 * input arguments.
3488 */
3489__LJMP static int hlua_applet_tcp_send(lua_State *L)
3490{
3491 MAY_LJMP(check_args(L, 2, "send"));
3492 lua_pushinteger(L, 0);
3493
3494 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3495}
3496
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003497/*
3498 *
3499 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003500 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003501 *
3502 *
3503 */
3504
3505/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003506 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003507 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003508__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003509{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003510 return (struct hlua_appctx *)MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003511}
3512
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003513/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003514 * according with a current TXN.
3515 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003516static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003517{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003518 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003519 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003520 struct stream_interface *si = ctx->owner;
3521 struct stream *s = si_strm(si);
3522 struct proxy *px = s->be;
3523 struct http_txn *txn = s->txn;
3524 const char *path;
3525 const char *end;
3526 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003527
3528 /* Check stack size. */
3529 if (!lua_checkstack(L, 3))
3530 return 0;
3531
3532 /* Create the object: obj[0] = userdata.
3533 * Note that the base of the Converters object is the
3534 * same than the TXN object.
3535 */
3536 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003537 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003538 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003539 appctx->appctx = ctx;
3540 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
3541 appctx->htxn.s = s;
3542 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003543
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003544 /* Create the "f" field that contains a list of fetches. */
3545 lua_pushstring(L, "f");
3546 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3547 return 0;
3548 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003549
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003550 /* Create the "sf" field that contains a list of stringsafe fetches. */
3551 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003552 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003553 return 0;
3554 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003555
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003556 /* Create the "c" field that contains a list of converters. */
3557 lua_pushstring(L, "c");
3558 if (!hlua_converters_new(L, &appctx->htxn, 0))
3559 return 0;
3560 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003561
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003562 /* Create the "sc" field that contains a list of stringsafe converters. */
3563 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003564 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003565 return 0;
3566 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003567
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003568 /* Stores the request method. */
3569 lua_pushstring(L, "method");
3570 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3571 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003572
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003573 /* Stores the http version. */
3574 lua_pushstring(L, "version");
3575 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3576 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003577
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003578 /* creates an array of headers. hlua_http_get_headers() crates and push
3579 * the array on the top of the stack.
3580 */
3581 lua_pushstring(L, "headers");
3582 htxn.s = s;
3583 htxn.p = px;
3584 htxn.dir = SMP_OPT_DIR_REQ;
3585 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3586 return 0;
3587 lua_settable(L, -3);
3588
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003589 /* Get path and qs */
3590 path = http_get_path(txn);
3591 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3592 p = path;
3593 while (p < end && *p != '?')
3594 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003595
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003596 /* Stores the request path. */
3597 lua_pushstring(L, "path");
3598 lua_pushlstring(L, path, p - path);
3599 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003600
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003601 /* Stores the query string. */
3602 lua_pushstring(L, "qs");
3603 if (*p == '?')
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003604 p++;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003605 lua_pushlstring(L, p, end - p);
3606 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003607
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003608 /* Stores the request path. */
3609 lua_pushstring(L, "length");
3610 lua_pushinteger(L, txn->req.body_len);
3611 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003612
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003613 /* Create an array of HTTP request headers. */
3614 lua_pushstring(L, "headers");
3615 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3616 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003617
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003618 /* Create an empty array of HTTP request headers. */
3619 lua_pushstring(L, "response");
3620 lua_newtable(L);
3621 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003622
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003623 /* Pop a class stream metatable and affect it to the table. */
3624 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3625 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003626
3627 return 1;
3628}
3629
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003630__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3631{
3632 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3633 struct stream *s = appctx->htxn.s;
3634 struct hlua *hlua = &s->hlua;
3635
3636 MAY_LJMP(check_args(L, 2, "set_priv"));
3637
3638 /* Remove previous value. */
3639 if (hlua->Mref != -1)
3640 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3641
3642 /* Get and store new value. */
3643 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3644 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3645
3646 return 0;
3647}
3648
3649__LJMP static int hlua_applet_http_get_priv(lua_State *L)
3650{
3651 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3652 struct stream *s = appctx->htxn.s;
3653 struct hlua *hlua = &s->hlua;
3654
3655 /* Push configuration index in the stack. */
3656 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3657
3658 return 1;
3659}
3660
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003661/* If expected data not yet available, it returns a yield. This function
3662 * consumes the data in the buffer. It returns a string containing the
3663 * data. This string can be empty.
3664 */
3665__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003666{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003667 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3668 struct stream_interface *si = appctx->appctx->owner;
3669 struct channel *chn = si_ic(si);
3670 int ret;
3671 char *blk1;
3672 int len1;
3673 char *blk2;
3674 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003675
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003676 /* Maybe we cant send a 100-continue ? */
3677 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3678 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3679 /* if ret == -2 or -3 the channel closed or the message si too
3680 * big for the buffers. We cant send anything. So, we ignoring
3681 * the error, considers that the 100-continue is sent, and try
3682 * to receive.
3683 * If ret is -1, we dont have room in the buffer, so we yield.
3684 */
3685 if (ret == -1) {
3686 si_applet_cant_put(si);
3687 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3688 }
3689 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3690 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003691
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003692 /* Check for the end of the data. */
3693 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3694 luaL_pushresult(&appctx->b);
3695 return 1;
3696 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003697
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003698 /* Read the maximum amount of data avalaible. */
3699 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003700
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003701 /* Data not yet avalaible. return yield. */
3702 if (ret == 0) {
3703 si_applet_cant_get(si);
3704 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3705 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003706
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003707 /* End of data: commit the total strings and return. */
3708 if (ret < 0) {
3709 luaL_pushresult(&appctx->b);
3710 return 1;
3711 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003712
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003713 /* Ensure that the block 2 length is usable. */
3714 if (ret == 1)
3715 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003716
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003717 /* Copy the fisrt block caping to the length required. */
3718 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3719 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3720 luaL_addlstring(&appctx->b, blk1, len1);
3721 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003722
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003723 /* Copy the second block. */
3724 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3725 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3726 luaL_addlstring(&appctx->b, blk2, len2);
3727 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003728
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003729 /* Consume input channel output buffer data. */
3730 bo_skip(si_oc(si), len1 + len2);
3731 luaL_pushresult(&appctx->b);
3732 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003733}
3734
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003735/* Check arguments for the fucntion "hlua_channel_get_yield". */
3736__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003737{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003738 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003739
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003740 /* Initialise the string catenation. */
3741 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003742
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003743 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003744}
3745
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003746/* If expected data not yet available, it returns a yield. This function
3747 * consumes the data in the buffer. It returns a string containing the
3748 * data. This string can be empty.
3749 */
3750__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003751{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003752 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3753 struct stream_interface *si = appctx->appctx->owner;
3754 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3755 struct channel *chn = si_ic(si);
3756 int ret;
3757 char *blk1;
3758 int len1;
3759 char *blk2;
3760 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003761
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003762 /* Maybe we cant send a 100-continue ? */
3763 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3764 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3765 /* if ret == -2 or -3 the channel closed or the message si too
3766 * big for the buffers. We cant send anything. So, we ignoring
3767 * the error, considers that the 100-continue is sent, and try
3768 * to receive.
3769 * If ret is -1, we dont have room in the buffer, so we yield.
3770 */
3771 if (ret == -1) {
3772 si_applet_cant_put(si);
3773 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3774 }
3775 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3776 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003777
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003778 /* Read the maximum amount of data avalaible. */
3779 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003780
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003781 /* Data not yet avalaible. return yield. */
3782 if (ret == 0) {
3783 si_applet_cant_get(si);
3784 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3785 }
3786
3787 /* End of data: commit the total strings and return. */
3788 if (ret < 0) {
3789 luaL_pushresult(&appctx->b);
3790 return 1;
3791 }
3792
3793 /* Ensure that the block 2 length is usable. */
3794 if (ret == 1)
3795 len2 = 0;
3796
3797 /* Copy the fisrt block caping to the length required. */
3798 if (len1 > len)
3799 len1 = len;
3800 luaL_addlstring(&appctx->b, blk1, len1);
3801 len -= len1;
3802
3803 /* Copy the second block. */
3804 if (len2 > len)
3805 len2 = len;
3806 luaL_addlstring(&appctx->b, blk2, len2);
3807 len -= len2;
3808
3809 /* Consume input channel output buffer data. */
3810 bo_skip(si_oc(si), len1 + len2);
3811 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
3812 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
3813
3814 /* If we are no other data avalaible, yield waiting for new data. */
3815 if (len > 0) {
3816 lua_pushinteger(L, len);
3817 lua_replace(L, 2);
3818 si_applet_cant_get(si);
3819 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3820 }
3821
3822 /* return the result. */
3823 luaL_pushresult(&appctx->b);
3824 return 1;
3825}
3826
3827/* Check arguments for the fucntion "hlua_channel_get_yield". */
3828__LJMP static int hlua_applet_http_recv(lua_State *L)
3829{
3830 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3831 int len = -1;
3832
3833 /* Check arguments. */
3834 if (lua_gettop(L) > 2)
3835 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3836 if (lua_gettop(L) >= 2) {
3837 len = MAY_LJMP(luaL_checkinteger(L, 2));
3838 lua_pop(L, 1);
3839 }
3840
3841 /* Check the required length */
3842 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3843 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3844 lua_pushinteger(L, len);
3845
3846 /* Initialise the string catenation. */
3847 luaL_buffinit(L, &appctx->b);
3848
3849 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
3850}
3851
3852/* Append data in the output side of the buffer. This data is immediatly
3853 * sent. The fcuntion returns the ammount of data writed. If the buffer
3854 * cannot contains the data, the function yield. The function returns -1
3855 * if the channel is closed.
3856 */
3857__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
3858{
3859 size_t len;
3860 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3861 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3862 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3863 struct stream_interface *si = appctx->appctx->owner;
3864 struct channel *chn = si_ic(si);
3865 int max;
3866
3867 /* Get the max amount of data which can write as input in the channel. */
3868 max = channel_recv_max(chn);
3869 if (max > (len - l))
3870 max = len - l;
3871
3872 /* Copy data. */
3873 bi_putblk(chn, str + l, max);
3874
3875 /* update counters. */
3876 l += max;
3877 lua_pop(L, 1);
3878 lua_pushinteger(L, l);
3879
3880 /* If some data is not send, declares the situation to the
3881 * applet, and returns a yield.
3882 */
3883 if (l < len) {
3884 si_applet_cant_put(si);
3885 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
3886 }
3887
3888 return 1;
3889}
3890
3891/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
3892 * yield the LUA process, and resume it without checking the
3893 * input arguments.
3894 */
3895__LJMP static int hlua_applet_http_send(lua_State *L)
3896{
3897 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3898 size_t len;
3899 char hex[10];
3900
3901 MAY_LJMP(luaL_checklstring(L, 2, &len));
3902
3903 /* If transfer encoding chunked is selected, we surround the data
3904 * by chunk data.
3905 */
3906 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
3907 snprintf(hex, 9, "%x", (unsigned int)len);
3908 lua_pushfstring(L, "%s\r\n", hex);
3909 lua_insert(L, 2); /* swap the last 2 entries. */
3910 lua_pushstring(L, "\r\n");
3911 lua_concat(L, 3);
3912 }
3913
3914 /* This interger is used for followinf the amount of data sent. */
3915 lua_pushinteger(L, 0);
3916
3917 /* We want to send some data. Headers must be sent. */
3918 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
3919 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
3920 WILL_LJMP(lua_error(L));
3921 }
3922
3923 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
3924}
3925
3926__LJMP static int hlua_applet_http_addheader(lua_State *L)
3927{
3928 const char *name;
3929 int ret;
3930
3931 MAY_LJMP(hlua_checkapplet_http(L, 1));
3932 name = MAY_LJMP(luaL_checkstring(L, 2));
3933 MAY_LJMP(luaL_checkstring(L, 3));
3934
3935 /* Push in the stack the "response" entry. */
3936 ret = lua_getfield(L, 1, "response");
3937 if (ret != LUA_TTABLE) {
3938 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
3939 "is expected as an array. %s found", lua_typename(L, ret));
3940 WILL_LJMP(lua_error(L));
3941 }
3942
3943 /* check if the header is already registered if it is not
3944 * the case, register it.
3945 */
3946 ret = lua_getfield(L, -1, name);
3947 if (ret == LUA_TNIL) {
3948
3949 /* Entry not found. */
3950 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
3951
3952 /* Insert the new header name in the array in the top of the stack.
3953 * It left the new array in the top of the stack.
3954 */
3955 lua_newtable(L);
3956 lua_pushvalue(L, 2);
3957 lua_pushvalue(L, -2);
3958 lua_settable(L, -4);
3959
3960 } else if (ret != LUA_TTABLE) {
3961
3962 /* corruption error. */
3963 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
3964 "is expected as an array. %s found", name, lua_typename(L, ret));
3965 WILL_LJMP(lua_error(L));
3966 }
3967
3968 /* Now the top od thestack is an array of values. We push
3969 * the header value as new entry.
3970 */
3971 lua_pushvalue(L, 3);
3972 ret = lua_rawlen(L, -2);
3973 lua_rawseti(L, -2, ret + 1);
3974 lua_pushboolean(L, 1);
3975 return 1;
3976}
3977
3978__LJMP static int hlua_applet_http_status(lua_State *L)
3979{
3980 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3981 int status = MAY_LJMP(luaL_checkinteger(L, 2));
3982
3983 if (status < 100 || status > 599) {
3984 lua_pushboolean(L, 0);
3985 return 1;
3986 }
3987
3988 appctx->appctx->ctx.hlua_apphttp.status = status;
3989 lua_pushboolean(L, 1);
3990 return 1;
3991}
3992
3993/* We will build the status line and the headers of the HTTP response.
3994 * We will try send at once if its not possible, we give back the hand
3995 * waiting for more room.
3996 */
3997__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
3998{
3999 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4000 struct stream_interface *si = appctx->appctx->owner;
4001 struct channel *chn = si_ic(si);
4002 int ret;
4003 size_t len;
4004 const char *msg;
4005
4006 /* Get the message as the first argument on the stack. */
4007 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4008
4009 /* Send the message at once. */
4010 ret = bi_putblk(chn, msg, len);
4011
4012 /* if ret == -2 or -3 the channel closed or the message si too
4013 * big for the buffers.
4014 */
4015 if (ret == -2 || ret == -3) {
4016 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4017 WILL_LJMP(lua_error(L));
4018 }
4019
4020 /* If ret is -1, we dont have room in the buffer, so we yield. */
4021 if (ret == -1) {
4022 si_applet_cant_put(si);
4023 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4024 }
4025
4026 /* Headers sent, set the flag. */
4027 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4028 return 0;
4029}
4030
4031__LJMP static int hlua_applet_http_start_response(lua_State *L)
4032{
4033 struct chunk *tmp = get_trash_chunk();
4034 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004035 const char *name;
4036 const char *value;
4037 int id;
4038 int hdr_connection = 0;
4039 int hdr_contentlength = -1;
4040 int hdr_chunked = 0;
4041
4042 /* Use the same http version than the request. */
4043 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004044 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004045 appctx->appctx->ctx.hlua_apphttp.status,
4046 get_reason(appctx->appctx->ctx.hlua_apphttp.status));
4047
4048 /* Get the array associated to the field "response" in the object AppletHTTP. */
4049 lua_pushvalue(L, 0);
4050 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4051 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4052 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4053 WILL_LJMP(lua_error(L));
4054 }
4055
4056 /* Browse the list of headers. */
4057 lua_pushnil(L);
4058 while(lua_next(L, -2) != 0) {
4059
4060 /* We expect a string as -2. */
4061 if (lua_type(L, -2) != LUA_TSTRING) {
4062 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4063 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4064 lua_typename(L, lua_type(L, -2)));
4065 WILL_LJMP(lua_error(L));
4066 }
4067 name = lua_tostring(L, -2);
4068
4069 /* We expect an array as -1. */
4070 if (lua_type(L, -1) != LUA_TTABLE) {
4071 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4072 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4073 name,
4074 lua_typename(L, lua_type(L, -1)));
4075 WILL_LJMP(lua_error(L));
4076 }
4077
4078 /* Browse the table who is on the top of the stack. */
4079 lua_pushnil(L);
4080 while(lua_next(L, -2) != 0) {
4081
4082 /* We expect a number as -2. */
4083 if (lua_type(L, -2) != LUA_TNUMBER) {
4084 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4085 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4086 name,
4087 lua_typename(L, lua_type(L, -2)));
4088 WILL_LJMP(lua_error(L));
4089 }
4090 id = lua_tointeger(L, -2);
4091
4092 /* We expect a string as -2. */
4093 if (lua_type(L, -1) != LUA_TSTRING) {
4094 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4095 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4096 name, id,
4097 lua_typename(L, lua_type(L, -1)));
4098 WILL_LJMP(lua_error(L));
4099 }
4100 value = lua_tostring(L, -1);
4101
4102 /* Catenate a new header. */
4103 chunk_appendf(tmp, "%s: %s\r\n", name, value);
4104
4105 /* Protocol checks. */
4106
4107 /* Check if the header conneciton is present. */
4108 if (strcasecmp("connection", name) == 0)
4109 hdr_connection = 1;
4110
4111 /* Copy the header content length. The length conversion
4112 * is done without control. If it contains a ad value, this
4113 * is not our problem.
4114 */
4115 if (strcasecmp("content-length", name) == 0)
4116 hdr_contentlength = atoi(value);
4117
4118 /* Check if the client annouces a transfer-encoding chunked it self. */
4119 if (strcasecmp("transfer-encoding", name) == 0 &&
4120 strcasecmp("chunked", value) == 0)
4121 hdr_chunked = 1;
4122
4123 /* Remove the array from the stack, and get next element with a remaining string. */
4124 lua_pop(L, 1);
4125 }
4126
4127 /* Remove the array from the stack, and get next element with a remaining string. */
4128 lua_pop(L, 1);
4129 }
4130
4131 /* If the http protocol version is 1.1, we expect an header "connection" set
4132 * to "close" to be HAProxy/keeplive compliant. Otherwise, we expect nothing.
4133 * If the header conneciton is present, don't change it, if it is not present,
4134 * we must set.
4135 *
4136 * we set a "connection: close" header for ensuring that the keepalive will be
4137 * respected by haproxy. HAProcy considers that the application cloe the connection
4138 * and it keep the connection from the client open.
4139 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004140 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 && !hdr_connection)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004141 chunk_appendf(tmp, "Connection: close\r\n");
4142
4143 /* If we dont have a content-length set, we must announce a transfer enconding
4144 * chunked. This is required by haproxy for the keepalive compliance.
4145 * If the applet annouce a transfer-encoding chunked itslef, don't
4146 * do anything.
4147 */
4148 if (hdr_contentlength == -1 && hdr_chunked == 0) {
4149 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4150 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4151 }
4152
4153 /* Finalize headers. */
4154 chunk_appendf(tmp, "\r\n");
4155
4156 /* Remove the last entry and the array of headers */
4157 lua_pop(L, 2);
4158
4159 /* Push the headers block. */
4160 lua_pushlstring(L, tmp->str, tmp->len);
4161
4162 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4163}
4164
4165/*
4166 *
4167 *
4168 * Class HTTP
4169 *
4170 *
4171 */
4172
4173/* Returns a struct hlua_txn if the stack entry "ud" is
4174 * a class stream, otherwise it throws an error.
4175 */
4176__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4177{
4178 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
4179}
4180
4181/* This function creates and push in the stack a HTTP object
4182 * according with a current TXN.
4183 */
4184static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4185{
4186 struct hlua_txn *htxn;
4187
4188 /* Check stack size. */
4189 if (!lua_checkstack(L, 3))
4190 return 0;
4191
4192 /* Create the object: obj[0] = userdata.
4193 * Note that the base of the Converters object is the
4194 * same than the TXN object.
4195 */
4196 lua_newtable(L);
4197 htxn = lua_newuserdata(L, sizeof(*htxn));
4198 lua_rawseti(L, -2, 0);
4199
4200 htxn->s = txn->s;
4201 htxn->p = txn->p;
4202
4203 /* Pop a class stream metatable and affect it to the table. */
4204 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4205 lua_setmetatable(L, -2);
4206
4207 return 1;
4208}
4209
4210/* This function creates ans returns an array of HTTP headers.
4211 * This function does not fails. It is used as wrapper with the
4212 * 2 following functions.
4213 */
4214__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4215{
4216 const char *cur_ptr, *cur_next, *p;
4217 int old_idx, cur_idx;
4218 struct hdr_idx_elem *cur_hdr;
4219 const char *hn, *hv;
4220 int hnl, hvl;
4221 int type;
4222 const char *in;
4223 char *out;
4224 int len;
4225
4226 /* Create the table. */
4227 lua_newtable(L);
4228
4229 if (!htxn->s->txn)
4230 return 1;
4231
4232 /* Build array of headers. */
4233 old_idx = 0;
4234 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4235
4236 while (1) {
4237 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4238 if (!cur_idx)
4239 break;
4240 old_idx = cur_idx;
4241
4242 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4243 cur_ptr = cur_next;
4244 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4245
4246 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4247 * and the next header starts at cur_next. We'll check
4248 * this header in the list as well as against the default
4249 * rule.
4250 */
4251
4252 /* look for ': *'. */
4253 hn = cur_ptr;
4254 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4255 if (p >= cur_ptr+cur_hdr->len)
4256 continue;
4257 hnl = p - hn;
4258 p++;
4259 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4260 p++;
4261 if (p >= cur_ptr+cur_hdr->len)
4262 continue;
4263 hv = p;
4264 hvl = cur_ptr+cur_hdr->len-p;
4265
4266 /* Lowercase the key. Don't check the size of trash, it have
4267 * the size of one buffer and the input data contains in one
4268 * buffer.
4269 */
4270 out = trash.str;
4271 for (in=hn; in<hn+hnl; in++, out++)
4272 *out = tolower(*in);
4273 *out = '\0';
4274
4275 /* Check for existing entry:
4276 * assume that the table is on the top of the stack, and
4277 * push the key in the stack, the function lua_gettable()
4278 * perform the lookup.
4279 */
4280 lua_pushlstring(L, trash.str, hnl);
4281 lua_gettable(L, -2);
4282 type = lua_type(L, -1);
4283
4284 switch (type) {
4285 case LUA_TNIL:
4286 /* Table not found, create it. */
4287 lua_pop(L, 1); /* remove the nil value. */
4288 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4289 lua_newtable(L); /* create and push empty table. */
4290 lua_pushlstring(L, hv, hvl); /* push header value. */
4291 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4292 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4293 break;
4294
4295 case LUA_TTABLE:
4296 /* Entry found: push the value in the table. */
4297 len = lua_rawlen(L, -1);
4298 lua_pushlstring(L, hv, hvl); /* push header value. */
4299 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4300 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4301 break;
4302
4303 default:
4304 /* Other cases are errors. */
4305 hlua_pusherror(L, "internal error during the parsing of headers.");
4306 WILL_LJMP(lua_error(L));
4307 }
4308 }
4309
4310 return 1;
4311}
4312
4313__LJMP static int hlua_http_req_get_headers(lua_State *L)
4314{
4315 struct hlua_txn *htxn;
4316
4317 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4318 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4319
4320 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4321}
4322
4323__LJMP static int hlua_http_res_get_headers(lua_State *L)
4324{
4325 struct hlua_txn *htxn;
4326
4327 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4328 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4329
4330 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4331}
4332
4333/* This function replace full header, or just a value in
4334 * the request or in the response. It is a wrapper fir the
4335 * 4 following functions.
4336 */
4337__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4338 struct http_msg *msg, int action)
4339{
4340 size_t name_len;
4341 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4342 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4343 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4344 struct my_regex re;
4345
4346 if (!regex_comp(reg, &re, 1, 1, NULL))
4347 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4348
4349 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4350 regex_free(&re);
4351 return 0;
4352}
4353
4354__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4355{
4356 struct hlua_txn *htxn;
4357
4358 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4359 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4360
4361 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4362}
4363
4364__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4365{
4366 struct hlua_txn *htxn;
4367
4368 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4369 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4370
4371 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4372}
4373
4374__LJMP static int hlua_http_req_rep_val(lua_State *L)
4375{
4376 struct hlua_txn *htxn;
4377
4378 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4379 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4380
4381 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4382}
4383
4384__LJMP static int hlua_http_res_rep_val(lua_State *L)
4385{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004386 struct hlua_txn *htxn;
4387
4388 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4389 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4390
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004391 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004392}
4393
4394/* This function deletes all the occurences of an header.
4395 * It is a wrapper for the 2 following functions.
4396 */
4397__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4398{
4399 size_t len;
4400 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4401 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004402 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004403
4404 ctx.idx = 0;
4405 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4406 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4407 return 0;
4408}
4409
4410__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4411{
4412 struct hlua_txn *htxn;
4413
4414 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4415 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4416
Willy Tarreaueee5b512015-04-03 23:46:31 +02004417 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004418}
4419
4420__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4421{
4422 struct hlua_txn *htxn;
4423
4424 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4425 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4426
Willy Tarreaueee5b512015-04-03 23:46:31 +02004427 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004428}
4429
4430/* This function adds an header. It is a wrapper used by
4431 * the 2 following functions.
4432 */
4433__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4434{
4435 size_t name_len;
4436 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4437 size_t value_len;
4438 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4439 char *p;
4440
4441 /* Check length. */
4442 trash.len = value_len + name_len + 2;
4443 if (trash.len > trash.size)
4444 return 0;
4445
4446 /* Creates the header string. */
4447 p = trash.str;
4448 memcpy(p, name, name_len);
4449 p += name_len;
4450 *p = ':';
4451 p++;
4452 *p = ' ';
4453 p++;
4454 memcpy(p, value, value_len);
4455
Willy Tarreaueee5b512015-04-03 23:46:31 +02004456 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004457 trash.str, trash.len) != 0);
4458
4459 return 0;
4460}
4461
4462__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4463{
4464 struct hlua_txn *htxn;
4465
4466 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4467 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4468
Willy Tarreaueee5b512015-04-03 23:46:31 +02004469 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004470}
4471
4472__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4473{
4474 struct hlua_txn *htxn;
4475
4476 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4477 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4478
Willy Tarreaueee5b512015-04-03 23:46:31 +02004479 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004480}
4481
4482static int hlua_http_req_set_hdr(lua_State *L)
4483{
4484 struct hlua_txn *htxn;
4485
4486 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4487 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4488
Willy Tarreaueee5b512015-04-03 23:46:31 +02004489 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4490 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004491}
4492
4493static int hlua_http_res_set_hdr(lua_State *L)
4494{
4495 struct hlua_txn *htxn;
4496
4497 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4498 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4499
Willy Tarreaueee5b512015-04-03 23:46:31 +02004500 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4501 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004502}
4503
4504/* This function set the method. */
4505static int hlua_http_req_set_meth(lua_State *L)
4506{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004507 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004508 size_t name_len;
4509 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004510
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004511 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004512 return 1;
4513}
4514
4515/* This function set the method. */
4516static int hlua_http_req_set_path(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));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004521 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004522 return 1;
4523}
4524
4525/* This function set the query-string. */
4526static int hlua_http_req_set_query(lua_State *L)
4527{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004528 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004529 size_t name_len;
4530 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004531
4532 /* Check length. */
4533 if (name_len > trash.size - 1) {
4534 lua_pushboolean(L, 0);
4535 return 1;
4536 }
4537
4538 /* Add the mark question as prefix. */
4539 chunk_reset(&trash);
4540 trash.str[trash.len++] = '?';
4541 memcpy(trash.str + trash.len, name, name_len);
4542 trash.len += name_len;
4543
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004544 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004545 return 1;
4546}
4547
4548/* This function set the uri. */
4549static int hlua_http_req_set_uri(lua_State *L)
4550{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004551 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004552 size_t name_len;
4553 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004554
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004555 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004556 return 1;
4557}
4558
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004559/* This function set the response code. */
4560static int hlua_http_res_set_status(lua_State *L)
4561{
4562 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4563 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
4564
4565 http_set_status(code, htxn->s);
4566 return 0;
4567}
4568
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004569/*
4570 *
4571 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004572 * Class TXN
4573 *
4574 *
4575 */
4576
4577/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004578 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004579 */
4580__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4581{
4582 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
4583}
4584
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004585__LJMP static int hlua_set_var(lua_State *L)
4586{
4587 struct hlua_txn *htxn;
4588 const char *name;
4589 size_t len;
4590 struct sample smp;
4591
4592 MAY_LJMP(check_args(L, 3, "set_var"));
4593
4594 /* It is useles to retrieve the stream, but this function
4595 * runs only in a stream context.
4596 */
4597 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4598 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4599
4600 /* Converts the third argument in a sample. */
4601 hlua_lua2smp(L, 3, &smp);
4602
4603 /* Store the sample in a variable. */
4604 vars_set_by_name(name, len, htxn->s, &smp);
4605 return 0;
4606}
4607
4608__LJMP static int hlua_get_var(lua_State *L)
4609{
4610 struct hlua_txn *htxn;
4611 const char *name;
4612 size_t len;
4613 struct sample smp;
4614
4615 MAY_LJMP(check_args(L, 2, "get_var"));
4616
4617 /* It is useles to retrieve the stream, but this function
4618 * runs only in a stream context.
4619 */
4620 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4621 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4622
4623 if (!vars_get_by_name(name, len, htxn->s, &smp)) {
4624 lua_pushnil(L);
4625 return 1;
4626 }
4627
4628 return hlua_smp2lua(L, &smp);
4629}
4630
Willy Tarreau59551662015-03-10 14:23:13 +01004631__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004632{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004633 struct hlua *hlua;
4634
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004635 MAY_LJMP(check_args(L, 2, "set_priv"));
4636
Willy Tarreau87b09662015-04-03 00:22:06 +02004637 /* It is useles to retrieve the stream, but this function
4638 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004639 */
4640 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004641 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004642
4643 /* Remove previous value. */
4644 if (hlua->Mref != -1)
4645 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
4646
4647 /* Get and store new value. */
4648 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4649 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4650
4651 return 0;
4652}
4653
Willy Tarreau59551662015-03-10 14:23:13 +01004654__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004655{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004656 struct hlua *hlua;
4657
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004658 MAY_LJMP(check_args(L, 1, "get_priv"));
4659
Willy Tarreau87b09662015-04-03 00:22:06 +02004660 /* It is useles to retrieve the stream, but this function
4661 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004662 */
4663 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004664 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004665
4666 /* Push configuration index in the stack. */
4667 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4668
4669 return 1;
4670}
4671
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004672/* Create stack entry containing a class TXN. This function
4673 * return 0 if the stack does not contains free slots,
4674 * otherwise it returns 1.
4675 */
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004676static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004677{
Willy Tarreaude491382015-04-06 11:04:28 +02004678 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004679
4680 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004681 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004682 return 0;
4683
4684 /* NOTE: The allocation never fails. The failure
4685 * throw an error, and the function never returns.
4686 * if the throw is not avalaible, the process is aborted.
4687 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004688 /* Create the object: obj[0] = userdata. */
4689 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004690 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004691 lua_rawseti(L, -2, 0);
4692
Willy Tarreaude491382015-04-06 11:04:28 +02004693 htxn->s = s;
4694 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004695 htxn->dir = dir;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004696
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004697 /* Create the "f" field that contains a list of fetches. */
4698 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004699 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004700 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004701 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004702
4703 /* Create the "sf" field that contains a list of stringsafe fetches. */
4704 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004705 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004706 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004707 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004708
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004709 /* Create the "c" field that contains a list of converters. */
4710 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004711 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004712 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004713 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004714
4715 /* Create the "sc" field that contains a list of stringsafe converters. */
4716 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004717 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004718 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004719 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004720
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004721 /* Create the "req" field that contains the request channel object. */
4722 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004723 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004724 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004725 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004726
4727 /* Create the "res" field that contains the response channel object. */
4728 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004729 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004730 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004731 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004732
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004733 /* Creates the HTTP object is the current proxy allows http. */
4734 lua_pushstring(L, "http");
4735 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02004736 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004737 return 0;
4738 }
4739 else
4740 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004741 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004742
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004743 /* Pop a class sesison metatable and affect it to the userdata. */
4744 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
4745 lua_setmetatable(L, -2);
4746
4747 return 1;
4748}
4749
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004750__LJMP static int hlua_txn_deflog(lua_State *L)
4751{
4752 const char *msg;
4753 struct hlua_txn *htxn;
4754
4755 MAY_LJMP(check_args(L, 2, "deflog"));
4756 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4757 msg = MAY_LJMP(luaL_checkstring(L, 2));
4758
4759 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
4760 return 0;
4761}
4762
4763__LJMP static int hlua_txn_log(lua_State *L)
4764{
4765 int level;
4766 const char *msg;
4767 struct hlua_txn *htxn;
4768
4769 MAY_LJMP(check_args(L, 3, "log"));
4770 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4771 level = MAY_LJMP(luaL_checkinteger(L, 2));
4772 msg = MAY_LJMP(luaL_checkstring(L, 3));
4773
4774 if (level < 0 || level >= NB_LOG_LEVELS)
4775 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4776
4777 hlua_sendlog(htxn->s->be, level, msg);
4778 return 0;
4779}
4780
4781__LJMP static int hlua_txn_log_debug(lua_State *L)
4782{
4783 const char *msg;
4784 struct hlua_txn *htxn;
4785
4786 MAY_LJMP(check_args(L, 2, "Debug"));
4787 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4788 msg = MAY_LJMP(luaL_checkstring(L, 2));
4789 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
4790 return 0;
4791}
4792
4793__LJMP static int hlua_txn_log_info(lua_State *L)
4794{
4795 const char *msg;
4796 struct hlua_txn *htxn;
4797
4798 MAY_LJMP(check_args(L, 2, "Info"));
4799 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4800 msg = MAY_LJMP(luaL_checkstring(L, 2));
4801 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
4802 return 0;
4803}
4804
4805__LJMP static int hlua_txn_log_warning(lua_State *L)
4806{
4807 const char *msg;
4808 struct hlua_txn *htxn;
4809
4810 MAY_LJMP(check_args(L, 2, "Warning"));
4811 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4812 msg = MAY_LJMP(luaL_checkstring(L, 2));
4813 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
4814 return 0;
4815}
4816
4817__LJMP static int hlua_txn_log_alert(lua_State *L)
4818{
4819 const char *msg;
4820 struct hlua_txn *htxn;
4821
4822 MAY_LJMP(check_args(L, 2, "Alert"));
4823 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4824 msg = MAY_LJMP(luaL_checkstring(L, 2));
4825 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
4826 return 0;
4827}
4828
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004829__LJMP static int hlua_txn_set_loglevel(lua_State *L)
4830{
4831 struct hlua_txn *htxn;
4832 int ll;
4833
4834 MAY_LJMP(check_args(L, 2, "set_loglevel"));
4835 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4836 ll = MAY_LJMP(luaL_checkinteger(L, 2));
4837
4838 if (ll < 0 || ll > 7)
4839 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
4840
4841 htxn->s->logs.level = ll;
4842 return 0;
4843}
4844
4845__LJMP static int hlua_txn_set_tos(lua_State *L)
4846{
4847 struct hlua_txn *htxn;
4848 struct connection *cli_conn;
4849 int tos;
4850
4851 MAY_LJMP(check_args(L, 2, "set_tos"));
4852 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4853 tos = MAY_LJMP(luaL_checkinteger(L, 2));
4854
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004855 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004856 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
4857
4858 return 0;
4859}
4860
4861__LJMP static int hlua_txn_set_mark(lua_State *L)
4862{
4863#ifdef SO_MARK
4864 struct hlua_txn *htxn;
4865 struct connection *cli_conn;
4866 int mark;
4867
4868 MAY_LJMP(check_args(L, 2, "set_mark"));
4869 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4870 mark = MAY_LJMP(luaL_checkinteger(L, 2));
4871
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004872 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02004873 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004874#endif
4875 return 0;
4876}
4877
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004878/* This function is an Lua binding that send pending data
4879 * to the client, and close the stream interface.
4880 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004881__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004882{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004883 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01004884 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004885
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004886 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004887 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004888
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004889 ic = &htxn->s->req;
4890 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01004891
Willy Tarreau630ef452015-08-28 10:06:15 +02004892 if (htxn->s->txn) {
4893 /* HTTP mode, let's stay in sync with the stream */
4894 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
4895 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
4896 htxn->s->txn->req.sov = 0;
4897 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
4898 oc->analysers = AN_RES_HTTP_XFER_BODY;
4899 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
4900 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
4901
Willy Tarreau630ef452015-08-28 10:06:15 +02004902 /* Note that if we want to support keep-alive, we need
4903 * to bypass the close/shutr_now calls below, but that
4904 * may only be done if the HTTP request was already
4905 * processed and the connection header is known (ie
4906 * not during TCP rules).
4907 */
4908 }
4909
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004910 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01004911 channel_abort(ic);
4912 channel_auto_close(ic);
4913 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004914
4915 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01004916 channel_auto_read(oc);
4917 channel_auto_close(oc);
4918 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004919
Willy Tarreau0458b082015-08-28 09:40:04 +02004920 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004921
4922 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004923 return 0;
4924}
4925
4926__LJMP static int hlua_log(lua_State *L)
4927{
4928 int level;
4929 const char *msg;
4930
4931 MAY_LJMP(check_args(L, 2, "log"));
4932 level = MAY_LJMP(luaL_checkinteger(L, 1));
4933 msg = MAY_LJMP(luaL_checkstring(L, 2));
4934
4935 if (level < 0 || level >= NB_LOG_LEVELS)
4936 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4937
4938 hlua_sendlog(NULL, level, msg);
4939 return 0;
4940}
4941
4942__LJMP static int hlua_log_debug(lua_State *L)
4943{
4944 const char *msg;
4945
4946 MAY_LJMP(check_args(L, 1, "debug"));
4947 msg = MAY_LJMP(luaL_checkstring(L, 1));
4948 hlua_sendlog(NULL, LOG_DEBUG, msg);
4949 return 0;
4950}
4951
4952__LJMP static int hlua_log_info(lua_State *L)
4953{
4954 const char *msg;
4955
4956 MAY_LJMP(check_args(L, 1, "info"));
4957 msg = MAY_LJMP(luaL_checkstring(L, 1));
4958 hlua_sendlog(NULL, LOG_INFO, msg);
4959 return 0;
4960}
4961
4962__LJMP static int hlua_log_warning(lua_State *L)
4963{
4964 const char *msg;
4965
4966 MAY_LJMP(check_args(L, 1, "warning"));
4967 msg = MAY_LJMP(luaL_checkstring(L, 1));
4968 hlua_sendlog(NULL, LOG_WARNING, msg);
4969 return 0;
4970}
4971
4972__LJMP static int hlua_log_alert(lua_State *L)
4973{
4974 const char *msg;
4975
4976 MAY_LJMP(check_args(L, 1, "alert"));
4977 msg = MAY_LJMP(luaL_checkstring(L, 1));
4978 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004979 return 0;
4980}
4981
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004982__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004983{
4984 int wakeup_ms = lua_tointeger(L, -1);
4985 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004986 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004987 return 0;
4988}
4989
4990__LJMP static int hlua_sleep(lua_State *L)
4991{
4992 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004993 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004994
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004995 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004996
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004997 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004998 wakeup_ms = tick_add(now_ms, delay);
4999 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005000
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005001 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5002 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005003}
5004
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005005__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005006{
5007 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005008 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005009
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005010 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005011
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005012 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005013 wakeup_ms = tick_add(now_ms, delay);
5014 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005015
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005016 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5017 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005018}
5019
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005020/* This functionis an LUA binding. it permits to give back
5021 * the hand at the HAProxy scheduler. It is used when the
5022 * LUA processing consumes a lot of time.
5023 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005024__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005025{
5026 return 0;
5027}
5028
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005029__LJMP static int hlua_yield(lua_State *L)
5030{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005031 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5032 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005033}
5034
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005035/* This function change the nice of the currently executed
5036 * task. It is used set low or high priority at the current
5037 * task.
5038 */
Willy Tarreau59551662015-03-10 14:23:13 +01005039__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005040{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005041 struct hlua *hlua;
5042 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005043
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005044 MAY_LJMP(check_args(L, 1, "set_nice"));
5045 hlua = hlua_gethlua(L);
5046 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005047
5048 /* If he task is not set, I'm in a start mode. */
5049 if (!hlua || !hlua->task)
5050 return 0;
5051
5052 if (nice < -1024)
5053 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005054 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005055 nice = 1024;
5056
5057 hlua->task->nice = nice;
5058 return 0;
5059}
5060
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005061/* This function is used as a calback of a task. It is called by the
5062 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5063 * return an E_AGAIN signal, the emmiter of this signal must set a
5064 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005065 *
5066 * Task wrapper are longjmp safe because the only one Lua code
5067 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005068 */
5069static struct task *hlua_process_task(struct task *task)
5070{
5071 struct hlua *hlua = task->context;
5072 enum hlua_exec status;
5073
5074 /* We need to remove the task from the wait queue before executing
5075 * the Lua code because we don't know if it needs to wait for
5076 * another timer or not in the case of E_AGAIN.
5077 */
5078 task_delete(task);
5079
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005080 /* If it is the first call to the task, we must initialize the
5081 * execution timeouts.
5082 */
5083 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005084 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005085
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005086 /* Execute the Lua code. */
5087 status = hlua_ctx_resume(hlua, 1);
5088
5089 switch (status) {
5090 /* finished or yield */
5091 case HLUA_E_OK:
5092 hlua_ctx_destroy(hlua);
5093 task_delete(task);
5094 task_free(task);
5095 break;
5096
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005097 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5098 if (hlua->wake_time != TICK_ETERNITY)
5099 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005100 break;
5101
5102 /* finished with error. */
5103 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005104 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005105 hlua_ctx_destroy(hlua);
5106 task_delete(task);
5107 task_free(task);
5108 break;
5109
5110 case HLUA_E_ERR:
5111 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005112 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005113 hlua_ctx_destroy(hlua);
5114 task_delete(task);
5115 task_free(task);
5116 break;
5117 }
5118 return NULL;
5119}
5120
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005121/* This function is an LUA binding that register LUA function to be
5122 * executed after the HAProxy configuration parsing and before the
5123 * HAProxy scheduler starts. This function expect only one LUA
5124 * argument that is a function. This function returns nothing, but
5125 * throws if an error is encountered.
5126 */
5127__LJMP static int hlua_register_init(lua_State *L)
5128{
5129 struct hlua_init_function *init;
5130 int ref;
5131
5132 MAY_LJMP(check_args(L, 1, "register_init"));
5133
5134 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5135
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005136 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005137 if (!init)
5138 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5139
5140 init->function_ref = ref;
5141 LIST_ADDQ(&hlua_init_functions, &init->l);
5142 return 0;
5143}
5144
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005145/* This functio is an LUA binding. It permits to register a task
5146 * executed in parallel of the main HAroxy activity. The task is
5147 * created and it is set in the HAProxy scheduler. It can be called
5148 * from the "init" section, "post init" or during the runtime.
5149 *
5150 * Lua prototype:
5151 *
5152 * <none> core.register_task(<function>)
5153 */
5154static int hlua_register_task(lua_State *L)
5155{
5156 struct hlua *hlua;
5157 struct task *task;
5158 int ref;
5159
5160 MAY_LJMP(check_args(L, 1, "register_task"));
5161
5162 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5163
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005164 hlua = calloc(1, sizeof(*hlua));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005165 if (!hlua)
5166 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5167
5168 task = task_new();
5169 task->context = hlua;
5170 task->process = hlua_process_task;
5171
5172 if (!hlua_ctx_init(hlua, task))
5173 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5174
5175 /* Restore the function in the stack. */
5176 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5177 hlua->nargs = 0;
5178
5179 /* Schedule task. */
5180 task_schedule(task, now_ms);
5181
5182 return 0;
5183}
5184
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005185/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5186 * doesn't allow "yield" functions because the HAProxy engine cannot
5187 * resume converters.
5188 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005189static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005190{
5191 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005192 struct stream *stream = smp->strm;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005193
Willy Tarreau87b09662015-04-03 00:22:06 +02005194 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005195 * Lua context can be not initialized. This behavior
5196 * permits to save performances because a systematic
5197 * Lua initialization cause 5% performances loss.
5198 */
Willy Tarreau87b09662015-04-03 00:22:06 +02005199 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005200 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005201 return 0;
5202 }
5203
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005204 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005205 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005206
5207 /* The following Lua calls can fail. */
5208 if (!SET_SAFE_LJMP(stream->hlua.T)) {
5209 SEND_ERR(stream->be, "Lua converter '%s': critical error.\n", fcn->name);
5210 return 0;
5211 }
5212
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005213 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005214 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005215 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005216 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005217 return 0;
5218 }
5219
5220 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005221 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005222
5223 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005224 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005225 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005226 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005227 return 0;
5228 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005229 hlua_smp2lua(stream->hlua.T, smp);
5230 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005231
5232 /* push keywords in the stack. */
5233 if (arg_p) {
5234 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02005235 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005236 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005237 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005238 return 0;
5239 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005240 hlua_arg2lua(stream->hlua.T, arg_p);
5241 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005242 }
5243 }
5244
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005245 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005246 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005247
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005248 /* At this point the execution is safe. */
5249 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005250 }
5251
5252 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005253 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005254 /* finished. */
5255 case HLUA_E_OK:
5256 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005257 hlua_lua2smp(stream->hlua.T, -1, smp);
5258 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005259 return 1;
5260
5261 /* yield. */
5262 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005263 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005264 return 0;
5265
5266 /* finished with error. */
5267 case HLUA_E_ERRMSG:
5268 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005269 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
5270 fcn->name, lua_tostring(stream->hlua.T, -1));
Willy Tarreau87b09662015-04-03 00:22:06 +02005271 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005272 return 0;
5273
5274 case HLUA_E_ERR:
5275 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005276 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005277
5278 default:
5279 return 0;
5280 }
5281}
5282
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005283/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5284 * doesn't allow "yield" functions because the HAProxy engine cannot
5285 * resume sample-fetches.
5286 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005287static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5288 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005289{
5290 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005291 struct stream *stream = smp->strm;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005292
Willy Tarreau87b09662015-04-03 00:22:06 +02005293 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005294 * Lua context can be not initialized. This behavior
5295 * permits to save performances because a systematic
5296 * Lua initialization cause 5% performances loss.
5297 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005298 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005299 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005300 return 0;
5301 }
5302
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005303 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005304 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005305
5306 /* The following Lua calls can fail. */
5307 if (!SET_SAFE_LJMP(stream->hlua.T)) {
5308 SEND_ERR(smp->px, "Lua sample-fetch '%s': critical error.\n", fcn->name);
5309 return 0;
5310 }
5311
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005312 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005313 if (!lua_checkstack(stream->hlua.T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005314 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005315 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005316 return 0;
5317 }
5318
5319 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005320 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005321
5322 /* push arguments in the stack. */
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005323 if (!hlua_txn_new(stream->hlua.T, stream, smp->px, smp->opt & SMP_OPT_DIR)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005324 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005325 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005326 return 0;
5327 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005328 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005329
5330 /* push keywords in the stack. */
5331 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5332 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005333 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005334 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005335 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005336 return 0;
5337 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005338 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005339 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005340 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005341 return 0;
5342 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005343 hlua_arg2lua(stream->hlua.T, arg_p);
5344 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005345 }
5346
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005347 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005348 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005349
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005350 /* At this point the execution is safe. */
5351 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005352 }
5353
5354 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005355 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005356 /* finished. */
5357 case HLUA_E_OK:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005358 if (!hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005359 return 0;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005360 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005361 hlua_lua2smp(stream->hlua.T, -1, smp);
5362 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005363
5364 /* Set the end of execution flag. */
5365 smp->flags &= ~SMP_F_MAY_CHANGE;
5366 return 1;
5367
5368 /* yield. */
5369 case HLUA_E_AGAIN:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005370 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005371 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005372 return 0;
5373
5374 /* finished with error. */
5375 case HLUA_E_ERRMSG:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005376 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005377 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005378 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
5379 fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005380 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005381 return 0;
5382
5383 case HLUA_E_ERR:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005384 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005385 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005386 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005387
5388 default:
5389 return 0;
5390 }
5391}
5392
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005393/* This function is an LUA binding used for registering
5394 * "sample-conv" functions. It expects a converter name used
5395 * in the haproxy configuration file, and an LUA function.
5396 */
5397__LJMP static int hlua_register_converters(lua_State *L)
5398{
5399 struct sample_conv_kw_list *sck;
5400 const char *name;
5401 int ref;
5402 int len;
5403 struct hlua_function *fcn;
5404
5405 MAY_LJMP(check_args(L, 2, "register_converters"));
5406
5407 /* First argument : converter name. */
5408 name = MAY_LJMP(luaL_checkstring(L, 1));
5409
5410 /* Second argument : lua function. */
5411 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5412
5413 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005414 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005415 if (!sck)
5416 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005417 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005418 if (!fcn)
5419 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5420
5421 /* Fill fcn. */
5422 fcn->name = strdup(name);
5423 if (!fcn->name)
5424 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5425 fcn->function_ref = ref;
5426
5427 /* List head */
5428 sck->list.n = sck->list.p = NULL;
5429
5430 /* converter keyword. */
5431 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005432 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005433 if (!sck->kw[0].kw)
5434 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5435
5436 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5437 sck->kw[0].process = hlua_sample_conv_wrapper;
5438 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
5439 sck->kw[0].val_args = NULL;
5440 sck->kw[0].in_type = SMP_T_STR;
5441 sck->kw[0].out_type = SMP_T_STR;
5442 sck->kw[0].private = fcn;
5443
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005444 /* Register this new converter */
5445 sample_register_convs(sck);
5446
5447 return 0;
5448}
5449
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005450/* This fucntion is an LUA binding used for registering
5451 * "sample-fetch" functions. It expects a converter name used
5452 * in the haproxy configuration file, and an LUA function.
5453 */
5454__LJMP static int hlua_register_fetches(lua_State *L)
5455{
5456 const char *name;
5457 int ref;
5458 int len;
5459 struct sample_fetch_kw_list *sfk;
5460 struct hlua_function *fcn;
5461
5462 MAY_LJMP(check_args(L, 2, "register_fetches"));
5463
5464 /* First argument : sample-fetch name. */
5465 name = MAY_LJMP(luaL_checkstring(L, 1));
5466
5467 /* Second argument : lua function. */
5468 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5469
5470 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005471 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005472 if (!sfk)
5473 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005474 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005475 if (!fcn)
5476 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5477
5478 /* Fill fcn. */
5479 fcn->name = strdup(name);
5480 if (!fcn->name)
5481 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5482 fcn->function_ref = ref;
5483
5484 /* List head */
5485 sfk->list.n = sfk->list.p = NULL;
5486
5487 /* sample-fetch keyword. */
5488 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005489 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005490 if (!sfk->kw[0].kw)
5491 return luaL_error(L, "lua out of memory error.");
5492
5493 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5494 sfk->kw[0].process = hlua_sample_fetch_wrapper;
5495 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
5496 sfk->kw[0].val_args = NULL;
5497 sfk->kw[0].out_type = SMP_T_STR;
5498 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5499 sfk->kw[0].val = 0;
5500 sfk->kw[0].private = fcn;
5501
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005502 /* Register this new fetch. */
5503 sample_register_fetches(sfk);
5504
5505 return 0;
5506}
5507
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005508/* This function is a wrapper to execute each LUA function declared
5509 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005510 * return ACT_RET_CONT if the processing is finished (with or without
5511 * error) and return ACT_RET_YIELD if the function must be called again
5512 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005513 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005514static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005515 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005516{
5517 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005518 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005519 int dir;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005520
5521 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01005522 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
5523 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
5524 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
5525 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005526 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005527 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005528 return ACT_RET_CONT;
5529 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005530
Willy Tarreau87b09662015-04-03 00:22:06 +02005531 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005532 * Lua context can be not initialized. This behavior
5533 * permits to save performances because a systematic
5534 * Lua initialization cause 5% performances loss.
5535 */
5536 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005537 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005538 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005539 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005540 }
5541
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005542 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01005543 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005544
5545 /* The following Lua calls can fail. */
5546 if (!SET_SAFE_LJMP(s->hlua.T)) {
5547 SEND_ERR(px, "Lua function '%s': critical error.\n",
5548 rule->arg.hlua_rule->fcn.name);
5549 return ACT_RET_CONT;
5550 }
5551
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005552 /* Check stack available size. */
5553 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005554 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005555 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005556 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005557 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005558 }
5559
5560 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005561 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005562
Willy Tarreau87b09662015-04-03 00:22:06 +02005563 /* Create and and push object stream in the stack. */
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005564 if (!hlua_txn_new(s->hlua.T, s, px, dir)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005565 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005566 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005567 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005568 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005569 }
5570 s->hlua.nargs = 1;
5571
5572 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005573 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005574 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005575 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005576 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005577 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005578 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005579 }
5580 lua_pushstring(s->hlua.T, *arg);
5581 s->hlua.nargs++;
5582 }
5583
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005584 /* Now the execution is safe. */
5585 RESET_SAFE_LJMP(s->hlua.T);
5586
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005587 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005588 s->hlua.max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005589 }
5590
5591 /* Execute the function. */
Willy Tarreau528192d2015-09-27 10:48:01 +02005592 switch (hlua_ctx_resume(&s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005593 /* finished. */
5594 case HLUA_E_OK:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005595 if (!hlua_check_proto(s, dir))
5596 return ACT_RET_ERR;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005597 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005598
5599 /* yield. */
5600 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005601 /* Set timeout in the required channel. */
5602 if (s->hlua.wake_time != TICK_ETERNITY) {
5603 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005604 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005605 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005606 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005607 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005608 /* Some actions can be wake up when a "write" event
5609 * is detected on a response channel. This is useful
5610 * only for actions targetted on the requests.
5611 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01005612 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005613 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005614 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005615 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005616 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01005617 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005618 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005619 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005620
5621 /* finished with error. */
5622 case HLUA_E_ERRMSG:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005623 if (!hlua_check_proto(s, dir))
5624 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005625 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005626 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005627 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005628 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005629 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005630
5631 case HLUA_E_ERR:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005632 if (!hlua_check_proto(s, dir))
5633 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005634 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005635 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005636 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005637
5638 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005639 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005640 }
5641}
5642
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005643struct task *hlua_applet_wakeup(struct task *t)
5644{
5645 struct appctx *ctx = t->context;
5646 struct stream_interface *si = ctx->owner;
5647
5648 /* If the applet is wake up without any expected work, the sheduler
5649 * remove it from the run queue. This flag indicate that the applet
5650 * is waiting for write. If the buffer is full, the main processing
5651 * will send some data and after call the applet, otherwise it call
5652 * the applet ASAP.
5653 */
5654 si_applet_cant_put(si);
5655 appctx_wakeup(ctx);
5656 return NULL;
5657}
5658
5659static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5660{
5661 struct stream_interface *si = ctx->owner;
5662 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5663 struct task *task;
5664 char **arg;
5665
5666 HLUA_INIT(hlua);
5667 ctx->ctx.hlua_apptcp.flags = 0;
5668
5669 /* Create task used by signal to wakeup applets. */
5670 task = task_new();
5671 if (!task) {
5672 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5673 ctx->rule->arg.hlua_rule->fcn.name);
5674 return 0;
5675 }
5676 task->nice = 0;
5677 task->context = ctx;
5678 task->process = hlua_applet_wakeup;
5679 ctx->ctx.hlua_apptcp.task = task;
5680
5681 /* In the execution wrappers linked with a stream, the
5682 * Lua context can be not initialized. This behavior
5683 * permits to save performances because a systematic
5684 * Lua initialization cause 5% performances loss.
5685 */
5686 if (!hlua_ctx_init(hlua, task)) {
5687 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
5688 ctx->rule->arg.hlua_rule->fcn.name);
5689 return 0;
5690 }
5691
5692 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005693 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005694
5695 /* The following Lua calls can fail. */
5696 if (!SET_SAFE_LJMP(hlua->T)) {
5697 SEND_ERR(px, "Lua applet tcp '%s': critical error.\n",
5698 ctx->rule->arg.hlua_rule->fcn.name);
5699 RESET_SAFE_LJMP(hlua->T);
5700 return 0;
5701 }
5702
5703 /* Check stack available size. */
5704 if (!lua_checkstack(hlua->T, 1)) {
5705 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5706 ctx->rule->arg.hlua_rule->fcn.name);
5707 RESET_SAFE_LJMP(hlua->T);
5708 return 0;
5709 }
5710
5711 /* Restore the function in the stack. */
5712 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5713
5714 /* Create and and push object stream in the stack. */
5715 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
5716 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5717 ctx->rule->arg.hlua_rule->fcn.name);
5718 RESET_SAFE_LJMP(hlua->T);
5719 return 0;
5720 }
5721 hlua->nargs = 1;
5722
5723 /* push keywords in the stack. */
5724 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5725 if (!lua_checkstack(hlua->T, 1)) {
5726 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5727 ctx->rule->arg.hlua_rule->fcn.name);
5728 RESET_SAFE_LJMP(hlua->T);
5729 return 0;
5730 }
5731 lua_pushstring(hlua->T, *arg);
5732 hlua->nargs++;
5733 }
5734
5735 RESET_SAFE_LJMP(hlua->T);
5736
5737 /* Wakeup the applet ASAP. */
5738 si_applet_cant_get(si);
5739 si_applet_cant_put(si);
5740
5741 return 1;
5742}
5743
5744static void hlua_applet_tcp_fct(struct appctx *ctx)
5745{
5746 struct stream_interface *si = ctx->owner;
5747 struct stream *strm = si_strm(si);
5748 struct channel *res = si_ic(si);
5749 struct act_rule *rule = ctx->rule;
5750 struct proxy *px = strm->be;
5751 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5752
5753 /* The applet execution is already done. */
5754 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
5755 return;
5756
5757 /* If the stream is disconnect or closed, ldo nothing. */
5758 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5759 return;
5760
5761 /* Execute the function. */
5762 switch (hlua_ctx_resume(hlua, 1)) {
5763 /* finished. */
5764 case HLUA_E_OK:
5765 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5766
5767 /* log time */
5768 strm->logs.tv_request = now;
5769
5770 /* eat the whole request */
5771 bo_skip(si_oc(si), si_ob(si)->o);
5772 res->flags |= CF_READ_NULL;
5773 si_shutr(si);
5774 return;
5775
5776 /* yield. */
5777 case HLUA_E_AGAIN:
5778 return;
5779
5780 /* finished with error. */
5781 case HLUA_E_ERRMSG:
5782 /* Display log. */
5783 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
5784 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
5785 lua_pop(hlua->T, 1);
5786 goto error;
5787
5788 case HLUA_E_ERR:
5789 /* Display log. */
5790 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
5791 rule->arg.hlua_rule->fcn.name);
5792 goto error;
5793
5794 default:
5795 goto error;
5796 }
5797
5798error:
5799
5800 /* For all other cases, just close the stream. */
5801 si_shutw(si);
5802 si_shutr(si);
5803 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5804}
5805
5806static void hlua_applet_tcp_release(struct appctx *ctx)
5807{
5808 task_free(ctx->ctx.hlua_apptcp.task);
5809 ctx->ctx.hlua_apptcp.task = NULL;
5810 hlua_ctx_destroy(&ctx->ctx.hlua_apptcp.hlua);
5811}
5812
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005813/* The function returns 1 if the initialisation is complete, 0 if
5814 * an errors occurs and -1 if more data are required for initializing
5815 * the applet.
5816 */
5817static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5818{
5819 struct stream_interface *si = ctx->owner;
5820 struct channel *req = si_oc(si);
5821 struct http_msg *msg;
5822 struct http_txn *txn;
5823 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5824 char **arg;
5825 struct hdr_ctx hdr;
5826 struct task *task;
5827 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
5828
5829 /* Wait for a full HTTP request. */
5830 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
5831 if (smp.flags & SMP_F_MAY_CHANGE)
5832 return -1;
5833 return 0;
5834 }
5835 txn = strm->txn;
5836 msg = &txn->req;
5837
Willy Tarreau0078bfc2015-10-07 20:20:28 +02005838 /* We want two things in HTTP mode :
5839 * - enforce server-close mode if we were in keep-alive, so that the
5840 * applet is released after each response ;
5841 * - enable request body transfer to the applet in order to resync
5842 * with the response body.
5843 */
5844 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
5845 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02005846
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005847 HLUA_INIT(hlua);
5848 ctx->ctx.hlua_apphttp.left_bytes = -1;
5849 ctx->ctx.hlua_apphttp.flags = 0;
5850
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01005851 if (txn->req.flags & HTTP_MSGF_VER_11)
5852 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
5853
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005854 /* Create task used by signal to wakeup applets. */
5855 task = task_new();
5856 if (!task) {
5857 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
5858 ctx->rule->arg.hlua_rule->fcn.name);
5859 return 0;
5860 }
5861 task->nice = 0;
5862 task->context = ctx;
5863 task->process = hlua_applet_wakeup;
5864 ctx->ctx.hlua_apphttp.task = task;
5865
5866 /* In the execution wrappers linked with a stream, the
5867 * Lua context can be not initialized. This behavior
5868 * permits to save performances because a systematic
5869 * Lua initialization cause 5% performances loss.
5870 */
5871 if (!hlua_ctx_init(hlua, task)) {
5872 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
5873 ctx->rule->arg.hlua_rule->fcn.name);
5874 return 0;
5875 }
5876
5877 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005878 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005879
5880 /* The following Lua calls can fail. */
5881 if (!SET_SAFE_LJMP(hlua->T)) {
5882 SEND_ERR(px, "Lua applet http '%s': critical error.\n",
5883 ctx->rule->arg.hlua_rule->fcn.name);
5884 return 0;
5885 }
5886
5887 /* Check stack available size. */
5888 if (!lua_checkstack(hlua->T, 1)) {
5889 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5890 ctx->rule->arg.hlua_rule->fcn.name);
5891 RESET_SAFE_LJMP(hlua->T);
5892 return 0;
5893 }
5894
5895 /* Restore the function in the stack. */
5896 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5897
5898 /* Create and and push object stream in the stack. */
5899 if (!hlua_applet_http_new(hlua->T, ctx)) {
5900 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5901 ctx->rule->arg.hlua_rule->fcn.name);
5902 RESET_SAFE_LJMP(hlua->T);
5903 return 0;
5904 }
5905 hlua->nargs = 1;
5906
5907 /* Look for a 100-continue expected. */
5908 if (msg->flags & HTTP_MSGF_VER_11) {
5909 hdr.idx = 0;
5910 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
5911 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
5912 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
5913 }
5914
5915 /* push keywords in the stack. */
5916 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5917 if (!lua_checkstack(hlua->T, 1)) {
5918 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5919 ctx->rule->arg.hlua_rule->fcn.name);
5920 RESET_SAFE_LJMP(hlua->T);
5921 return 0;
5922 }
5923 lua_pushstring(hlua->T, *arg);
5924 hlua->nargs++;
5925 }
5926
5927 RESET_SAFE_LJMP(hlua->T);
5928
5929 /* Wakeup the applet when data is ready for read. */
5930 si_applet_cant_get(si);
5931
5932 return 1;
5933}
5934
5935static void hlua_applet_http_fct(struct appctx *ctx)
5936{
5937 struct stream_interface *si = ctx->owner;
5938 struct stream *strm = si_strm(si);
5939 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005940 struct act_rule *rule = ctx->rule;
5941 struct proxy *px = strm->be;
5942 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5943 char *blk1;
5944 int len1;
5945 char *blk2;
5946 int len2;
5947 int ret;
5948
5949 /* If the stream is disconnect or closed, ldo nothing. */
5950 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5951 return;
5952
5953 /* Set the currently running flag. */
5954 if (!HLUA_IS_RUNNING(hlua) &&
5955 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
5956
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005957 /* Wait for full HTTP analysys. */
5958 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
5959 si_applet_cant_get(si);
5960 return;
5961 }
5962
5963 /* Store the max amount of bytes that we can read. */
5964 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
5965
5966 /* We need to flush the request header. This left the body
5967 * for the Lua.
5968 */
5969
5970 /* Read the maximum amount of data avalaible. */
5971 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
5972 if (ret == -1)
5973 return;
5974
5975 /* No data available, ask for more data. */
5976 if (ret == 1)
5977 len2 = 0;
5978 if (ret == 0)
5979 len1 = 0;
5980 if (len1 + len2 < strm->txn->req.eoh + 2) {
5981 si_applet_cant_get(si);
5982 return;
5983 }
5984
5985 /* skip the requests bytes. */
5986 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
5987 }
5988
5989 /* Executes The applet if it is not done. */
5990 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
5991
5992 /* Execute the function. */
5993 switch (hlua_ctx_resume(hlua, 1)) {
5994 /* finished. */
5995 case HLUA_E_OK:
5996 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
5997 break;
5998
5999 /* yield. */
6000 case HLUA_E_AGAIN:
6001 return;
6002
6003 /* finished with error. */
6004 case HLUA_E_ERRMSG:
6005 /* Display log. */
6006 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6007 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6008 lua_pop(hlua->T, 1);
6009 goto error;
6010
6011 case HLUA_E_ERR:
6012 /* Display log. */
6013 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6014 rule->arg.hlua_rule->fcn.name);
6015 goto error;
6016
6017 default:
6018 goto error;
6019 }
6020 }
6021
6022 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6023
6024 /* We must send the final chunk. */
6025 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6026 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6027
6028 /* sent last chunk at once. */
6029 ret = bi_putblk(res, "0\r\n\r\n", 5);
6030
6031 /* critical error. */
6032 if (ret == -2 || ret == -3) {
6033 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6034 rule->arg.hlua_rule->fcn.name);
6035 goto error;
6036 }
6037
6038 /* no enough space error. */
6039 if (ret == -1) {
6040 si_applet_cant_put(si);
6041 return;
6042 }
6043
6044 /* set the last chunk sent. */
6045 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6046 }
6047
6048 /* close the connection. */
6049
6050 /* status / log */
6051 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6052 strm->logs.tv_request = now;
6053
6054 /* eat the whole request */
6055 bo_skip(si_oc(si), si_ob(si)->o);
6056 res->flags |= CF_READ_NULL;
6057 si_shutr(si);
6058
6059 return;
6060 }
6061
6062error:
6063
6064 /* If we are in HTTP mode, and we are not send any
6065 * data, return a 500 server error in best effort:
6066 * if there are no room avalaible in the buffer,
6067 * just close the connection.
6068 */
6069 bi_putblk(res, error_500, strlen(error_500));
6070 if (!(strm->flags & SF_ERR_MASK))
6071 strm->flags |= SF_ERR_RESOURCE;
6072 si_shutw(si);
6073 si_shutr(si);
6074 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6075}
6076
6077static void hlua_applet_http_release(struct appctx *ctx)
6078{
6079 task_free(ctx->ctx.hlua_apphttp.task);
6080 ctx->ctx.hlua_apphttp.task = NULL;
6081 hlua_ctx_destroy(&ctx->ctx.hlua_apphttp.hlua);
6082}
6083
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006084/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6085 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006086 *
6087 * This function can fail with an abort() due to an Lua critical error.
6088 * We are in the configuration parsing process of HAProxy, this abort() is
6089 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006090 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006091static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6092 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006093{
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006094 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6095
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006096 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006097 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006098 if (!rule->arg.hlua_rule) {
6099 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006100 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006101 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006102
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006103 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006104 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006105
6106 /* TODO: later accept arguments. */
6107 rule->arg.hlua_rule->args = NULL;
6108
Thierry FOURNIER42148732015-09-02 17:17:33 +02006109 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006110 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006111 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006112}
6113
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006114static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6115 struct act_rule *rule, char **err)
6116{
6117 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6118
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006119 /* HTTP applets are forbidden in tcp-request rules.
6120 * HTTP applet request requires everything initilized by
6121 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6122 * The applet will be immediately initilized, but its before
6123 * the call of this analyzer.
6124 */
6125 if (rule->from != ACT_F_HTTP_REQ) {
6126 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6127 return ACT_RET_PRS_ERR;
6128 }
6129
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006130 /* Memory for the rule. */
6131 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6132 if (!rule->arg.hlua_rule) {
6133 memprintf(err, "out of memory error");
6134 return ACT_RET_PRS_ERR;
6135 }
6136
6137 /* Reference the Lua function and store the reference. */
6138 rule->arg.hlua_rule->fcn = *fcn;
6139
6140 /* TODO: later accept arguments. */
6141 rule->arg.hlua_rule->args = NULL;
6142
6143 /* Add applet pointer in the rule. */
6144 rule->applet.obj_type = OBJ_TYPE_APPLET;
6145 rule->applet.name = fcn->name;
6146 rule->applet.init = hlua_applet_http_init;
6147 rule->applet.fct = hlua_applet_http_fct;
6148 rule->applet.release = hlua_applet_http_release;
6149 rule->applet.timeout = hlua_timeout_applet;
6150
6151 return ACT_RET_PRS_OK;
6152}
6153
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006154/* This function is an LUA binding used for registering
6155 * "sample-conv" functions. It expects a converter name used
6156 * in the haproxy configuration file, and an LUA function.
6157 */
6158__LJMP static int hlua_register_action(lua_State *L)
6159{
6160 struct action_kw_list *akl;
6161 const char *name;
6162 int ref;
6163 int len;
6164 struct hlua_function *fcn;
6165
Thierry FOURNIERed0bdaa2015-12-20 19:51:06 +01006166 MAY_LJMP(check_args(L, 3, "register_action"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006167
6168 /* First argument : converter name. */
6169 name = MAY_LJMP(luaL_checkstring(L, 1));
6170
6171 /* Second argument : environment. */
6172 if (lua_type(L, 2) != LUA_TTABLE)
6173 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6174
6175 /* Third argument : lua function. */
6176 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6177
6178 /* browse the second argulent as an array. */
6179 lua_pushnil(L);
6180 while (lua_next(L, 2) != 0) {
6181 if (lua_type(L, -1) != LUA_TSTRING)
6182 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6183
6184 /* Check required environment. Only accepted "http" or "tcp". */
6185 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006186 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006187 if (!akl)
6188 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006189 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006190 if (!fcn)
6191 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6192
6193 /* Fill fcn. */
6194 fcn->name = strdup(name);
6195 if (!fcn->name)
6196 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6197 fcn->function_ref = ref;
6198
6199 /* List head */
6200 akl->list.n = akl->list.p = NULL;
6201
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006202 /* action keyword. */
6203 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006204 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006205 if (!akl->kw[0].kw)
6206 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6207
6208 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6209
6210 akl->kw[0].match_pfx = 0;
6211 akl->kw[0].private = fcn;
6212 akl->kw[0].parse = action_register_lua;
6213
6214 /* select the action registering point. */
6215 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6216 tcp_req_cont_keywords_register(akl);
6217 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6218 tcp_res_cont_keywords_register(akl);
6219 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6220 http_req_keywords_register(akl);
6221 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6222 http_res_keywords_register(akl);
6223 else
6224 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6225 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6226 "are expected.", lua_tostring(L, -1)));
6227
6228 /* pop the environment string. */
6229 lua_pop(L, 1);
6230 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006231 return ACT_RET_PRS_OK;
6232}
6233
6234static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6235 struct act_rule *rule, char **err)
6236{
6237 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6238
6239 /* Memory for the rule. */
6240 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6241 if (!rule->arg.hlua_rule) {
6242 memprintf(err, "out of memory error");
6243 return ACT_RET_PRS_ERR;
6244 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006245
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006246 /* Reference the Lua function and store the reference. */
6247 rule->arg.hlua_rule->fcn = *fcn;
6248
6249 /* TODO: later accept arguments. */
6250 rule->arg.hlua_rule->args = NULL;
6251
6252 /* Add applet pointer in the rule. */
6253 rule->applet.obj_type = OBJ_TYPE_APPLET;
6254 rule->applet.name = fcn->name;
6255 rule->applet.init = hlua_applet_tcp_init;
6256 rule->applet.fct = hlua_applet_tcp_fct;
6257 rule->applet.release = hlua_applet_tcp_release;
6258 rule->applet.timeout = hlua_timeout_applet;
6259
6260 return 0;
6261}
6262
6263/* This function is an LUA binding used for registering
6264 * "sample-conv" functions. It expects a converter name used
6265 * in the haproxy configuration file, and an LUA function.
6266 */
6267__LJMP static int hlua_register_service(lua_State *L)
6268{
6269 struct action_kw_list *akl;
6270 const char *name;
6271 const char *env;
6272 int ref;
6273 int len;
6274 struct hlua_function *fcn;
6275
6276 MAY_LJMP(check_args(L, 3, "register_service"));
6277
6278 /* First argument : converter name. */
6279 name = MAY_LJMP(luaL_checkstring(L, 1));
6280
6281 /* Second argument : environment. */
6282 env = MAY_LJMP(luaL_checkstring(L, 2));
6283
6284 /* Third argument : lua function. */
6285 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6286
6287 /* Check required environment. Only accepted "http" or "tcp". */
6288 /* Allocate and fill the sample fetch keyword struct. */
6289 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6290 if (!akl)
6291 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6292 fcn = calloc(1, sizeof(*fcn));
6293 if (!fcn)
6294 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6295
6296 /* Fill fcn. */
6297 len = strlen("<lua.>") + strlen(name) + 1;
6298 fcn->name = calloc(1, len);
6299 if (!fcn->name)
6300 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6301 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6302 fcn->function_ref = ref;
6303
6304 /* List head */
6305 akl->list.n = akl->list.p = NULL;
6306
6307 /* converter keyword. */
6308 len = strlen("lua.") + strlen(name) + 1;
6309 akl->kw[0].kw = calloc(1, len);
6310 if (!akl->kw[0].kw)
6311 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6312
6313 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6314
6315 if (strcmp(env, "tcp") == 0)
6316 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006317 else if (strcmp(env, "http") == 0)
6318 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006319 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006320 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6321 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006322
6323 akl->kw[0].match_pfx = 0;
6324 akl->kw[0].private = fcn;
6325
6326 /* End of array. */
6327 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6328
6329 /* Register this new converter */
6330 service_keywords_register(akl);
6331
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006332 return 0;
6333}
6334
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006335static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
6336 struct proxy *defpx, const char *file, int line,
6337 char **err, unsigned int *timeout)
6338{
6339 const char *error;
6340
6341 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
6342 if (error && *error != '\0') {
6343 memprintf(err, "%s: invalid timeout", args[0]);
6344 return -1;
6345 }
6346 return 0;
6347}
6348
6349static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
6350 struct proxy *defpx, const char *file, int line,
6351 char **err)
6352{
6353 return hlua_read_timeout(args, section_type, curpx, defpx,
6354 file, line, err, &hlua_timeout_session);
6355}
6356
6357static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
6358 struct proxy *defpx, const char *file, int line,
6359 char **err)
6360{
6361 return hlua_read_timeout(args, section_type, curpx, defpx,
6362 file, line, err, &hlua_timeout_task);
6363}
6364
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006365static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
6366 struct proxy *defpx, const char *file, int line,
6367 char **err)
6368{
6369 return hlua_read_timeout(args, section_type, curpx, defpx,
6370 file, line, err, &hlua_timeout_applet);
6371}
6372
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006373static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
6374 struct proxy *defpx, const char *file, int line,
6375 char **err)
6376{
6377 char *error;
6378
6379 hlua_nb_instruction = strtoll(args[1], &error, 10);
6380 if (*error != '\0') {
6381 memprintf(err, "%s: invalid number", args[0]);
6382 return -1;
6383 }
6384 return 0;
6385}
6386
Willy Tarreau32f61e22015-03-18 17:54:59 +01006387static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
6388 struct proxy *defpx, const char *file, int line,
6389 char **err)
6390{
6391 char *error;
6392
6393 if (*(args[1]) == 0) {
6394 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
6395 return -1;
6396 }
6397 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
6398 if (*error != '\0') {
6399 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
6400 return -1;
6401 }
6402 return 0;
6403}
6404
6405
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006406/* This function is called by the main configuration key "lua-load". It loads and
6407 * execute an lua file during the parsing of the HAProxy configuration file. It is
6408 * the main lua entry point.
6409 *
6410 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
6411 * occured, otherwise it returns 0.
6412 *
6413 * In some error case, LUA set an error message in top of the stack. This function
6414 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006415 *
6416 * This function can fail with an abort() due to an Lua critical error.
6417 * We are in the configuration parsing process of HAProxy, this abort() is
6418 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006419 */
6420static int hlua_load(char **args, int section_type, struct proxy *curpx,
6421 struct proxy *defpx, const char *file, int line,
6422 char **err)
6423{
6424 int error;
6425
6426 /* Just load and compile the file. */
6427 error = luaL_loadfile(gL.T, args[1]);
6428 if (error) {
6429 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
6430 lua_pop(gL.T, 1);
6431 return -1;
6432 }
6433
6434 /* If no syntax error where detected, execute the code. */
6435 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
6436 switch (error) {
6437 case LUA_OK:
6438 break;
6439 case LUA_ERRRUN:
6440 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
6441 lua_pop(gL.T, 1);
6442 return -1;
6443 case LUA_ERRMEM:
6444 memprintf(err, "lua out of memory error\n");
6445 return -1;
6446 case LUA_ERRERR:
6447 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
6448 lua_pop(gL.T, 1);
6449 return -1;
6450 case LUA_ERRGCMM:
6451 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
6452 lua_pop(gL.T, 1);
6453 return -1;
6454 default:
6455 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
6456 lua_pop(gL.T, 1);
6457 return -1;
6458 }
6459
6460 return 0;
6461}
6462
6463/* configuration keywords declaration */
6464static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006465 { CFG_GLOBAL, "lua-load", hlua_load },
6466 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
6467 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02006468 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006469 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01006470 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006471 { 0, NULL, NULL },
6472}};
6473
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006474/* This function can fail with an abort() due to an Lua critical error.
6475 * We are in the initialisation process of HAProxy, this abort() is
6476 * tolerated.
6477 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006478int hlua_post_init()
6479{
6480 struct hlua_init_function *init;
6481 const char *msg;
6482 enum hlua_exec ret;
6483
6484 list_for_each_entry(init, &hlua_init_functions, l) {
6485 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
6486 ret = hlua_ctx_resume(&gL, 0);
6487 switch (ret) {
6488 case HLUA_E_OK:
6489 lua_pop(gL.T, -1);
6490 return 1;
6491 case HLUA_E_AGAIN:
6492 Alert("lua init: yield not allowed.\n");
6493 return 0;
6494 case HLUA_E_ERRMSG:
6495 msg = lua_tostring(gL.T, -1);
6496 Alert("lua init: %s.\n", msg);
6497 return 0;
6498 case HLUA_E_ERR:
6499 default:
6500 Alert("lua init: unknown runtime error.\n");
6501 return 0;
6502 }
6503 }
6504 return 1;
6505}
6506
Willy Tarreau32f61e22015-03-18 17:54:59 +01006507/* The memory allocator used by the Lua stack. <ud> is a pointer to the
6508 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
6509 * is the previously allocated size or the kind of object in case of a new
6510 * allocation. <nsize> is the requested new size.
6511 */
6512static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
6513{
6514 struct hlua_mem_allocator *zone = ud;
6515
6516 if (nsize == 0) {
6517 /* it's a free */
6518 if (ptr)
6519 zone->allocated -= osize;
6520 free(ptr);
6521 return NULL;
6522 }
6523
6524 if (!ptr) {
6525 /* it's a new allocation */
6526 if (zone->limit && zone->allocated + nsize > zone->limit)
6527 return NULL;
6528
6529 ptr = malloc(nsize);
6530 if (ptr)
6531 zone->allocated += nsize;
6532 return ptr;
6533 }
6534
6535 /* it's a realloc */
6536 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
6537 return NULL;
6538
6539 ptr = realloc(ptr, nsize);
6540 if (ptr)
6541 zone->allocated += nsize - osize;
6542 return ptr;
6543}
6544
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006545/* Ithis function can fail with an abort() due to an Lua critical error.
6546 * We are in the initialisation process of HAProxy, this abort() is
6547 * tolerated.
6548 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01006549void hlua_init(void)
6550{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006551 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006552 int idx;
6553 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006554 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006555 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006556#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006557 struct srv_kw *kw;
6558 int tmp_error;
6559 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01006560 char *args[] = { /* SSL client configuration. */
6561 "ssl",
6562 "verify",
6563 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01006564 NULL
6565 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006566#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006567
Willy Tarreau87b09662015-04-03 00:22:06 +02006568 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006569 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
6570
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006571 /* Register configuration keywords. */
6572 cfg_register_keywords(&cfg_kws);
6573
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006574 /* Init main lua stack. */
6575 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01006576 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006577 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006578 gL.T = luaL_newstate();
6579 hlua_sethlua(&gL);
6580 gL.Tref = LUA_REFNIL;
6581 gL.task = NULL;
6582
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006583 /* From this point, until the end of the initialisation fucntion,
6584 * the Lua function can fail with an abort. We are in the initialisation
6585 * process of HAProxy, this abort() is tolerated.
6586 */
6587
Willy Tarreau32f61e22015-03-18 17:54:59 +01006588 /* change the memory allocators to track memory usage */
6589 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
6590
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006591 /* Initialise lua. */
6592 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006593
6594 /*
6595 *
6596 * Create "core" object.
6597 *
6598 */
6599
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01006600 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006601 lua_newtable(gL.T);
6602
6603 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006604 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006605 hlua_class_const_int(gL.T, log_levels[i], i);
6606
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006607 /* Register special functions. */
6608 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006609 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006610 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006611 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006612 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006613 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006614 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01006615 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006616 hlua_class_function(gL.T, "sleep", hlua_sleep);
6617 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01006618 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
6619 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
6620 hlua_class_function(gL.T, "set_map", hlua_set_map);
6621 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006622 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006623 hlua_class_function(gL.T, "log", hlua_log);
6624 hlua_class_function(gL.T, "Debug", hlua_log_debug);
6625 hlua_class_function(gL.T, "Info", hlua_log_info);
6626 hlua_class_function(gL.T, "Warning", hlua_log_warning);
6627 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02006628 hlua_class_function(gL.T, "done", hlua_done);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006629
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006630 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006631
6632 /*
6633 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006634 * Register class Map
6635 *
6636 */
6637
6638 /* This table entry is the object "Map" base. */
6639 lua_newtable(gL.T);
6640
6641 /* register pattern types. */
6642 for (i=0; i<PAT_MATCH_NUM; i++)
6643 hlua_class_const_int(gL.T, pat_match_names[i], i);
6644
6645 /* register constructor. */
6646 hlua_class_function(gL.T, "new", hlua_map_new);
6647
6648 /* Create and fill the metatable. */
6649 lua_newtable(gL.T);
6650
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006651 /* Create the __tostring identifier */
6652 lua_pushstring(gL.T, "__tostring");
6653 lua_pushstring(gL.T, CLASS_MAP);
6654 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6655 lua_rawset(gL.T, -3);
6656
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006657 /* Create and fille the __index entry. */
6658 lua_pushstring(gL.T, "__index");
6659 lua_newtable(gL.T);
6660
6661 /* Register . */
6662 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
6663 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
6664
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006665 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006666
6667 /* Register previous table in the registry with reference and named entry. */
6668 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6669 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6670 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
6671 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6672
6673 /* Assign the metatable to the mai Map object. */
6674 lua_setmetatable(gL.T, -2);
6675
6676 /* Set a name to the table. */
6677 lua_setglobal(gL.T, "Map");
6678
6679 /*
6680 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006681 * Register class Channel
6682 *
6683 */
6684
6685 /* Create and fill the metatable. */
6686 lua_newtable(gL.T);
6687
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006688 /* Create the __tostring identifier */
6689 lua_pushstring(gL.T, "__tostring");
6690 lua_pushstring(gL.T, CLASS_CHANNEL);
6691 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6692 lua_rawset(gL.T, -3);
6693
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006694 /* Create and fille the __index entry. */
6695 lua_pushstring(gL.T, "__index");
6696 lua_newtable(gL.T);
6697
6698 /* Register . */
6699 hlua_class_function(gL.T, "get", hlua_channel_get);
6700 hlua_class_function(gL.T, "dup", hlua_channel_dup);
6701 hlua_class_function(gL.T, "getline", hlua_channel_getline);
6702 hlua_class_function(gL.T, "set", hlua_channel_set);
6703 hlua_class_function(gL.T, "append", hlua_channel_append);
6704 hlua_class_function(gL.T, "send", hlua_channel_send);
6705 hlua_class_function(gL.T, "forward", hlua_channel_forward);
6706 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
6707 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
6708
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006709 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006710
6711 /* Register previous table in the registry with reference and named entry. */
6712 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6713 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
6714 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6715
6716 /*
6717 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006718 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006719 *
6720 */
6721
6722 /* Create and fill the metatable. */
6723 lua_newtable(gL.T);
6724
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006725 /* Create the __tostring identifier */
6726 lua_pushstring(gL.T, "__tostring");
6727 lua_pushstring(gL.T, CLASS_FETCHES);
6728 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6729 lua_rawset(gL.T, -3);
6730
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006731 /* Create and fille the __index entry. */
6732 lua_pushstring(gL.T, "__index");
6733 lua_newtable(gL.T);
6734
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006735 /* Browse existing fetches and create the associated
6736 * object method.
6737 */
6738 sf = NULL;
6739 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
6740
6741 /* Dont register the keywork if the arguments check function are
6742 * not safe during the runtime.
6743 */
6744 if ((sf->val_args != NULL) &&
6745 (sf->val_args != val_payload_lv) &&
6746 (sf->val_args != val_hdr))
6747 continue;
6748
6749 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
6750 * by an underscore.
6751 */
6752 strncpy(trash.str, sf->kw, trash.size);
6753 trash.str[trash.size - 1] = '\0';
6754 for (p = trash.str; *p; p++)
6755 if (*p == '.' || *p == '-' || *p == '+')
6756 *p = '_';
6757
6758 /* Register the function. */
6759 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01006760 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006761 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006762 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006763 }
6764
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006765 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006766
6767 /* Register previous table in the registry with reference and named entry. */
6768 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6769 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
6770 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6771
6772 /*
6773 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006774 * Register class Converters
6775 *
6776 */
6777
6778 /* Create and fill the metatable. */
6779 lua_newtable(gL.T);
6780
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006781 /* Create the __tostring identifier */
6782 lua_pushstring(gL.T, "__tostring");
6783 lua_pushstring(gL.T, CLASS_CONVERTERS);
6784 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6785 lua_rawset(gL.T, -3);
6786
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006787 /* Create and fill the __index entry. */
6788 lua_pushstring(gL.T, "__index");
6789 lua_newtable(gL.T);
6790
6791 /* Browse existing converters and create the associated
6792 * object method.
6793 */
6794 sc = NULL;
6795 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
6796 /* Dont register the keywork if the arguments check function are
6797 * not safe during the runtime.
6798 */
6799 if (sc->val_args != NULL)
6800 continue;
6801
6802 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
6803 * by an underscore.
6804 */
6805 strncpy(trash.str, sc->kw, trash.size);
6806 trash.str[trash.size - 1] = '\0';
6807 for (p = trash.str; *p; p++)
6808 if (*p == '.' || *p == '-' || *p == '+')
6809 *p = '_';
6810
6811 /* Register the function. */
6812 lua_pushstring(gL.T, trash.str);
6813 lua_pushlightuserdata(gL.T, sc);
6814 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006815 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006816 }
6817
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006818 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006819
6820 /* Register previous table in the registry with reference and named entry. */
6821 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6822 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
6823 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6824
6825 /*
6826 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006827 * Register class HTTP
6828 *
6829 */
6830
6831 /* Create and fill the metatable. */
6832 lua_newtable(gL.T);
6833
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006834 /* Create the __tostring identifier */
6835 lua_pushstring(gL.T, "__tostring");
6836 lua_pushstring(gL.T, CLASS_HTTP);
6837 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6838 lua_rawset(gL.T, -3);
6839
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006840 /* Create and fille the __index entry. */
6841 lua_pushstring(gL.T, "__index");
6842 lua_newtable(gL.T);
6843
6844 /* Register Lua functions. */
6845 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
6846 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
6847 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
6848 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
6849 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
6850 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
6851 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
6852 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
6853 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
6854 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
6855
6856 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
6857 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
6858 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
6859 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
6860 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
6861 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006862 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006863
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006864 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006865
6866 /* Register previous table in the registry with reference and named entry. */
6867 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6868 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
6869 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6870
6871 /*
6872 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006873 * Register class AppletTCP
6874 *
6875 */
6876
6877 /* Create and fill the metatable. */
6878 lua_newtable(gL.T);
6879
6880 /* Create the __tostring identifier */
6881 lua_pushstring(gL.T, "__tostring");
6882 lua_pushstring(gL.T, CLASS_APPLET_TCP);
6883 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6884 lua_rawset(gL.T, -3);
6885
6886 /* Create and fille the __index entry. */
6887 lua_pushstring(gL.T, "__index");
6888 lua_newtable(gL.T);
6889
6890 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01006891 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
6892 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
6893 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
6894 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
6895 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006896
6897 lua_settable(gL.T, -3);
6898
6899 /* Register previous table in the registry with reference and named entry. */
6900 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6901 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_APPLET_TCP); /* register class session. */
6902 class_applet_tcp_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6903
6904 /*
6905 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006906 * Register class AppletHTTP
6907 *
6908 */
6909
6910 /* Create and fill the metatable. */
6911 lua_newtable(gL.T);
6912
6913 /* Create the __tostring identifier */
6914 lua_pushstring(gL.T, "__tostring");
6915 lua_pushstring(gL.T, CLASS_APPLET_HTTP);
6916 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6917 lua_rawset(gL.T, -3);
6918
6919 /* Create and fille the __index entry. */
6920 lua_pushstring(gL.T, "__index");
6921 lua_newtable(gL.T);
6922
6923 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01006924 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
6925 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006926 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
6927 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
6928 hlua_class_function(gL.T, "send", hlua_applet_http_send);
6929 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
6930 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
6931 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
6932
6933 lua_settable(gL.T, -3);
6934
6935 /* Register previous table in the registry with reference and named entry. */
6936 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6937 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_APPLET_HTTP); /* register class session. */
6938 class_applet_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6939
6940 /*
6941 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006942 * Register class TXN
6943 *
6944 */
6945
6946 /* Create and fill the metatable. */
6947 lua_newtable(gL.T);
6948
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006949 /* Create the __tostring identifier */
6950 lua_pushstring(gL.T, "__tostring");
6951 lua_pushstring(gL.T, CLASS_TXN);
6952 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6953 lua_rawset(gL.T, -3);
6954
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006955 /* Create and fille the __index entry. */
6956 lua_pushstring(gL.T, "__index");
6957 lua_newtable(gL.T);
6958
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006959 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01006960 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
6961 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006962 hlua_class_function(gL.T, "set_var", hlua_set_var);
6963 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006964 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006965 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
6966 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
6967 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006968 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
6969 hlua_class_function(gL.T, "log", hlua_txn_log);
6970 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
6971 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
6972 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
6973 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006974
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006975 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006976
6977 /* Register previous table in the registry with reference and named entry. */
6978 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6979 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
6980 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006981
6982 /*
6983 *
6984 * Register class Socket
6985 *
6986 */
6987
6988 /* Create and fill the metatable. */
6989 lua_newtable(gL.T);
6990
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006991 /* Create the __tostring identifier */
6992 lua_pushstring(gL.T, "__tostring");
6993 lua_pushstring(gL.T, CLASS_SOCKET);
6994 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6995 lua_rawset(gL.T, -3);
6996
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006997 /* Create and fille the __index entry. */
6998 lua_pushstring(gL.T, "__index");
6999 lua_newtable(gL.T);
7000
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007001#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007002 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007003#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007004 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7005 hlua_class_function(gL.T, "send", hlua_socket_send);
7006 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7007 hlua_class_function(gL.T, "close", hlua_socket_close);
7008 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7009 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7010 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7011 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7012
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007013 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007014
7015 /* Register the garbage collector entry. */
7016 lua_pushstring(gL.T, "__gc");
7017 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007018 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007019
7020 /* Register previous table in the registry with reference and named entry. */
7021 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
7022 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
7023 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
7024 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
7025
7026 /* Proxy and server configuration initialisation. */
7027 memset(&socket_proxy, 0, sizeof(socket_proxy));
7028 init_new_proxy(&socket_proxy);
7029 socket_proxy.parent = NULL;
7030 socket_proxy.last_change = now.tv_sec;
7031 socket_proxy.id = "LUA-SOCKET";
7032 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7033 socket_proxy.maxconn = 0;
7034 socket_proxy.accept = NULL;
7035 socket_proxy.options2 |= PR_O2_INDEPSTR;
7036 socket_proxy.srv = NULL;
7037 socket_proxy.conn_retries = 0;
7038 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7039
7040 /* Init TCP server: unchanged parameters */
7041 memset(&socket_tcp, 0, sizeof(socket_tcp));
7042 socket_tcp.next = NULL;
7043 socket_tcp.proxy = &socket_proxy;
7044 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7045 LIST_INIT(&socket_tcp.actconns);
7046 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007047 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007048 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007049 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007050 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
7051 socket_tcp.last_change = 0;
7052 socket_tcp.id = "LUA-TCP-CONN";
7053 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7054 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7055 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7056
7057 /* XXX: Copy default parameter from default server,
7058 * but the default server is not initialized.
7059 */
7060 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7061 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7062 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7063 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7064 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7065 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7066 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7067 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7068 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7069 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7070
7071 socket_tcp.check.status = HCHK_STATUS_INI;
7072 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7073 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7074 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7075 socket_tcp.check.server = &socket_tcp;
7076
7077 socket_tcp.agent.status = HCHK_STATUS_INI;
7078 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7079 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7080 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7081 socket_tcp.agent.server = &socket_tcp;
7082
7083 socket_tcp.xprt = &raw_sock;
7084
7085#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007086 /* Init TCP server: unchanged parameters */
7087 memset(&socket_ssl, 0, sizeof(socket_ssl));
7088 socket_ssl.next = NULL;
7089 socket_ssl.proxy = &socket_proxy;
7090 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7091 LIST_INIT(&socket_ssl.actconns);
7092 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007093 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007094 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007095 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007096 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
7097 socket_ssl.last_change = 0;
7098 socket_ssl.id = "LUA-SSL-CONN";
7099 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7100 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7101 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7102
7103 /* XXX: Copy default parameter from default server,
7104 * but the default server is not initialized.
7105 */
7106 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7107 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7108 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7109 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7110 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7111 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7112 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7113 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7114 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7115 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7116
7117 socket_ssl.check.status = HCHK_STATUS_INI;
7118 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7119 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7120 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7121 socket_ssl.check.server = &socket_ssl;
7122
7123 socket_ssl.agent.status = HCHK_STATUS_INI;
7124 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7125 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7126 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7127 socket_ssl.agent.server = &socket_ssl;
7128
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007129 socket_ssl.use_ssl = 1;
7130 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007131
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007132 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007133 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7134 /*
7135 *
7136 * If the keyword is not known, we can search in the registered
7137 * server keywords. This is usefull to configure special SSL
7138 * features like client certificates and ssl_verify.
7139 *
7140 */
7141 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7142 if (tmp_error != 0) {
7143 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7144 abort(); /* This must be never arrives because the command line
7145 not editable by the user. */
7146 }
7147 idx += kw->skip;
7148 }
7149 }
7150
7151 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007152 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007153#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007154}