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