blob: d70b01b6cafe2405490a423d5af21132eba13dbd [file] [log] [blame]
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001#include <sys/socket.h>
2
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01006#include <lauxlib.h>
7#include <lua.h>
8#include <lualib.h>
9
Thierry FOURNIER463119c2015-03-10 00:35:36 +010010#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
11#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010012#endif
13
Thierry FOURNIER380d0932015-01-23 14:27:52 +010014#include <ebpttree.h>
15
16#include <common/cfgparse.h>
17
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010018#include <types/connection.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010019#include <types/hlua.h>
20#include <types/proxy.h>
21
Thierry FOURNIER55da1652015-01-23 11:36:30 +010022#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020023#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010024#include <proto/channel.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010025#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010026#include <proto/hlua.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020027#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010028#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010029#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010030#include <proto/payload.h>
31#include <proto/proto_http.h>
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010032#include <proto/proto_tcp.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010033#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010034#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010035#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020036#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020037#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010038#include <proto/ssl_sock.h>
39#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010040#include <proto/task.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020041#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010042
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010043/* Lua uses longjmp to perform yield or throwing errors. This
44 * macro is used only for identifying the function that can
45 * not return because a longjmp is executed.
46 * __LJMP marks a prototype of hlua file that can use longjmp.
47 * WILL_LJMP() marks an lua function that will use longjmp.
48 * MAY_LJMP() marks an lua function that may use longjmp.
49 */
50#define __LJMP
51#define WILL_LJMP(func) func
52#define MAY_LJMP(func) func
53
Thierry FOURNIERbabae282015-09-17 11:36:37 +020054/* This couple of function executes securely some Lua calls outside of
55 * the lua runtime environment. Each Lua call can return a longjmp
56 * if it encounter a memory error.
57 *
58 * Lua documentation extract:
59 *
60 * If an error happens outside any protected environment, Lua calls
61 * a panic function (see lua_atpanic) and then calls abort, thus
62 * exiting the host application. Your panic function can avoid this
63 * exit by never returning (e.g., doing a long jump to your own
64 * recovery point outside Lua).
65 *
66 * The panic function runs as if it were a message handler (see
67 * §2.3); in particular, the error message is at the top of the
68 * stack. However, there is no guarantee about stack space. To push
69 * anything on the stack, the panic function must first check the
70 * available space (see §4.2).
71 *
72 * We must check all the Lua entry point. This includes:
73 * - The include/proto/hlua.h exported functions
74 * - the task wrapper function
75 * - The action wrapper function
76 * - The converters wrapper function
77 * - The sample-fetch wrapper functions
78 *
79 * It is tolerated that the initilisation function returns an abort.
80 * Before each Lua abort, an error message is writed on stderr.
81 *
82 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
83 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
84 * because they must be exists in the program stack when the longjmp
85 * is called.
86 */
87jmp_buf safe_ljmp_env;
88static int hlua_panic_safe(lua_State *L) { return 0; }
89static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
90
91#define SET_SAFE_LJMP(__L) \
92 ({ \
93 int ret; \
94 if (setjmp(safe_ljmp_env) != 0) { \
95 lua_atpanic(__L, hlua_panic_safe); \
96 ret = 0; \
97 } else { \
98 lua_atpanic(__L, hlua_panic_ljmp); \
99 ret = 1; \
100 } \
101 ret; \
102 })
103
104/* If we are the last function catching Lua errors, we
105 * must reset the panic function.
106 */
107#define RESET_SAFE_LJMP(__L) \
108 do { \
109 lua_atpanic(__L, hlua_panic_safe); \
110 } while(0)
111
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200112/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200113#define APPLET_DONE 0x01 /* applet processing is done. */
114#define APPLET_100C 0x02 /* 100 continue expected. */
115#define APPLET_HDR_SENT 0x04 /* Response header sent. */
116#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
117#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100118#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200119
120#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200121
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100122/* The main Lua execution context. */
123struct hlua gL;
124
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100125/* This is the memory pool containing all the signal structs. These
126 * struct are used to store each requiered signal between two tasks.
127 */
128struct pool_head *pool2_hlua_com;
129
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100130/* Used for Socket connection. */
131static struct proxy socket_proxy;
132static struct server socket_tcp;
133#ifdef USE_OPENSSL
134static struct server socket_ssl;
135#endif
136
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100137/* List head of the function called at the initialisation time. */
138struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
139
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100140/* The following variables contains the reference of the different
141 * Lua classes. These references are useful for identify metadata
142 * associated with an object.
143 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100144static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100145static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100146static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100147static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100148static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100149static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200150static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200151static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200152static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100153
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100154/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200155 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100156 * short timeout. Lua linked with tasks doesn't have a timeout
157 * because a task may remain alive during all the haproxy execution.
158 */
159static unsigned int hlua_timeout_session = 4000; /* session timeout. */
160static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200161static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100162
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100163/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
164 * it is used for preventing infinite loops.
165 *
166 * I test the scheer with an infinite loop containing one incrementation
167 * and one test. I run this loop between 10 seconds, I raise a ceil of
168 * 710M loops from one interrupt each 9000 instructions, so I fix the value
169 * to one interrupt each 10 000 instructions.
170 *
171 * configured | Number of
172 * instructions | loops executed
173 * between two | in milions
174 * forced yields |
175 * ---------------+---------------
176 * 10 | 160
177 * 500 | 670
178 * 1000 | 680
179 * 5000 | 700
180 * 7000 | 700
181 * 8000 | 700
182 * 9000 | 710 <- ceil
183 * 10000 | 710
184 * 100000 | 710
185 * 1000000 | 710
186 *
187 */
188static unsigned int hlua_nb_instruction = 10000;
189
Willy Tarreau32f61e22015-03-18 17:54:59 +0100190/* Descriptor for the memory allocation state. If limit is not null, it will
191 * be enforced on any memory allocation.
192 */
193struct hlua_mem_allocator {
194 size_t allocated;
195 size_t limit;
196};
197
198static struct hlua_mem_allocator hlua_global_allocator;
199
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200200static const char error_500[] =
201 "HTTP/1.0 500 Server Error\r\n"
202 "Cache-Control: no-cache\r\n"
203 "Connection: close\r\n"
204 "Content-Type: text/html\r\n"
205 "\r\n"
206 "<html><body><h1>500 Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
207
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100208/* These functions converts types between HAProxy internal args or
209 * sample and LUA types. Another function permits to check if the
210 * LUA stack contains arguments according with an required ARG_T
211 * format.
212 */
213static int hlua_arg2lua(lua_State *L, const struct arg *arg);
214static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100215__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
216 unsigned int mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100217static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100218static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100219static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
220
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200221__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
222
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200223#define SEND_ERR(__be, __fmt, __args...) \
224 do { \
225 send_log(__be, LOG_ERR, __fmt, ## __args); \
226 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
227 Alert(__fmt, ## __args); \
228 } while (0)
229
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100230/* Used to check an Lua function type in the stack. It creates and
231 * returns a reference of the function. This function throws an
232 * error if the rgument is not a "function".
233 */
234__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
235{
236 if (!lua_isfunction(L, argno)) {
237 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
238 WILL_LJMP(luaL_argerror(L, argno, msg));
239 }
240 lua_pushvalue(L, argno);
241 return luaL_ref(L, LUA_REGISTRYINDEX);
242}
243
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200244/* Return the string that is of the top of the stack. */
245const char *hlua_get_top_error_string(lua_State *L)
246{
247 if (lua_gettop(L) < 1)
248 return "unknown error";
249 if (lua_type(L, -1) != LUA_TSTRING)
250 return "unknown error";
251 return lua_tostring(L, -1);
252}
253
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100254/* The three following functions are useful for adding entries
255 * in a table. These functions takes a string and respectively an
256 * integer, a string or a function and add it to the table in the
257 * top of the stack.
258 *
259 * These functions throws an error if no more stack size is
260 * available.
261 */
262__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100263 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100264{
265 if (!lua_checkstack(L, 2))
266 WILL_LJMP(luaL_error(L, "full stack"));
267 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100268 lua_pushinteger(L, value);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200269 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100270}
271__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
272 const char *value)
273{
274 if (!lua_checkstack(L, 2))
275 WILL_LJMP(luaL_error(L, "full stack"));
276 lua_pushstring(L, name);
277 lua_pushstring(L, value);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200278 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100279}
280__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
281 int (*function)(lua_State *L))
282{
283 if (!lua_checkstack(L, 2))
284 WILL_LJMP(luaL_error(L, "full stack"));
285 lua_pushstring(L, name);
286 lua_pushcclosure(L, function, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200287 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100288}
289
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +0200290__LJMP static int hlua_dump_object(struct lua_State *L)
291{
292 const char *name = (const char *)lua_tostring(L, lua_upvalueindex(1));
293 lua_pushfstring(L, "HAProxy class %s", name);
294 return 1;
295}
296
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100297/* This function check the number of arguments available in the
298 * stack. If the number of arguments available is not the same
299 * then <nb> an error is throwed.
300 */
301__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
302{
303 if (lua_gettop(L) == nb)
304 return;
305 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
306}
307
308/* Return true if the data in stack[<ud>] is an object of
309 * type <class_ref>.
310 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100311static int hlua_metaistype(lua_State *L, int ud, int class_ref)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100312{
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100313 if (!lua_getmetatable(L, ud))
314 return 0;
315
316 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
317 if (!lua_rawequal(L, -1, -2)) {
318 lua_pop(L, 2);
319 return 0;
320 }
321
322 lua_pop(L, 2);
323 return 1;
324}
325
326/* Return an object of the expected type, or throws an error. */
327__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
328{
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100329 void *p;
330
331 /* Check if the stack entry is an array. */
332 if (!lua_istable(L, ud))
333 WILL_LJMP(luaL_argerror(L, ud, NULL));
334 /* Check if the metadata have the expected type. */
335 if (!hlua_metaistype(L, ud, class_ref))
336 WILL_LJMP(luaL_argerror(L, ud, NULL));
337 /* Push on the stack at the entry [0] of the table. */
338 lua_rawgeti(L, ud, 0);
339 /* Check if this entry is userdata. */
340 p = lua_touserdata(L, -1);
341 if (!p)
342 WILL_LJMP(luaL_argerror(L, ud, NULL));
343 /* Remove the entry returned by lua_rawgeti(). */
344 lua_pop(L, 1);
345 /* Return the associated struct. */
346 return p;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100347}
348
349/* This fucntion push an error string prefixed by the file name
350 * and the line number where the error is encountered.
351 */
352static int hlua_pusherror(lua_State *L, const char *fmt, ...)
353{
354 va_list argp;
355 va_start(argp, fmt);
356 luaL_where(L, 1);
357 lua_pushvfstring(L, fmt, argp);
358 va_end(argp);
359 lua_concat(L, 2);
360 return 1;
361}
362
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100363/* This function register a new signal. "lua" is the current lua
364 * execution context. It contains a pointer to the associated task.
365 * "link" is a list head attached to an other task that must be wake
366 * the lua task if an event occurs. This is useful with external
367 * events like TCP I/O or sleep functions. This funcion allocate
368 * memory for the signal.
369 */
370static int hlua_com_new(struct hlua *lua, struct list *link)
371{
372 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
373 if (!com)
374 return 0;
375 LIST_ADDQ(&lua->com, &com->purge_me);
376 LIST_ADDQ(link, &com->wake_me);
377 com->task = lua->task;
378 return 1;
379}
380
381/* This function purge all the pending signals when the LUA execution
382 * is finished. This prevent than a coprocess try to wake a deleted
383 * task. This function remove the memory associated to the signal.
384 */
385static void hlua_com_purge(struct hlua *lua)
386{
387 struct hlua_com *com, *back;
388
389 /* Delete all pending communication signals. */
390 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
391 LIST_DEL(&com->purge_me);
392 LIST_DEL(&com->wake_me);
393 pool_free2(pool2_hlua_com, com);
394 }
395}
396
397/* This function sends signals. It wakes all the tasks attached
398 * to a list head, and remove the signal, and free the used
399 * memory.
400 */
401static void hlua_com_wake(struct list *wake)
402{
403 struct hlua_com *com, *back;
404
405 /* Wake task and delete all pending communication signals. */
406 list_for_each_entry_safe(com, back, wake, wake_me) {
407 LIST_DEL(&com->purge_me);
408 LIST_DEL(&com->wake_me);
409 task_wakeup(com->task, TASK_WOKEN_MSG);
410 pool_free2(pool2_hlua_com, com);
411 }
412}
413
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100414/* This functions is used with sample fetch and converters. It
415 * converts the HAProxy configuration argument in a lua stack
416 * values.
417 *
418 * It takes an array of "arg", and each entry of the array is
419 * converted and pushed in the LUA stack.
420 */
421static int hlua_arg2lua(lua_State *L, const struct arg *arg)
422{
423 switch (arg->type) {
424 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100425 case ARGT_TIME:
426 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100427 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100428 break;
429
430 case ARGT_STR:
431 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
432 break;
433
434 case ARGT_IPV4:
435 case ARGT_IPV6:
436 case ARGT_MSK4:
437 case ARGT_MSK6:
438 case ARGT_FE:
439 case ARGT_BE:
440 case ARGT_TAB:
441 case ARGT_SRV:
442 case ARGT_USR:
443 case ARGT_MAP:
444 default:
445 lua_pushnil(L);
446 break;
447 }
448 return 1;
449}
450
451/* This function take one entrie in an LUA stack at the index "ud",
452 * and try to convert it in an HAProxy argument entry. This is useful
453 * with sample fetch wrappers. The input arguments are gived to the
454 * lua wrapper and converted as arg list by thi function.
455 */
456static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
457{
458 switch (lua_type(L, ud)) {
459
460 case LUA_TNUMBER:
461 case LUA_TBOOLEAN:
462 arg->type = ARGT_SINT;
463 arg->data.sint = lua_tointeger(L, ud);
464 break;
465
466 case LUA_TSTRING:
467 arg->type = ARGT_STR;
468 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
469 break;
470
471 case LUA_TUSERDATA:
472 case LUA_TNIL:
473 case LUA_TTABLE:
474 case LUA_TFUNCTION:
475 case LUA_TTHREAD:
476 case LUA_TLIGHTUSERDATA:
477 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200478 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100479 break;
480 }
481 return 1;
482}
483
484/* the following functions are used to convert a struct sample
485 * in Lua type. This useful to convert the return of the
486 * fetchs or converters.
487 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100488static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100489{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200490 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100491 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100492 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200493 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100494 break;
495
496 case SMP_T_BIN:
497 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200498 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100499 break;
500
501 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200502 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100503 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
504 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
505 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
506 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
507 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
508 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
509 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
510 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
511 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200512 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100513 break;
514 default:
515 lua_pushnil(L);
516 break;
517 }
518 break;
519
520 case SMP_T_IPV4:
521 case SMP_T_IPV6:
522 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200523 if (sample_casts[smp->data.type][SMP_T_STR] &&
524 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200525 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100526 else
527 lua_pushnil(L);
528 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100529 default:
530 lua_pushnil(L);
531 break;
532 }
533 return 1;
534}
535
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100536/* the following functions are used to convert a struct sample
537 * in Lua strings. This is useful to convert the return of the
538 * fetchs or converters.
539 */
540static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
541{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200542 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100543
544 case SMP_T_BIN:
545 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200546 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100547 break;
548
549 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200550 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100551 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
552 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
553 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
554 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
555 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
556 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
557 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
558 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
559 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200560 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100561 break;
562 default:
563 lua_pushstring(L, "");
564 break;
565 }
566 break;
567
568 case SMP_T_SINT:
569 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100570 case SMP_T_IPV4:
571 case SMP_T_IPV6:
572 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200573 if (sample_casts[smp->data.type][SMP_T_STR] &&
574 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200575 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100576 else
577 lua_pushstring(L, "");
578 break;
579 default:
580 lua_pushstring(L, "");
581 break;
582 }
583 return 1;
584}
585
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100586/* the following functions are used to convert an Lua type in a
587 * struct sample. This is useful to provide data from a converter
588 * to the LUA code.
589 */
590static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
591{
592 switch (lua_type(L, ud)) {
593
594 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200595 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200596 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100597 break;
598
599
600 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200601 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200602 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100603 break;
604
605 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200606 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100607 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200608 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100609 break;
610
611 case LUA_TUSERDATA:
612 case LUA_TNIL:
613 case LUA_TTABLE:
614 case LUA_TFUNCTION:
615 case LUA_TTHREAD:
616 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200617 case LUA_TNONE:
618 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200619 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200620 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100621 break;
622 }
623 return 1;
624}
625
626/* This function check the "argp" builded by another conversion function
627 * is in accord with the expected argp defined by the "mask". The fucntion
628 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100629 *
630 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
631 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100632 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100633__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
634 unsigned int mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100635{
636 int min_arg;
637 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100638 struct proxy *px;
639 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100640
641 idx = 0;
642 min_arg = ARGM(mask);
643 mask >>= ARGM_BITS;
644
645 while (1) {
646
647 /* Check oversize. */
648 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100649 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100650 }
651
652 /* Check for mandatory arguments. */
653 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100654 if (idx < min_arg) {
655
656 /* If miss other argument than the first one, we return an error. */
657 if (idx > 0)
658 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
659
660 /* If first argument have a certain type, some default values
661 * may be used. See the function smp_resolve_args().
662 */
663 switch (mask & ARGT_MASK) {
664
665 case ARGT_FE:
666 if (!(p->cap & PR_CAP_FE))
667 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
668 argp[idx].data.prx = p;
669 argp[idx].type = ARGT_FE;
670 argp[idx+1].type = ARGT_STOP;
671 break;
672
673 case ARGT_BE:
674 if (!(p->cap & PR_CAP_BE))
675 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
676 argp[idx].data.prx = p;
677 argp[idx].type = ARGT_BE;
678 argp[idx+1].type = ARGT_STOP;
679 break;
680
681 case ARGT_TAB:
682 argp[idx].data.prx = p;
683 argp[idx].type = ARGT_TAB;
684 argp[idx+1].type = ARGT_STOP;
685 break;
686
687 default:
688 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
689 break;
690 }
691 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100692 return 0;
693 }
694
695 /* Check for exceed the number of requiered argument. */
696 if ((mask & ARGT_MASK) == ARGT_STOP &&
697 argp[idx].type != ARGT_STOP) {
698 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
699 }
700
701 if ((mask & ARGT_MASK) == ARGT_STOP &&
702 argp[idx].type == ARGT_STOP) {
703 return 0;
704 }
705
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100706 /* Convert some argument types. */
707 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100708 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100709 if (argp[idx].type != ARGT_SINT)
710 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
711 argp[idx].type = ARGT_SINT;
712 break;
713
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100714 case ARGT_TIME:
715 if (argp[idx].type != ARGT_SINT)
716 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200717 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100718 break;
719
720 case ARGT_SIZE:
721 if (argp[idx].type != ARGT_SINT)
722 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200723 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100724 break;
725
726 case ARGT_FE:
727 if (argp[idx].type != ARGT_STR)
728 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
729 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
730 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200731 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100732 if (!argp[idx].data.prx)
733 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
734 argp[idx].type = ARGT_FE;
735 break;
736
737 case ARGT_BE:
738 if (argp[idx].type != ARGT_STR)
739 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
740 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
741 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200742 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100743 if (!argp[idx].data.prx)
744 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
745 argp[idx].type = ARGT_BE;
746 break;
747
748 case ARGT_TAB:
749 if (argp[idx].type != ARGT_STR)
750 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
751 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
752 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200753 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100754 if (!argp[idx].data.prx)
755 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
756 argp[idx].type = ARGT_TAB;
757 break;
758
759 case ARGT_SRV:
760 if (argp[idx].type != ARGT_STR)
761 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
762 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
763 trash.str[argp[idx].data.str.len] = 0;
764 sname = strrchr(trash.str, '/');
765 if (sname) {
766 *sname++ = '\0';
767 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200768 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100769 if (!px)
770 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
771 }
772 else {
773 sname = trash.str;
774 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100775 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100776 argp[idx].data.srv = findserver(px, sname);
777 if (!argp[idx].data.srv)
778 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
779 argp[idx].type = ARGT_SRV;
780 break;
781
782 case ARGT_IPV4:
783 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
784 trash.str[argp[idx].data.str.len] = 0;
785 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
786 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
787 argp[idx].type = ARGT_IPV4;
788 break;
789
790 case ARGT_MSK4:
791 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
792 trash.str[argp[idx].data.str.len] = 0;
793 if (!str2mask(trash.str, &argp[idx].data.ipv4))
794 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
795 argp[idx].type = ARGT_MSK4;
796 break;
797
798 case ARGT_IPV6:
799 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
800 trash.str[argp[idx].data.str.len] = 0;
801 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
802 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
803 argp[idx].type = ARGT_IPV6;
804 break;
805
806 case ARGT_MSK6:
807 case ARGT_MAP:
808 case ARGT_REG:
809 case ARGT_USR:
810 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100811 break;
812 }
813
814 /* Check for type of argument. */
815 if ((mask & ARGT_MASK) != argp[idx].type) {
816 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
817 arg_type_names[(mask & ARGT_MASK)],
818 arg_type_names[argp[idx].type & ARGT_MASK]);
819 WILL_LJMP(luaL_argerror(L, first + idx, msg));
820 }
821
822 /* Next argument. */
823 mask >>= ARGT_BITS;
824 idx++;
825 }
826}
827
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100828/*
829 * The following functions are used to make correspondance between the the
830 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100831 *
832 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100833 * - hlua_sethlua : create the association between hlua context and lua_state.
834 */
835static inline struct hlua *hlua_gethlua(lua_State *L)
836{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100837 struct hlua **hlua = lua_getextraspace(L);
838 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100839}
840static inline void hlua_sethlua(struct hlua *hlua)
841{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100842 struct hlua **hlua_store = lua_getextraspace(hlua->T);
843 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100844}
845
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100846/* This function is used to send logs. It try to send on screen (stderr)
847 * and on the default syslog server.
848 */
849static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
850{
851 struct tm tm;
852 char *p;
853
854 /* Cleanup the log message. */
855 p = trash.str;
856 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200857 if (p >= trash.str + trash.size - 1) {
858 /* Break the message if exceed the buffer size. */
859 *(p-4) = ' ';
860 *(p-3) = '.';
861 *(p-2) = '.';
862 *(p-1) = '.';
863 break;
864 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100865 if (isprint(*msg))
866 *p = *msg;
867 else
868 *p = '.';
869 }
870 *p = '\0';
871
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200872 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100873 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200874 get_localtime(date.tv_sec, &tm);
875 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100876 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
877 (int)getpid(), trash.str);
878 fflush(stderr);
879 }
880}
881
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100882/* This function just ensure that the yield will be always
883 * returned with a timeout and permit to set some flags
884 */
885__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100886 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100887{
888 struct hlua *hlua = hlua_gethlua(L);
889
890 /* Set the wake timeout. If timeout is required, we set
891 * the expiration time.
892 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200893 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100894
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100895 hlua->flags |= flags;
896
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100897 /* Process the yield. */
898 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
899}
900
Willy Tarreau87b09662015-04-03 00:22:06 +0200901/* This function initialises the Lua environment stored in the stream.
902 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100903 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200904 *
905 * This function is particular. it initialises a new Lua thread. If the
906 * initialisation fails (example: out of memory error), the lua function
907 * throws an error (longjmp).
908 *
909 * This function manipulates two Lua stack: the main and the thread. Only
910 * the main stack can fail. The thread is not manipulated. This function
911 * MUST NOT manipulate the created thread stack state, because is not
912 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100913 */
914int hlua_ctx_init(struct hlua *lua, struct task *task)
915{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200916 if (!SET_SAFE_LJMP(gL.T)) {
917 lua->Tref = LUA_REFNIL;
918 return 0;
919 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100920 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100921 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100922 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100923 lua->T = lua_newthread(gL.T);
924 if (!lua->T) {
925 lua->Tref = LUA_REFNIL;
926 return 0;
927 }
928 hlua_sethlua(lua);
929 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
930 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200931 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100932 return 1;
933}
934
Willy Tarreau87b09662015-04-03 00:22:06 +0200935/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100936 * is destroyed. The destroy also the memory context. The struct "lua"
937 * is not freed.
938 */
939void hlua_ctx_destroy(struct hlua *lua)
940{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100941 if (!lua->T)
942 return;
943
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100944 /* Purge all the pending signals. */
945 hlua_com_purge(lua);
946
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100947 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
948 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200949
950 /* Forces a garbage collecting process. If the Lua program is finished
951 * without error, we run the GC on the thread pointer. Its freed all
952 * the unused memory.
953 * If the thread is finnish with an error or is currently yielded,
954 * it seems that the GC applied on the thread doesn't clean anything,
955 * so e run the GC on the main thread.
956 * NOTE: maybe this action locks all the Lua threads untiml the en of
957 * the garbage collection.
958 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200959 if (lua->flags & HLUA_MUST_GC) {
960 lua_gc(lua->T, LUA_GCCOLLECT, 0);
961 if (lua_status(lua->T) != LUA_OK)
962 lua_gc(gL.T, LUA_GCCOLLECT, 0);
963 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200964
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200965 lua->T = NULL;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100966}
967
968/* This function is used to restore the Lua context when a coroutine
969 * fails. This function copy the common memory between old coroutine
970 * and the new coroutine. The old coroutine is destroyed, and its
971 * replaced by the new coroutine.
972 * If the flag "keep_msg" is set, the last entry of the old is assumed
973 * as string error message and it is copied in the new stack.
974 */
975static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
976{
977 lua_State *T;
978 int new_ref;
979
980 /* Renew the main LUA stack doesn't have sense. */
981 if (lua == &gL)
982 return 0;
983
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100984 /* New Lua coroutine. */
985 T = lua_newthread(gL.T);
986 if (!T)
987 return 0;
988
989 /* Copy last error message. */
990 if (keep_msg)
991 lua_xmove(lua->T, T, 1);
992
993 /* Copy data between the coroutines. */
994 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
995 lua_xmove(lua->T, T, 1);
996 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
997
998 /* Destroy old data. */
999 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1000
1001 /* The thread is garbage collected by Lua. */
1002 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
1003
1004 /* Fill the struct with the new coroutine values. */
1005 lua->Mref = new_ref;
1006 lua->T = T;
1007 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
1008
1009 /* Set context. */
1010 hlua_sethlua(lua);
1011
1012 return 1;
1013}
1014
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001015void hlua_hook(lua_State *L, lua_Debug *ar)
1016{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001017 struct hlua *hlua = hlua_gethlua(L);
1018
1019 /* Lua cannot yield when its returning from a function,
1020 * so, we can fix the interrupt hook to 1 instruction,
1021 * expecting that the function is finnished.
1022 */
1023 if (lua_gethookmask(L) & LUA_MASKRET) {
1024 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1025 return;
1026 }
1027
1028 /* restore the interrupt condition. */
1029 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1030
1031 /* If we interrupt the Lua processing in yieldable state, we yield.
1032 * If the state is not yieldable, trying yield causes an error.
1033 */
1034 if (lua_isyieldable(L))
1035 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
1036
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001037 /* If we cannot yield, update the clock and check the timeout. */
1038 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001039 hlua->run_time += now_ms - hlua->start_time;
1040 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001041 lua_pushfstring(L, "execution timeout");
1042 WILL_LJMP(lua_error(L));
1043 }
1044
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001045 /* Update the start time. */
1046 hlua->start_time = now_ms;
1047
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001048 /* Try to interrupt the process at the end of the current
1049 * unyieldable function.
1050 */
1051 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001052}
1053
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001054/* This function start or resumes the Lua stack execution. If the flag
1055 * "yield_allowed" if no set and the LUA stack execution returns a yield
1056 * The function return an error.
1057 *
1058 * The function can returns 4 values:
1059 * - HLUA_E_OK : The execution is terminated without any errors.
1060 * - HLUA_E_AGAIN : The execution must continue at the next associated
1061 * task wakeup.
1062 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
1063 * the top of the stack.
1064 * - HLUA_E_ERR : An error has occured without error message.
1065 *
1066 * If an error occured, the stack is renewed and it is ready to run new
1067 * LUA code.
1068 */
1069static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1070{
1071 int ret;
1072 const char *msg;
1073
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001074 /* Initialise run time counter. */
1075 if (!HLUA_IS_RUNNING(lua))
1076 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001077
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001078resume_execution:
1079
1080 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1081 * instructions. it is used for preventing infinite loops.
1082 */
1083 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1084
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001085 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001086 HLUA_SET_RUN(lua);
1087 HLUA_CLR_CTRLYIELD(lua);
1088 HLUA_CLR_WAKERESWR(lua);
1089 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001090
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001091 /* Update the start time. */
1092 lua->start_time = now_ms;
1093
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001094 /* Call the function. */
1095 ret = lua_resume(lua->T, gL.T, lua->nargs);
1096 switch (ret) {
1097
1098 case LUA_OK:
1099 ret = HLUA_E_OK;
1100 break;
1101
1102 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001103 /* Check if the execution timeout is expired. It it is the case, we
1104 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001105 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001106 tv_update_date(0, 1);
1107 lua->run_time += now_ms - lua->start_time;
1108 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001109 lua_settop(lua->T, 0); /* Empty the stack. */
1110 if (!lua_checkstack(lua->T, 1)) {
1111 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001112 break;
1113 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001114 lua_pushfstring(lua->T, "execution timeout");
1115 ret = HLUA_E_ERRMSG;
1116 break;
1117 }
1118 /* Process the forced yield. if the general yield is not allowed or
1119 * if no task were associated this the current Lua execution
1120 * coroutine, we resume the execution. Else we want to return in the
1121 * scheduler and we want to be waked up again, to continue the
1122 * current Lua execution. So we schedule our own task.
1123 */
1124 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001125 if (!yield_allowed || !lua->task)
1126 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001127 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001128 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001129 if (!yield_allowed) {
1130 lua_settop(lua->T, 0); /* Empty the stack. */
1131 if (!lua_checkstack(lua->T, 1)) {
1132 ret = HLUA_E_ERR;
1133 break;
1134 }
1135 lua_pushfstring(lua->T, "yield not allowed");
1136 ret = HLUA_E_ERRMSG;
1137 break;
1138 }
1139 ret = HLUA_E_AGAIN;
1140 break;
1141
1142 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001143
1144 /* Special exit case. The traditionnal exit is returned as an error
1145 * because the errors ares the only one mean to return immediately
1146 * from and lua execution.
1147 */
1148 if (lua->flags & HLUA_EXIT) {
1149 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001150 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001151 break;
1152 }
1153
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001154 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001155 if (!lua_checkstack(lua->T, 1)) {
1156 ret = HLUA_E_ERR;
1157 break;
1158 }
1159 msg = lua_tostring(lua->T, -1);
1160 lua_settop(lua->T, 0); /* Empty the stack. */
1161 lua_pop(lua->T, 1);
1162 if (msg)
1163 lua_pushfstring(lua->T, "runtime error: %s", msg);
1164 else
1165 lua_pushfstring(lua->T, "unknown runtime error");
1166 ret = HLUA_E_ERRMSG;
1167 break;
1168
1169 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001170 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001171 lua_settop(lua->T, 0); /* Empty the stack. */
1172 if (!lua_checkstack(lua->T, 1)) {
1173 ret = HLUA_E_ERR;
1174 break;
1175 }
1176 lua_pushfstring(lua->T, "out of memory error");
1177 ret = HLUA_E_ERRMSG;
1178 break;
1179
1180 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001181 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001182 if (!lua_checkstack(lua->T, 1)) {
1183 ret = HLUA_E_ERR;
1184 break;
1185 }
1186 msg = lua_tostring(lua->T, -1);
1187 lua_settop(lua->T, 0); /* Empty the stack. */
1188 lua_pop(lua->T, 1);
1189 if (msg)
1190 lua_pushfstring(lua->T, "message handler error: %s", msg);
1191 else
1192 lua_pushfstring(lua->T, "message handler error");
1193 ret = HLUA_E_ERRMSG;
1194 break;
1195
1196 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001197 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001198 lua_settop(lua->T, 0); /* Empty the stack. */
1199 if (!lua_checkstack(lua->T, 1)) {
1200 ret = HLUA_E_ERR;
1201 break;
1202 }
1203 lua_pushfstring(lua->T, "unknonwn error");
1204 ret = HLUA_E_ERRMSG;
1205 break;
1206 }
1207
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001208 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001209 if (lua->flags & HLUA_MUST_GC &&
1210 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001211 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1212
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001213 switch (ret) {
1214 case HLUA_E_AGAIN:
1215 break;
1216
1217 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001218 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001219 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001220 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001221 break;
1222
1223 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001224 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001225 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001226 hlua_ctx_renew(lua, 0);
1227 break;
1228
1229 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001230 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001231 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001232 break;
1233 }
1234
1235 return ret;
1236}
1237
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001238/* This function exit the current code. */
1239__LJMP static int hlua_done(lua_State *L)
1240{
1241 struct hlua *hlua = hlua_gethlua(L);
1242
1243 hlua->flags |= HLUA_EXIT;
1244 WILL_LJMP(lua_error(L));
1245
1246 return 0;
1247}
1248
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001249/* This function is an LUA binding. It provides a function
1250 * for deleting ACL from a referenced ACL file.
1251 */
1252__LJMP static int hlua_del_acl(lua_State *L)
1253{
1254 const char *name;
1255 const char *key;
1256 struct pat_ref *ref;
1257
1258 MAY_LJMP(check_args(L, 2, "del_acl"));
1259
1260 name = MAY_LJMP(luaL_checkstring(L, 1));
1261 key = MAY_LJMP(luaL_checkstring(L, 2));
1262
1263 ref = pat_ref_lookup(name);
1264 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001265 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001266
1267 pat_ref_delete(ref, key);
1268 return 0;
1269}
1270
1271/* This function is an LUA binding. It provides a function
1272 * for deleting map entry from a referenced map file.
1273 */
1274static int hlua_del_map(lua_State *L)
1275{
1276 const char *name;
1277 const char *key;
1278 struct pat_ref *ref;
1279
1280 MAY_LJMP(check_args(L, 2, "del_map"));
1281
1282 name = MAY_LJMP(luaL_checkstring(L, 1));
1283 key = MAY_LJMP(luaL_checkstring(L, 2));
1284
1285 ref = pat_ref_lookup(name);
1286 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001287 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001288
1289 pat_ref_delete(ref, key);
1290 return 0;
1291}
1292
1293/* This function is an LUA binding. It provides a function
1294 * for adding ACL pattern from a referenced ACL file.
1295 */
1296static int hlua_add_acl(lua_State *L)
1297{
1298 const char *name;
1299 const char *key;
1300 struct pat_ref *ref;
1301
1302 MAY_LJMP(check_args(L, 2, "add_acl"));
1303
1304 name = MAY_LJMP(luaL_checkstring(L, 1));
1305 key = MAY_LJMP(luaL_checkstring(L, 2));
1306
1307 ref = pat_ref_lookup(name);
1308 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001309 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001310
1311 if (pat_ref_find_elt(ref, key) == NULL)
1312 pat_ref_add(ref, key, NULL, NULL);
1313 return 0;
1314}
1315
1316/* This function is an LUA binding. It provides a function
1317 * for setting map pattern and sample from a referenced map
1318 * file.
1319 */
1320static int hlua_set_map(lua_State *L)
1321{
1322 const char *name;
1323 const char *key;
1324 const char *value;
1325 struct pat_ref *ref;
1326
1327 MAY_LJMP(check_args(L, 3, "set_map"));
1328
1329 name = MAY_LJMP(luaL_checkstring(L, 1));
1330 key = MAY_LJMP(luaL_checkstring(L, 2));
1331 value = MAY_LJMP(luaL_checkstring(L, 3));
1332
1333 ref = pat_ref_lookup(name);
1334 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001335 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001336
1337 if (pat_ref_find_elt(ref, key) != NULL)
1338 pat_ref_set(ref, key, value, NULL);
1339 else
1340 pat_ref_add(ref, key, value, NULL);
1341 return 0;
1342}
1343
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001344/* A class is a lot of memory that contain data. This data can be a table,
1345 * an integer or user data. This data is associated with a metatable. This
1346 * metatable have an original version registred in the global context with
1347 * the name of the object (_G[<name>] = <metable> ).
1348 *
1349 * A metable is a table that modify the standard behavior of a standard
1350 * access to the associated data. The entries of this new metatable are
1351 * defined as is:
1352 *
1353 * http://lua-users.org/wiki/MetatableEvents
1354 *
1355 * __index
1356 *
1357 * we access an absent field in a table, the result is nil. This is
1358 * true, but it is not the whole truth. Actually, such access triggers
1359 * the interpreter to look for an __index metamethod: If there is no
1360 * such method, as usually happens, then the access results in nil;
1361 * otherwise, the metamethod will provide the result.
1362 *
1363 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1364 * the key does not appear in the table, but the metatable has an __index
1365 * property:
1366 *
1367 * - if the value is a function, the function is called, passing in the
1368 * table and the key; the return value of that function is returned as
1369 * the result.
1370 *
1371 * - if the value is another table, the value of the key in that table is
1372 * asked for and returned (and if it doesn't exist in that table, but that
1373 * table's metatable has an __index property, then it continues on up)
1374 *
1375 * - Use "rawget(myTable,key)" to skip this metamethod.
1376 *
1377 * http://www.lua.org/pil/13.4.1.html
1378 *
1379 * __newindex
1380 *
1381 * Like __index, but control property assignment.
1382 *
1383 * __mode - Control weak references. A string value with one or both
1384 * of the characters 'k' and 'v' which specifies that the the
1385 * keys and/or values in the table are weak references.
1386 *
1387 * __call - Treat a table like a function. When a table is followed by
1388 * parenthesis such as "myTable( 'foo' )" and the metatable has
1389 * a __call key pointing to a function, that function is invoked
1390 * (passing any specified arguments) and the return value is
1391 * returned.
1392 *
1393 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1394 * called, if the metatable for myTable has a __metatable
1395 * key, the value of that key is returned instead of the
1396 * actual metatable.
1397 *
1398 * __tostring - Control string representation. When the builtin
1399 * "tostring( myTable )" function is called, if the metatable
1400 * for myTable has a __tostring property set to a function,
1401 * that function is invoked (passing myTable to it) and the
1402 * return value is used as the string representation.
1403 *
1404 * __len - Control table length. When the table length is requested using
1405 * the length operator ( '#' ), if the metatable for myTable has
1406 * a __len key pointing to a function, that function is invoked
1407 * (passing myTable to it) and the return value used as the value
1408 * of "#myTable".
1409 *
1410 * __gc - Userdata finalizer code. When userdata is set to be garbage
1411 * collected, if the metatable has a __gc field pointing to a
1412 * function, that function is first invoked, passing the userdata
1413 * to it. The __gc metamethod is not called for tables.
1414 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1415 *
1416 * Special metamethods for redefining standard operators:
1417 * http://www.lua.org/pil/13.1.html
1418 *
1419 * __add "+"
1420 * __sub "-"
1421 * __mul "*"
1422 * __div "/"
1423 * __unm "!"
1424 * __pow "^"
1425 * __concat ".."
1426 *
1427 * Special methods for redfining standar relations
1428 * http://www.lua.org/pil/13.2.html
1429 *
1430 * __eq "=="
1431 * __lt "<"
1432 * __le "<="
1433 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001434
1435/*
1436 *
1437 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001438 * Class Map
1439 *
1440 *
1441 */
1442
1443/* Returns a struct hlua_map if the stack entry "ud" is
1444 * a class session, otherwise it throws an error.
1445 */
1446__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1447{
1448 return (struct map_descriptor *)MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
1449}
1450
1451/* This function is the map constructor. It don't need
1452 * the class Map object. It creates and return a new Map
1453 * object. It must be called only during "body" or "init"
1454 * context because it process some filesystem accesses.
1455 */
1456__LJMP static int hlua_map_new(struct lua_State *L)
1457{
1458 const char *fn;
1459 int match = PAT_MATCH_STR;
1460 struct sample_conv conv;
1461 const char *file = "";
1462 int line = 0;
1463 lua_Debug ar;
1464 char *err = NULL;
1465 struct arg args[2];
1466
1467 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1468 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1469
1470 fn = MAY_LJMP(luaL_checkstring(L, 1));
1471
1472 if (lua_gettop(L) >= 2) {
1473 match = MAY_LJMP(luaL_checkinteger(L, 2));
1474 if (match < 0 || match >= PAT_MATCH_NUM)
1475 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1476 }
1477
1478 /* Get Lua filename and line number. */
1479 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1480 lua_getinfo(L, "Sl", &ar); /* get info about it */
1481 if (ar.currentline > 0) { /* is there info? */
1482 file = ar.short_src;
1483 line = ar.currentline;
1484 }
1485 }
1486
1487 /* fill fake sample_conv struct. */
1488 conv.kw = ""; /* unused. */
1489 conv.process = NULL; /* unused. */
1490 conv.arg_mask = 0; /* unused. */
1491 conv.val_args = NULL; /* unused. */
1492 conv.out_type = SMP_T_STR;
1493 conv.private = (void *)(long)match;
1494 switch (match) {
1495 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1496 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1497 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1498 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1499 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1500 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1501 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001502 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001503 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1504 default:
1505 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1506 }
1507
1508 /* fill fake args. */
1509 args[0].type = ARGT_STR;
1510 args[0].data.str.str = (char *)fn;
1511 args[1].type = ARGT_STOP;
1512
1513 /* load the map. */
1514 if (!sample_load_map(args, &conv, file, line, &err)) {
1515 /* error case: we cant use luaL_error because we must
1516 * free the err variable.
1517 */
1518 luaL_where(L, 1);
1519 lua_pushfstring(L, "'new': %s.", err);
1520 lua_concat(L, 2);
1521 free(err);
1522 WILL_LJMP(lua_error(L));
1523 }
1524
1525 /* create the lua object. */
1526 lua_newtable(L);
1527 lua_pushlightuserdata(L, args[0].data.map);
1528 lua_rawseti(L, -2, 0);
1529
1530 /* Pop a class Map metatable and affect it to the userdata. */
1531 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1532 lua_setmetatable(L, -2);
1533
1534
1535 return 1;
1536}
1537
1538__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1539{
1540 struct map_descriptor *desc;
1541 struct pattern *pat;
1542 struct sample smp;
1543
1544 MAY_LJMP(check_args(L, 2, "lookup"));
1545 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001546 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001547 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001548 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001549 }
1550 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001551 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001552 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001553 smp.data.u.str.str = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.len));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001554 }
1555
1556 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001557 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001558 if (str)
1559 lua_pushstring(L, "");
1560 else
1561 lua_pushnil(L);
1562 return 1;
1563 }
1564
1565 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001566 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001567 return 1;
1568}
1569
1570__LJMP static int hlua_map_lookup(struct lua_State *L)
1571{
1572 return _hlua_map_lookup(L, 0);
1573}
1574
1575__LJMP static int hlua_map_slookup(struct lua_State *L)
1576{
1577 return _hlua_map_lookup(L, 1);
1578}
1579
1580/*
1581 *
1582 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001583 * Class Socket
1584 *
1585 *
1586 */
1587
1588__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1589{
1590 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1591}
1592
1593/* This function is the handler called for each I/O on the established
1594 * connection. It is used for notify space avalaible to send or data
1595 * received.
1596 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001597static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001598{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001599 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001600 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001601
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001602 /* If the connection object is not avalaible, close all the
1603 * streams and wakeup everithing waiting for.
1604 */
1605 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001606 si_shutw(si);
1607 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001608 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001609 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1610 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001611 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001612 }
1613
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001614 /* If we cant write, wakeup the pending write signals. */
1615 if (channel_output_closed(si_ic(si)))
1616 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1617
1618 /* If we cant read, wakeup the pending read signals. */
1619 if (channel_input_closed(si_oc(si)))
1620 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1621
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001622 /* if the connection is not estabkished, inform the stream that we want
1623 * to be notified whenever the connection completes.
1624 */
1625 if (!(c->flags & CO_FL_CONNECTED)) {
1626 si_applet_cant_get(si);
1627 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001628 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001629 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001630
1631 /* This function is called after the connect. */
1632 appctx->ctx.hlua.connected = 1;
1633
1634 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001635 if (channel_may_recv(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001636 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1637
1638 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001639 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001640 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1641}
1642
Willy Tarreau87b09662015-04-03 00:22:06 +02001643/* This function is called when the "struct stream" is destroyed.
1644 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001645 * Wake all the pending signals.
1646 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001647static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001648{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001649 /* Remove my link in the original object. */
1650 if (appctx->ctx.hlua.socket)
1651 appctx->ctx.hlua.socket->s = NULL;
1652
1653 /* Wake all the task waiting for me. */
1654 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1655 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1656}
1657
1658/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001659 * uses this object. If the stream does not exists, just quit.
1660 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001661 * pending signal can rest in the read and write lists. destroy
1662 * it.
1663 */
1664__LJMP static int hlua_socket_gc(lua_State *L)
1665{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001666 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001667 struct appctx *appctx;
1668
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001669 MAY_LJMP(check_args(L, 1, "__gc"));
1670
1671 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001672 if (!socket->s)
1673 return 0;
1674
Willy Tarreau87b09662015-04-03 00:22:06 +02001675 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001676 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001677 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001678 socket->s = NULL;
1679 appctx->ctx.hlua.socket = NULL;
1680
1681 return 0;
1682}
1683
1684/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001685 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001686 */
1687__LJMP static int hlua_socket_close(lua_State *L)
1688{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001689 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001690 struct appctx *appctx;
1691
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001692 MAY_LJMP(check_args(L, 1, "close"));
1693
1694 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001695 if (!socket->s)
1696 return 0;
1697
Willy Tarreau87b09662015-04-03 00:22:06 +02001698 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001699 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001700 appctx = objt_appctx(socket->s->si[0].end);
1701 appctx->ctx.hlua.socket = NULL;
1702 socket->s = NULL;
1703
1704 return 0;
1705}
1706
1707/* This Lua function assumes that the stack contain three parameters.
1708 * 1 - USERDATA containing a struct socket
1709 * 2 - INTEGER with values of the macro defined below
1710 * If the integer is -1, we must read at most one line.
1711 * If the integer is -2, we ust read all the data until the
1712 * end of the stream.
1713 * If the integer is positive value, we must read a number of
1714 * bytes corresponding to this value.
1715 */
1716#define HLSR_READ_LINE (-1)
1717#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001718__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001719{
1720 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1721 int wanted = lua_tointeger(L, 2);
1722 struct hlua *hlua = hlua_gethlua(L);
1723 struct appctx *appctx;
1724 int len;
1725 int nblk;
1726 char *blk1;
1727 int len1;
1728 char *blk2;
1729 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001730 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001731 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001732
1733 /* Check if this lua stack is schedulable. */
1734 if (!hlua || !hlua->task)
1735 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1736 "'frontend', 'backend' or 'task'"));
1737
1738 /* check for connection closed. If some data where read, return it. */
1739 if (!socket->s)
1740 goto connection_closed;
1741
Willy Tarreau94aa6172015-03-13 14:19:06 +01001742 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001743 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001744 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001745 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001746 if (nblk < 0) /* Connection close. */
1747 goto connection_closed;
1748 if (nblk == 0) /* No data avalaible. */
1749 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001750
1751 /* remove final \r\n. */
1752 if (nblk == 1) {
1753 if (blk1[len1-1] == '\n') {
1754 len1--;
1755 skip_at_end++;
1756 if (blk1[len1-1] == '\r') {
1757 len1--;
1758 skip_at_end++;
1759 }
1760 }
1761 }
1762 else {
1763 if (blk2[len2-1] == '\n') {
1764 len2--;
1765 skip_at_end++;
1766 if (blk2[len2-1] == '\r') {
1767 len2--;
1768 skip_at_end++;
1769 }
1770 }
1771 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001772 }
1773
1774 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001775 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001776 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001777 if (nblk < 0) /* Connection close. */
1778 goto connection_closed;
1779 if (nblk == 0) /* No data avalaible. */
1780 goto connection_empty;
1781 }
1782
1783 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001784 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001785 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001786 if (nblk < 0) /* Connection close. */
1787 goto connection_closed;
1788 if (nblk == 0) /* No data avalaible. */
1789 goto connection_empty;
1790
1791 if (len1 > wanted) {
1792 nblk = 1;
1793 len1 = wanted;
1794 } if (nblk == 2 && len1 + len2 > wanted)
1795 len2 = wanted - len1;
1796 }
1797
1798 len = len1;
1799
1800 luaL_addlstring(&socket->b, blk1, len1);
1801 if (nblk == 2) {
1802 len += len2;
1803 luaL_addlstring(&socket->b, blk2, len2);
1804 }
1805
1806 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001807 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001808
1809 /* Don't wait anything. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001810 stream_int_notify(&socket->s->si[0]);
1811 stream_int_update_applet(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001812
1813 /* If the pattern reclaim to read all the data
1814 * in the connection, got out.
1815 */
1816 if (wanted == HLSR_READ_ALL)
1817 goto connection_empty;
1818 else if (wanted >= 0 && len < wanted)
1819 goto connection_empty;
1820
1821 /* Return result. */
1822 luaL_pushresult(&socket->b);
1823 return 1;
1824
1825connection_closed:
1826
1827 /* If the buffer containds data. */
1828 if (socket->b.n > 0) {
1829 luaL_pushresult(&socket->b);
1830 return 1;
1831 }
1832 lua_pushnil(L);
1833 lua_pushstring(L, "connection closed.");
1834 return 2;
1835
1836connection_empty:
1837
1838 appctx = objt_appctx(socket->s->si[0].end);
1839 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1840 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001841 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001842 return 0;
1843}
1844
1845/* This Lus function gets two parameters. The first one can be string
1846 * or a number. If the string is "*l", the user require one line. If
1847 * the string is "*a", the user require all the content of the stream.
1848 * If the value is a number, the user require a number of bytes equal
1849 * to the value. The default value is "*l" (a line).
1850 *
1851 * This paraeter with a variable type is converted in integer. This
1852 * integer takes this values:
1853 * -1 : read a line
1854 * -2 : read all the stream
1855 * >0 : amount if bytes.
1856 *
1857 * The second parameter is optinal. It contains a string that must be
1858 * concatenated with the read data.
1859 */
1860__LJMP static int hlua_socket_receive(struct lua_State *L)
1861{
1862 int wanted = HLSR_READ_LINE;
1863 const char *pattern;
1864 int type;
1865 char *error;
1866 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001867 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001868
1869 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1870 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1871
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001872 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001873
1874 /* check for pattern. */
1875 if (lua_gettop(L) >= 2) {
1876 type = lua_type(L, 2);
1877 if (type == LUA_TSTRING) {
1878 pattern = lua_tostring(L, 2);
1879 if (strcmp(pattern, "*a") == 0)
1880 wanted = HLSR_READ_ALL;
1881 else if (strcmp(pattern, "*l") == 0)
1882 wanted = HLSR_READ_LINE;
1883 else {
1884 wanted = strtoll(pattern, &error, 10);
1885 if (*error != '\0')
1886 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1887 }
1888 }
1889 else if (type == LUA_TNUMBER) {
1890 wanted = lua_tointeger(L, 2);
1891 if (wanted < 0)
1892 WILL_LJMP(luaL_error(L, "Unsupported size."));
1893 }
1894 }
1895
1896 /* Set pattern. */
1897 lua_pushinteger(L, wanted);
1898 lua_replace(L, 2);
1899
1900 /* init bufffer, and fiil it wih prefix. */
1901 luaL_buffinit(L, &socket->b);
1902
1903 /* Check prefix. */
1904 if (lua_gettop(L) >= 3) {
1905 if (lua_type(L, 3) != LUA_TSTRING)
1906 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1907 pattern = lua_tolstring(L, 3, &len);
1908 luaL_addlstring(&socket->b, pattern, len);
1909 }
1910
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001911 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001912}
1913
1914/* Write the Lua input string in the output buffer.
1915 * This fucntion returns a yield if no space are available.
1916 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001917static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001918{
1919 struct hlua_socket *socket;
1920 struct hlua *hlua = hlua_gethlua(L);
1921 struct appctx *appctx;
1922 size_t buf_len;
1923 const char *buf;
1924 int len;
1925 int send_len;
1926 int sent;
1927
1928 /* Check if this lua stack is schedulable. */
1929 if (!hlua || !hlua->task)
1930 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1931 "'frontend', 'backend' or 'task'"));
1932
1933 /* Get object */
1934 socket = MAY_LJMP(hlua_checksocket(L, 1));
1935 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001936 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001937
1938 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001939 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001940 lua_pushinteger(L, -1);
1941 return 1;
1942 }
1943
1944 /* Update the input buffer data. */
1945 buf += sent;
1946 send_len = buf_len - sent;
1947
1948 /* All the data are sent. */
1949 if (sent >= buf_len)
1950 return 1; /* Implicitly return the length sent. */
1951
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001952 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1953 * the request buffer if its not required.
1954 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001955 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001956 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001957 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001958 goto hlua_socket_write_yield_return;
1959 }
1960 }
1961
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001962 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001963 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001964 if (len <= 0)
1965 goto hlua_socket_write_yield_return;
1966
1967 /* send data */
1968 if (len < send_len)
1969 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001970 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001971
1972 /* "Not enough space" (-1), "Buffer too little to contain
1973 * the data" (-2) are not expected because the available length
1974 * is tested.
1975 * Other unknown error are also not expected.
1976 */
1977 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001978 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001979 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001980
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001981 MAY_LJMP(hlua_socket_close(L));
1982 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001983 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001984 return 1;
1985 }
1986
1987 /* update buffers. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001988 stream_int_notify(&socket->s->si[0]);
1989 stream_int_update_applet(&socket->s->si[0]);
1990
Willy Tarreau94aa6172015-03-13 14:19:06 +01001991 socket->s->req.rex = TICK_ETERNITY;
1992 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001993
1994 /* Update length sent. */
1995 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001996 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001997
1998 /* All the data buffer is sent ? */
1999 if (sent + len >= buf_len)
2000 return 1;
2001
2002hlua_socket_write_yield_return:
2003 appctx = objt_appctx(socket->s->si[0].end);
2004 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2005 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002006 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002007 return 0;
2008}
2009
2010/* This function initiate the send of data. It just check the input
2011 * parameters and push an integer in the Lua stack that contain the
2012 * amount of data writed in the buffer. This is used by the function
2013 * "hlua_socket_write_yield" that can yield.
2014 *
2015 * The Lua function gets between 3 and 4 parameters. The first one is
2016 * the associated object. The second is a string buffer. The third is
2017 * a facultative integer that represents where is the buffer position
2018 * of the start of the data that can send. The first byte is the
2019 * position "1". The default value is "1". The fourth argument is a
2020 * facultative integer that represents where is the buffer position
2021 * of the end of the data that can send. The default is the last byte.
2022 */
2023static int hlua_socket_send(struct lua_State *L)
2024{
2025 int i;
2026 int j;
2027 const char *buf;
2028 size_t buf_len;
2029
2030 /* Check number of arguments. */
2031 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2032 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2033
2034 /* Get the string. */
2035 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2036
2037 /* Get and check j. */
2038 if (lua_gettop(L) == 4) {
2039 j = MAY_LJMP(luaL_checkinteger(L, 4));
2040 if (j < 0)
2041 j = buf_len + j + 1;
2042 if (j > buf_len)
2043 j = buf_len + 1;
2044 lua_pop(L, 1);
2045 }
2046 else
2047 j = buf_len;
2048
2049 /* Get and check i. */
2050 if (lua_gettop(L) == 3) {
2051 i = MAY_LJMP(luaL_checkinteger(L, 3));
2052 if (i < 0)
2053 i = buf_len + i + 1;
2054 if (i > buf_len)
2055 i = buf_len + 1;
2056 lua_pop(L, 1);
2057 } else
2058 i = 1;
2059
2060 /* Check bth i and j. */
2061 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002062 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002063 return 1;
2064 }
2065 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002066 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002067 return 1;
2068 }
2069 if (i == 0)
2070 i = 1;
2071 if (j == 0)
2072 j = 1;
2073
2074 /* Pop the string. */
2075 lua_pop(L, 1);
2076
2077 /* Update the buffer length. */
2078 buf += i - 1;
2079 buf_len = j - i + 1;
2080 lua_pushlstring(L, buf, buf_len);
2081
2082 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002083 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002084
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002085 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002086}
2087
Willy Tarreau22b0a682015-06-17 19:43:49 +02002088#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002089__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2090{
2091 static char buffer[SOCKET_INFO_MAX_LEN];
2092 int ret;
2093 int len;
2094 char *p;
2095
2096 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2097 if (ret <= 0) {
2098 lua_pushnil(L);
2099 return 1;
2100 }
2101
2102 if (ret == AF_UNIX) {
2103 lua_pushstring(L, buffer+1);
2104 return 1;
2105 }
2106 else if (ret == AF_INET6) {
2107 buffer[0] = '[';
2108 len = strlen(buffer);
2109 buffer[len] = ']';
2110 len++;
2111 buffer[len] = ':';
2112 len++;
2113 p = buffer;
2114 }
2115 else if (ret == AF_INET) {
2116 p = buffer + 1;
2117 len = strlen(p);
2118 p[len] = ':';
2119 len++;
2120 }
2121 else {
2122 lua_pushnil(L);
2123 return 1;
2124 }
2125
2126 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2127 lua_pushnil(L);
2128 return 1;
2129 }
2130
2131 lua_pushstring(L, p);
2132 return 1;
2133}
2134
2135/* Returns information about the peer of the connection. */
2136__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2137{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002138 struct hlua_socket *socket;
2139 struct connection *conn;
2140
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002141 MAY_LJMP(check_args(L, 1, "getpeername"));
2142
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002143 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002144
2145 /* Check if the tcp object is avalaible. */
2146 if (!socket->s) {
2147 lua_pushnil(L);
2148 return 1;
2149 }
2150
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002151 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002152 if (!conn) {
2153 lua_pushnil(L);
2154 return 1;
2155 }
2156
2157 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
2158 unsigned int salen = sizeof(conn->addr.to);
2159 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
2160 lua_pushnil(L);
2161 return 1;
2162 }
2163 conn->flags |= CO_FL_ADDR_TO_SET;
2164 }
2165
2166 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2167}
2168
2169/* Returns information about my connection side. */
2170static int hlua_socket_getsockname(struct lua_State *L)
2171{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002172 struct hlua_socket *socket;
2173 struct connection *conn;
2174
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002175 MAY_LJMP(check_args(L, 1, "getsockname"));
2176
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002177 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002178
2179 /* Check if the tcp object is avalaible. */
2180 if (!socket->s) {
2181 lua_pushnil(L);
2182 return 1;
2183 }
2184
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002185 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186 if (!conn) {
2187 lua_pushnil(L);
2188 return 1;
2189 }
2190
2191 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2192 unsigned int salen = sizeof(conn->addr.from);
2193 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2194 lua_pushnil(L);
2195 return 1;
2196 }
2197 conn->flags |= CO_FL_ADDR_FROM_SET;
2198 }
2199
2200 return hlua_socket_info(L, &conn->addr.from);
2201}
2202
2203/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002204static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002205 .obj_type = OBJ_TYPE_APPLET,
2206 .name = "<LUA_TCP>",
2207 .fct = hlua_socket_handler,
2208 .release = hlua_socket_release,
2209};
2210
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002211__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002212{
2213 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2214 struct hlua *hlua = hlua_gethlua(L);
2215 struct appctx *appctx;
2216
2217 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002218 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002219 lua_pushnil(L);
2220 lua_pushstring(L, "Can't connect");
2221 return 2;
2222 }
2223
2224 appctx = objt_appctx(socket->s->si[0].end);
2225
2226 /* Check for connection established. */
2227 if (appctx->ctx.hlua.connected) {
2228 lua_pushinteger(L, 1);
2229 return 1;
2230 }
2231
2232 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2233 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002234 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002235 return 0;
2236}
2237
2238/* This function fail or initite the connection. */
2239__LJMP static int hlua_socket_connect(struct lua_State *L)
2240{
2241 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002242 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002243 const char *ip;
2244 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002245 struct hlua *hlua;
2246 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002247 int low, high;
2248 struct sockaddr_storage *addr;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002249
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002250 if (lua_gettop(L) < 2)
2251 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002252
2253 /* Get args. */
2254 socket = MAY_LJMP(hlua_checksocket(L, 1));
2255 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002256 if (lua_gettop(L) >= 3)
2257 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002258
Willy Tarreau973a5422015-08-05 21:47:23 +02002259 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002260 if (!conn)
2261 WILL_LJMP(luaL_error(L, "connect: internal error"));
2262
Willy Tarreau3adac082015-09-26 17:51:09 +02002263 /* needed for the connection not to be closed */
2264 conn->target = socket->s->target;
2265
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002266 /* Parse ip address. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002267 addr = str2sa_range(ip, &low, &high, NULL, NULL, NULL, 0);
2268 if (!addr)
2269 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
2270 if (low != high)
2271 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
2272 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002273
2274 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002275 if (low == 0) {
2276 if (conn->addr.to.ss_family == AF_INET) {
2277 if (port == -1)
2278 WILL_LJMP(luaL_error(L, "connect: port missing"));
2279 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2280 } else if (conn->addr.to.ss_family == AF_INET6) {
2281 if (port == -1)
2282 WILL_LJMP(luaL_error(L, "connect: port missing"));
2283 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2284 }
2285 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002286
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002287 hlua = hlua_gethlua(L);
2288 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002289
2290 /* inform the stream that we want to be notified whenever the
2291 * connection completes.
2292 */
2293 si_applet_cant_get(&socket->s->si[0]);
2294 si_applet_cant_put(&socket->s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002295 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002296
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002297 hlua->flags |= HLUA_MUST_GC;
2298
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002299 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2300 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002301 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002302
2303 return 0;
2304}
2305
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002306#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002307__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2308{
2309 struct hlua_socket *socket;
2310
2311 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2312 socket = MAY_LJMP(hlua_checksocket(L, 1));
2313 socket->s->target = &socket_ssl.obj_type;
2314 return MAY_LJMP(hlua_socket_connect(L));
2315}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002316#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002317
2318__LJMP static int hlua_socket_setoption(struct lua_State *L)
2319{
2320 return 0;
2321}
2322
2323__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2324{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002325 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002326 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002327
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002328 MAY_LJMP(check_args(L, 2, "settimeout"));
2329
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002330 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002331 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002332
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002333 socket->s->req.rto = tmout;
2334 socket->s->req.wto = tmout;
2335 socket->s->res.rto = tmout;
2336 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002337
2338 return 0;
2339}
2340
2341__LJMP static int hlua_socket_new(lua_State *L)
2342{
2343 struct hlua_socket *socket;
2344 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002345 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002346 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002347 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002348
2349 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002350 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002351 hlua_pusherror(L, "socket: full stack");
2352 goto out_fail_conf;
2353 }
2354
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002355 /* Create the object: obj[0] = userdata. */
2356 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002357 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002358 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002359 memset(socket, 0, sizeof(*socket));
2360
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002361 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002362 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002363 hlua_pusherror(L, "socket: uninitialized pools.");
2364 goto out_fail_conf;
2365 }
2366
Willy Tarreau87b09662015-04-03 00:22:06 +02002367 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002368 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2369 lua_setmetatable(L, -2);
2370
Willy Tarreaud420a972015-04-06 00:39:18 +02002371 /* Create the applet context */
2372 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002373 if (!appctx) {
2374 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002375 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002376 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002377
Willy Tarreaud420a972015-04-06 00:39:18 +02002378 appctx->ctx.hlua.socket = socket;
2379 appctx->ctx.hlua.connected = 0;
2380 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2381 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002382
Willy Tarreaud420a972015-04-06 00:39:18 +02002383 /* Now create a session, task and stream for this applet */
2384 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2385 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002386 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002387 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002388 }
2389
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002390 task = task_new();
2391 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002392 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002393 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002394 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002395 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002396
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002397 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002398 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002399 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002400 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002401 }
2402
Willy Tarreaud420a972015-04-06 00:39:18 +02002403 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002404 socket->s = strm;
2405 strm->hlua.T = NULL;
2406 strm->hlua.Tref = LUA_REFNIL;
2407 strm->hlua.Mref = LUA_REFNIL;
2408 strm->hlua.nargs = 0;
2409 strm->hlua.flags = 0;
2410 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002411
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002412 /* Configure "right" stream interface. this "si" is used to connect
2413 * and retrieve data from the server. The connection is initialized
2414 * with the "struct server".
2415 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002416 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002417
2418 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002419 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2420 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002421
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002422 /* Update statistics counters. */
2423 socket_proxy.feconn++; /* beconn will be increased later */
2424 jobs++;
2425 totalconn++;
2426
2427 /* Return yield waiting for connection. */
2428 return 1;
2429
Willy Tarreaud420a972015-04-06 00:39:18 +02002430 out_fail_stream:
2431 task_free(task);
2432 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002433 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002434 out_fail_sess:
2435 appctx_free(appctx);
2436 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002437 WILL_LJMP(lua_error(L));
2438 return 0;
2439}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002440
2441/*
2442 *
2443 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002444 * Class Channel
2445 *
2446 *
2447 */
2448
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002449/* The state between the channel data and the HTTP parser state can be
2450 * unconsistent, so reset the parser and call it again. Warning, this
2451 * action not revalidate the request and not send a 400 if the modified
2452 * resuest is not valid.
2453 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002454 * This function never fails. The direction is set using dir, which equals
2455 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002456 */
2457static void hlua_resynchonize_proto(struct stream *stream, int dir)
2458{
2459 /* Protocol HTTP. */
2460 if (stream->be->mode == PR_MODE_HTTP) {
2461
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002462 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002463 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002464 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002465 http_txn_reset_res(stream->txn);
2466
2467 if (stream->txn->hdr_idx.v)
2468 hdr_idx_init(&stream->txn->hdr_idx);
2469
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002470 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002471 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002472 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002473 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2474 }
2475}
2476
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002477/* Check the protocole integrity after the Lua manipulations. Close the stream
2478 * and returns 0 if fails, otherwise returns 1. The direction is set using dir,
2479 * which equals either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002480 */
2481static int hlua_check_proto(struct stream *stream, int dir)
2482{
2483 const struct chunk msg = { .len = 0 };
2484
Willy Tarreau9af89f72015-09-26 11:50:08 +02002485 /* Protocol HTTP. The message parsing state must match the request or
2486 * response state. The problem that may happen is that Lua modifies
2487 * the request or response message *after* it was parsed, and corrupted
2488 * it so that it could not be processed anymore. We just need to verify
2489 * if the parser is still expected to run or not.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002490 */
2491 if (stream->be->mode == PR_MODE_HTTP) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002492 if (dir == SMP_OPT_DIR_REQ &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002493 !(stream->req.analysers & AN_REQ_WAIT_HTTP) &&
2494 stream->txn->req.msg_state < HTTP_MSG_BODY) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002495 stream_int_retnclose(&stream->si[0], &msg);
2496 return 0;
2497 }
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002498 else if (dir == SMP_OPT_DIR_RES &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002499 !(stream->res.analysers & AN_RES_WAIT_HTTP) &&
2500 stream->txn->rsp.msg_state < HTTP_MSG_BODY) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002501 stream_int_retnclose(&stream->si[0], &msg);
2502 return 0;
2503 }
2504 }
2505 return 1;
2506}
2507
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002508/* Returns the struct hlua_channel join to the class channel in the
2509 * stack entry "ud" or throws an argument error.
2510 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002511__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002512{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002513 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002514}
2515
Willy Tarreau47860ed2015-03-10 14:07:50 +01002516/* Pushes the channel onto the top of the stack. If the stask does not have a
2517 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002518 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002519static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002520{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002521 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002522 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002523 return 0;
2524
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002525 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002526 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002527 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002528
2529 /* Pop a class sesison metatable and affect it to the userdata. */
2530 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2531 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002532 return 1;
2533}
2534
2535/* Duplicate all the data present in the input channel and put it
2536 * in a string LUA variables. Returns -1 and push a nil value in
2537 * the stack if the channel is closed and all the data are consumed,
2538 * returns 0 if no data are available, otherwise it returns the length
2539 * of the builded string.
2540 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002541static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002542{
2543 char *blk1;
2544 char *blk2;
2545 int len1;
2546 int len2;
2547 int ret;
2548 luaL_Buffer b;
2549
Willy Tarreau47860ed2015-03-10 14:07:50 +01002550 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002551 if (unlikely(ret == 0))
2552 return 0;
2553
2554 if (unlikely(ret < 0)) {
2555 lua_pushnil(L);
2556 return -1;
2557 }
2558
2559 luaL_buffinit(L, &b);
2560 luaL_addlstring(&b, blk1, len1);
2561 if (unlikely(ret == 2))
2562 luaL_addlstring(&b, blk2, len2);
2563 luaL_pushresult(&b);
2564
2565 if (unlikely(ret == 2))
2566 return len1 + len2;
2567 return len1;
2568}
2569
2570/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2571 * a yield. This function keep the data in the buffer.
2572 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002573__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002574{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002575 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002576
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002577 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2578
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002579 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002580 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002581 return 1;
2582}
2583
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002584/* Check arguments for the function "hlua_channel_dup_yield". */
2585__LJMP static int hlua_channel_dup(lua_State *L)
2586{
2587 MAY_LJMP(check_args(L, 1, "dup"));
2588 MAY_LJMP(hlua_checkchannel(L, 1));
2589 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2590}
2591
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002592/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2593 * a yield. This function consumes the data in the buffer. It returns
2594 * a string containing the data or a nil pointer if no data are available
2595 * and the channel is closed.
2596 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002597__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002598{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002599 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002600 int ret;
2601
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002602 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002603
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002604 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002605 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002606 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002607
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002608 if (unlikely(ret == -1))
2609 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002610
Willy Tarreau47860ed2015-03-10 14:07:50 +01002611 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002612 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002613 return 1;
2614}
2615
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002616/* Check arguments for the fucntion "hlua_channel_get_yield". */
2617__LJMP static int hlua_channel_get(lua_State *L)
2618{
2619 MAY_LJMP(check_args(L, 1, "get"));
2620 MAY_LJMP(hlua_checkchannel(L, 1));
2621 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2622}
2623
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002624/* This functions consumes and returns one line. If the channel is closed,
2625 * and the last data does not contains a final '\n', the data are returned
2626 * without the final '\n'. When no more data are avalaible, it returns nil
2627 * value.
2628 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002629__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002630{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002631 char *blk1;
2632 char *blk2;
2633 int len1;
2634 int len2;
2635 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002636 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002637 int ret;
2638 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002639
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002640 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2641
Willy Tarreau47860ed2015-03-10 14:07:50 +01002642 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002643 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002644 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002645
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002646 if (ret == -1) {
2647 lua_pushnil(L);
2648 return 1;
2649 }
2650
2651 luaL_buffinit(L, &b);
2652 luaL_addlstring(&b, blk1, len1);
2653 len = len1;
2654 if (unlikely(ret == 2)) {
2655 luaL_addlstring(&b, blk2, len2);
2656 len += len2;
2657 }
2658 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002659 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002660 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002661 return 1;
2662}
2663
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002664/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2665__LJMP static int hlua_channel_getline(lua_State *L)
2666{
2667 MAY_LJMP(check_args(L, 1, "getline"));
2668 MAY_LJMP(hlua_checkchannel(L, 1));
2669 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2670}
2671
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002672/* This function takes a string as input, and append it at the
2673 * input side of channel. If the data is too big, but a space
2674 * is probably available after sending some data, the function
2675 * yield. If the data is bigger than the buffer, or if the
2676 * channel is closed, it returns -1. otherwise, it returns the
2677 * amount of data writed.
2678 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002679__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002680{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002681 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002682 size_t len;
2683 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2684 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2685 int ret;
2686 int max;
2687
Willy Tarreau47860ed2015-03-10 14:07:50 +01002688 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002689 if (max > len - l)
2690 max = len - l;
2691
Willy Tarreau47860ed2015-03-10 14:07:50 +01002692 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002693 if (ret == -2 || ret == -3) {
2694 lua_pushinteger(L, -1);
2695 return 1;
2696 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002697 if (ret == -1) {
2698 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002699 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002700 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002701 l += ret;
2702 lua_pop(L, 1);
2703 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002704 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002705
Willy Tarreau47860ed2015-03-10 14:07:50 +01002706 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2707 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002708 /* There are no space avalaible, and the output buffer is empty.
2709 * in this case, we cannot add more data, so we cannot yield,
2710 * we return the amount of copyied data.
2711 */
2712 return 1;
2713 }
2714 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002715 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002716 return 1;
2717}
2718
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002719/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002720 * of the writed string, or -1 if the channel is closed or if the
2721 * buffer size is too little for the data.
2722 */
2723__LJMP static int hlua_channel_append(lua_State *L)
2724{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002725 size_t len;
2726
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002727 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002728 MAY_LJMP(hlua_checkchannel(L, 1));
2729 MAY_LJMP(luaL_checklstring(L, 2, &len));
2730 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002731 lua_pushinteger(L, 0);
2732
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002733 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002734}
2735
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002736/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002737 * his process by cleaning the buffer. The result is a replacement
2738 * of the current data. It returns the length of the writed string,
2739 * or -1 if the channel is closed or if the buffer size is too
2740 * little for the data.
2741 */
2742__LJMP static int hlua_channel_set(lua_State *L)
2743{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002744 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002745
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002746 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002747 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002748 lua_pushinteger(L, 0);
2749
Willy Tarreau47860ed2015-03-10 14:07:50 +01002750 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002751
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002752 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002753}
2754
2755/* Append data in the output side of the buffer. This data is immediatly
2756 * sent. The fcuntion returns the ammount of data writed. If the buffer
2757 * cannot contains the data, the function yield. The function returns -1
2758 * if the channel is closed.
2759 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002760__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002761{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002762 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002763 size_t len;
2764 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2765 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2766 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002767 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002768
Willy Tarreau47860ed2015-03-10 14:07:50 +01002769 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002770 lua_pushinteger(L, -1);
2771 return 1;
2772 }
2773
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002774 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2775 * the request buffer if its not required.
2776 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002777 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002778 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002779 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002780 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002781 }
2782 }
2783
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002784 /* the writed data will be immediatly sent, so we can check
2785 * the avalaible space without taking in account the reserve.
2786 * The reserve is guaranted for the processing of incoming
2787 * data, because the buffer will be flushed.
2788 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002789 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002790
2791 /* If there are no space avalaible, and the output buffer is empty.
2792 * in this case, we cannot add more data, so we cannot yield,
2793 * we return the amount of copyied data.
2794 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002795 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002796 return 1;
2797
2798 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002799 if (max > len - l)
2800 max = len - l;
2801
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002802 /* The buffer avalaible size may be not contiguous. This test
2803 * detects a non contiguous buffer and realign it.
2804 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002805 if (bi_space_for_replace(chn->buf) < max)
2806 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002807
2808 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002809 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002810
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002811 /* buffer replace considers that the input part is filled.
2812 * so, I must forward these new data in the output part.
2813 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002814 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002815
2816 l += max;
2817 lua_pop(L, 1);
2818 lua_pushinteger(L, l);
2819
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002820 /* If there are no space avalaible, and the output buffer is empty.
2821 * in this case, we cannot add more data, so we cannot yield,
2822 * we return the amount of copyied data.
2823 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002824 max = chn->buf->size - buffer_len(chn->buf);
2825 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002826 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002827
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002828 if (l < len) {
2829 /* If we are waiting for space in the response buffer, we
2830 * must set the flag WAKERESWR. This flag required the task
2831 * wake up if any activity is detected on the response buffer.
2832 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002833 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002834 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002835 else
2836 HLUA_SET_WAKEREQWR(hlua);
2837 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002838 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002839
2840 return 1;
2841}
2842
2843/* Just a wraper of "_hlua_channel_send". This wrapper permits
2844 * yield the LUA process, and resume it without checking the
2845 * input arguments.
2846 */
2847__LJMP static int hlua_channel_send(lua_State *L)
2848{
2849 MAY_LJMP(check_args(L, 2, "send"));
2850 lua_pushinteger(L, 0);
2851
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002852 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002853}
2854
2855/* This function forward and amount of butes. The data pass from
2856 * the input side of the buffer to the output side, and can be
2857 * forwarded. This function never fails.
2858 *
2859 * The Lua function takes an amount of bytes to be forwarded in
2860 * imput. It returns the number of bytes forwarded.
2861 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002862__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002863{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002864 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002865 int len;
2866 int l;
2867 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002868 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002869
2870 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2871 len = MAY_LJMP(luaL_checkinteger(L, 2));
2872 l = MAY_LJMP(luaL_checkinteger(L, -1));
2873
2874 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002875 if (max > chn->buf->i)
2876 max = chn->buf->i;
2877 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002878 l += max;
2879
2880 lua_pop(L, 1);
2881 lua_pushinteger(L, l);
2882
2883 /* Check if it miss bytes to forward. */
2884 if (l < len) {
2885 /* The the input channel or the output channel are closed, we
2886 * must return the amount of data forwarded.
2887 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002888 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002889 return 1;
2890
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002891 /* If we are waiting for space data in the response buffer, we
2892 * must set the flag WAKERESWR. This flag required the task
2893 * wake up if any activity is detected on the response buffer.
2894 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002895 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002896 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002897 else
2898 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002899
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002900 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002901 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002902 }
2903
2904 return 1;
2905}
2906
2907/* Just check the input and prepare the stack for the previous
2908 * function "hlua_channel_forward_yield"
2909 */
2910__LJMP static int hlua_channel_forward(lua_State *L)
2911{
2912 MAY_LJMP(check_args(L, 2, "forward"));
2913 MAY_LJMP(hlua_checkchannel(L, 1));
2914 MAY_LJMP(luaL_checkinteger(L, 2));
2915
2916 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002917 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002918}
2919
2920/* Just returns the number of bytes available in the input
2921 * side of the buffer. This function never fails.
2922 */
2923__LJMP static int hlua_channel_get_in_len(lua_State *L)
2924{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002925 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002926
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002927 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002928 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002929 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002930 return 1;
2931}
2932
2933/* Just returns the number of bytes available in the output
2934 * side of the buffer. This function never fails.
2935 */
2936__LJMP static int hlua_channel_get_out_len(lua_State *L)
2937{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002938 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002939
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002940 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002941 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002942 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002943 return 1;
2944}
2945
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002946/*
2947 *
2948 *
2949 * Class Fetches
2950 *
2951 *
2952 */
2953
2954/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002955 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002956 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002957__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002958{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002959 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002960}
2961
2962/* This function creates and push in the stack a fetch object according
2963 * with a current TXN.
2964 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002965static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002966{
Willy Tarreau7073c472015-04-06 11:15:40 +02002967 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002968
2969 /* Check stack size. */
2970 if (!lua_checkstack(L, 3))
2971 return 0;
2972
2973 /* Create the object: obj[0] = userdata.
2974 * Note that the base of the Fetches object is the
2975 * transaction object.
2976 */
2977 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002978 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002979 lua_rawseti(L, -2, 0);
2980
Willy Tarreau7073c472015-04-06 11:15:40 +02002981 hsmp->s = txn->s;
2982 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01002983 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002984 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002985
2986 /* Pop a class sesison metatable and affect it to the userdata. */
2987 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2988 lua_setmetatable(L, -2);
2989
2990 return 1;
2991}
2992
2993/* This function is an LUA binding. It is called with each sample-fetch.
2994 * It uses closure argument to store the associated sample-fetch. It
2995 * returns only one argument or throws an error. An error is thrown
2996 * only if an error is encountered during the argument parsing. If
2997 * the "sample-fetch" function fails, nil is returned.
2998 */
2999__LJMP static int hlua_run_sample_fetch(lua_State *L)
3000{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003001 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003002 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003003 struct arg args[ARGM_NBARGS + 1];
3004 int i;
3005 struct sample smp;
3006
3007 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003008 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003009
3010 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003011 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003012
Thierry FOURNIERca988662015-12-20 18:43:03 +01003013 /* Check execution authorization. */
3014 if (f->use & SMP_USE_HTTP_ANY &&
3015 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3016 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3017 "is not available in Lua services", f->kw);
3018 WILL_LJMP(lua_error(L));
3019 }
3020
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003021 /* Get extra arguments. */
3022 for (i = 0; i < lua_gettop(L) - 1; i++) {
3023 if (i >= ARGM_NBARGS)
3024 break;
3025 hlua_lua2arg(L, i + 2, &args[i]);
3026 }
3027 args[i].type = ARGT_STOP;
3028
3029 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003030 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003031
3032 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003033 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003034 lua_pushfstring(L, "error in arguments");
3035 WILL_LJMP(lua_error(L));
3036 }
3037
3038 /* Initialise the sample. */
3039 memset(&smp, 0, sizeof(smp));
3040
3041 /* Run the sample fetch process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02003042 smp.px = hsmp->p;
3043 smp.sess = hsmp->s->sess;
3044 smp.strm = hsmp->s;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003045 smp.opt = hsmp->dir & SMP_OPT_DIR;
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003046 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003047 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003048 lua_pushstring(L, "");
3049 else
3050 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003051 return 1;
3052 }
3053
3054 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003055 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003056 hlua_smp2lua_str(L, &smp);
3057 else
3058 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003059 return 1;
3060}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003061
3062/*
3063 *
3064 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003065 * Class Converters
3066 *
3067 *
3068 */
3069
3070/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003071 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003072 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003073__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003074{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003075 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003076}
3077
3078/* This function creates and push in the stack a Converters object
3079 * according with a current TXN.
3080 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003081static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003082{
Willy Tarreau7073c472015-04-06 11:15:40 +02003083 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003084
3085 /* Check stack size. */
3086 if (!lua_checkstack(L, 3))
3087 return 0;
3088
3089 /* Create the object: obj[0] = userdata.
3090 * Note that the base of the Converters object is the
3091 * same than the TXN object.
3092 */
3093 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003094 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003095 lua_rawseti(L, -2, 0);
3096
Willy Tarreau7073c472015-04-06 11:15:40 +02003097 hsmp->s = txn->s;
3098 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003099 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003100 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003101
Willy Tarreau87b09662015-04-03 00:22:06 +02003102 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003103 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3104 lua_setmetatable(L, -2);
3105
3106 return 1;
3107}
3108
3109/* This function is an LUA binding. It is called with each converter.
3110 * It uses closure argument to store the associated converter. It
3111 * returns only one argument or throws an error. An error is thrown
3112 * only if an error is encountered during the argument parsing. If
3113 * the converter function function fails, nil is returned.
3114 */
3115__LJMP static int hlua_run_sample_conv(lua_State *L)
3116{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003117 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003118 struct sample_conv *conv;
3119 struct arg args[ARGM_NBARGS + 1];
3120 int i;
3121 struct sample smp;
3122
3123 /* Get closure arguments. */
3124 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
3125
3126 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003127 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003128
3129 /* Get extra arguments. */
3130 for (i = 0; i < lua_gettop(L) - 2; i++) {
3131 if (i >= ARGM_NBARGS)
3132 break;
3133 hlua_lua2arg(L, i + 3, &args[i]);
3134 }
3135 args[i].type = ARGT_STOP;
3136
3137 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003138 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003139
3140 /* Run the special args checker. */
3141 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3142 hlua_pusherror(L, "error in arguments");
3143 WILL_LJMP(lua_error(L));
3144 }
3145
3146 /* Initialise the sample. */
3147 if (!hlua_lua2smp(L, 2, &smp)) {
3148 hlua_pusherror(L, "error in the input argument");
3149 WILL_LJMP(lua_error(L));
3150 }
3151
3152 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003153 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003154 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003155 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003156 WILL_LJMP(lua_error(L));
3157 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003158 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3159 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003160 hlua_pusherror(L, "error during the input argument casting");
3161 WILL_LJMP(lua_error(L));
3162 }
3163
3164 /* Run the sample conversion process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02003165 smp.px = hsmp->p;
3166 smp.sess = hsmp->s->sess;
3167 smp.strm = hsmp->s;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003168 smp.opt = hsmp->dir & SMP_OPT_DIR;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003169 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003170 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003171 lua_pushstring(L, "");
3172 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003173 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003174 return 1;
3175 }
3176
3177 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003178 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003179 hlua_smp2lua_str(L, &smp);
3180 else
3181 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003182 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003183}
3184
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003185/*
3186 *
3187 *
3188 * Class AppletTCP
3189 *
3190 *
3191 */
3192
3193/* Returns a struct hlua_txn if the stack entry "ud" is
3194 * a class stream, otherwise it throws an error.
3195 */
3196__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3197{
3198 return (struct hlua_appctx *)MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
3199}
3200
3201/* This function creates and push in the stack an Applet object
3202 * according with a current TXN.
3203 */
3204static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3205{
3206 struct hlua_appctx *appctx;
3207 struct stream_interface *si = ctx->owner;
3208 struct stream *s = si_strm(si);
3209 struct proxy *p = s->be;
3210
3211 /* Check stack size. */
3212 if (!lua_checkstack(L, 3))
3213 return 0;
3214
3215 /* Create the object: obj[0] = userdata.
3216 * Note that the base of the Converters object is the
3217 * same than the TXN object.
3218 */
3219 lua_newtable(L);
3220 appctx = lua_newuserdata(L, sizeof(*appctx));
3221 lua_rawseti(L, -2, 0);
3222 appctx->appctx = ctx;
3223 appctx->htxn.s = s;
3224 appctx->htxn.p = p;
3225
3226 /* Create the "f" field that contains a list of fetches. */
3227 lua_pushstring(L, "f");
3228 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3229 return 0;
3230 lua_settable(L, -3);
3231
3232 /* Create the "sf" field that contains a list of stringsafe fetches. */
3233 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003234 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003235 return 0;
3236 lua_settable(L, -3);
3237
3238 /* Create the "c" field that contains a list of converters. */
3239 lua_pushstring(L, "c");
3240 if (!hlua_converters_new(L, &appctx->htxn, 0))
3241 return 0;
3242 lua_settable(L, -3);
3243
3244 /* Create the "sc" field that contains a list of stringsafe converters. */
3245 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003246 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003247 return 0;
3248 lua_settable(L, -3);
3249
3250 /* Pop a class stream metatable and affect it to the table. */
3251 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3252 lua_setmetatable(L, -2);
3253
3254 return 1;
3255}
3256
3257/* If expected data not yet available, it returns a yield. This function
3258 * consumes the data in the buffer. It returns a string containing the
3259 * data. This string can be empty.
3260 */
3261__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3262{
3263 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3264 struct stream_interface *si = appctx->appctx->owner;
3265 int ret;
3266 char *blk1;
3267 int len1;
3268 char *blk2;
3269 int len2;
3270
3271 /* Read the maximum amount of data avalaible. */
3272 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3273
3274 /* Data not yet avalaible. return yield. */
3275 if (ret == 0) {
3276 si_applet_cant_get(si);
3277 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3278 }
3279
3280 /* End of data: commit the total strings and return. */
3281 if (ret < 0) {
3282 luaL_pushresult(&appctx->b);
3283 return 1;
3284 }
3285
3286 /* Ensure that the block 2 length is usable. */
3287 if (ret == 1)
3288 len2 = 0;
3289
3290 /* dont check the max length read and dont check. */
3291 luaL_addlstring(&appctx->b, blk1, len1);
3292 luaL_addlstring(&appctx->b, blk2, len2);
3293
3294 /* Consume input channel output buffer data. */
3295 bo_skip(si_oc(si), len1 + len2);
3296 luaL_pushresult(&appctx->b);
3297 return 1;
3298}
3299
3300/* Check arguments for the fucntion "hlua_channel_get_yield". */
3301__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3302{
3303 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3304
3305 /* Initialise the string catenation. */
3306 luaL_buffinit(L, &appctx->b);
3307
3308 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3309}
3310
3311/* If expected data not yet available, it returns a yield. This function
3312 * consumes the data in the buffer. It returns a string containing the
3313 * data. This string can be empty.
3314 */
3315__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3316{
3317 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3318 struct stream_interface *si = appctx->appctx->owner;
3319 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3320 int ret;
3321 char *blk1;
3322 int len1;
3323 char *blk2;
3324 int len2;
3325
3326 /* Read the maximum amount of data avalaible. */
3327 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3328
3329 /* Data not yet avalaible. return yield. */
3330 if (ret == 0) {
3331 si_applet_cant_get(si);
3332 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3333 }
3334
3335 /* End of data: commit the total strings and return. */
3336 if (ret < 0) {
3337 luaL_pushresult(&appctx->b);
3338 return 1;
3339 }
3340
3341 /* Ensure that the block 2 length is usable. */
3342 if (ret == 1)
3343 len2 = 0;
3344
3345 if (len == -1) {
3346
3347 /* If len == -1, catenate all the data avalaile and
3348 * yield because we want to get all the data until
3349 * the end of data stream.
3350 */
3351 luaL_addlstring(&appctx->b, blk1, len1);
3352 luaL_addlstring(&appctx->b, blk2, len2);
3353 bo_skip(si_oc(si), len1 + len2);
3354 si_applet_cant_get(si);
3355 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3356
3357 } else {
3358
3359 /* Copy the fisrt block caping to the length required. */
3360 if (len1 > len)
3361 len1 = len;
3362 luaL_addlstring(&appctx->b, blk1, len1);
3363 len -= len1;
3364
3365 /* Copy the second block. */
3366 if (len2 > len)
3367 len2 = len;
3368 luaL_addlstring(&appctx->b, blk2, len2);
3369 len -= len2;
3370
3371 /* Consume input channel output buffer data. */
3372 bo_skip(si_oc(si), len1 + len2);
3373
3374 /* If we are no other data avalaible, yield waiting for new data. */
3375 if (len > 0) {
3376 lua_pushinteger(L, len);
3377 lua_replace(L, 2);
3378 si_applet_cant_get(si);
3379 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3380 }
3381
3382 /* return the result. */
3383 luaL_pushresult(&appctx->b);
3384 return 1;
3385 }
3386
3387 /* we never executes this */
3388 hlua_pusherror(L, "Lua: internal error");
3389 WILL_LJMP(lua_error(L));
3390 return 0;
3391}
3392
3393/* Check arguments for the fucntion "hlua_channel_get_yield". */
3394__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3395{
3396 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3397 int len = -1;
3398
3399 if (lua_gettop(L) > 2)
3400 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3401 if (lua_gettop(L) >= 2) {
3402 len = MAY_LJMP(luaL_checkinteger(L, 2));
3403 lua_pop(L, 1);
3404 }
3405
3406 /* Confirm or set the required length */
3407 lua_pushinteger(L, len);
3408
3409 /* Initialise the string catenation. */
3410 luaL_buffinit(L, &appctx->b);
3411
3412 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3413}
3414
3415/* Append data in the output side of the buffer. This data is immediatly
3416 * sent. The fcuntion returns the ammount of data writed. If the buffer
3417 * cannot contains the data, the function yield. The function returns -1
3418 * if the channel is closed.
3419 */
3420__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3421{
3422 size_t len;
3423 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3424 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3425 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3426 struct stream_interface *si = appctx->appctx->owner;
3427 struct channel *chn = si_ic(si);
3428 int max;
3429
3430 /* Get the max amount of data which can write as input in the channel. */
3431 max = channel_recv_max(chn);
3432 if (max > (len - l))
3433 max = len - l;
3434
3435 /* Copy data. */
3436 bi_putblk(chn, str + l, max);
3437
3438 /* update counters. */
3439 l += max;
3440 lua_pop(L, 1);
3441 lua_pushinteger(L, l);
3442
3443 /* If some data is not send, declares the situation to the
3444 * applet, and returns a yield.
3445 */
3446 if (l < len) {
3447 si_applet_cant_put(si);
3448 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3449 }
3450
3451 return 1;
3452}
3453
3454/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3455 * yield the LUA process, and resume it without checking the
3456 * input arguments.
3457 */
3458__LJMP static int hlua_applet_tcp_send(lua_State *L)
3459{
3460 MAY_LJMP(check_args(L, 2, "send"));
3461 lua_pushinteger(L, 0);
3462
3463 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3464}
3465
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003466/*
3467 *
3468 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003469 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003470 *
3471 *
3472 */
3473
3474/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003475 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003476 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003477__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003478{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003479 return (struct hlua_appctx *)MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003480}
3481
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003482/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003483 * according with a current TXN.
3484 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003485static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003486{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003487 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003488 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003489 struct stream_interface *si = ctx->owner;
3490 struct stream *s = si_strm(si);
3491 struct proxy *px = s->be;
3492 struct http_txn *txn = s->txn;
3493 const char *path;
3494 const char *end;
3495 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003496
3497 /* Check stack size. */
3498 if (!lua_checkstack(L, 3))
3499 return 0;
3500
3501 /* Create the object: obj[0] = userdata.
3502 * Note that the base of the Converters object is the
3503 * same than the TXN object.
3504 */
3505 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003506 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003507 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003508 appctx->appctx = ctx;
3509 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
3510 appctx->htxn.s = s;
3511 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003512
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003513 /* Create the "f" field that contains a list of fetches. */
3514 lua_pushstring(L, "f");
3515 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3516 return 0;
3517 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003518
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003519 /* Create the "sf" field that contains a list of stringsafe fetches. */
3520 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003521 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003522 return 0;
3523 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003524
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003525 /* Create the "c" field that contains a list of converters. */
3526 lua_pushstring(L, "c");
3527 if (!hlua_converters_new(L, &appctx->htxn, 0))
3528 return 0;
3529 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003530
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003531 /* Create the "sc" field that contains a list of stringsafe converters. */
3532 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003533 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003534 return 0;
3535 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003536
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003537 /* Stores the request method. */
3538 lua_pushstring(L, "method");
3539 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3540 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003541
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003542 /* Stores the http version. */
3543 lua_pushstring(L, "version");
3544 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3545 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003546
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003547 /* creates an array of headers. hlua_http_get_headers() crates and push
3548 * the array on the top of the stack.
3549 */
3550 lua_pushstring(L, "headers");
3551 htxn.s = s;
3552 htxn.p = px;
3553 htxn.dir = SMP_OPT_DIR_REQ;
3554 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3555 return 0;
3556 lua_settable(L, -3);
3557
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003558 /* Get path and qs */
3559 path = http_get_path(txn);
3560 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3561 p = path;
3562 while (p < end && *p != '?')
3563 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003564
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003565 /* Stores the request path. */
3566 lua_pushstring(L, "path");
3567 lua_pushlstring(L, path, p - path);
3568 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003569
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003570 /* Stores the query string. */
3571 lua_pushstring(L, "qs");
3572 if (*p == '?')
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003573 p++;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003574 lua_pushlstring(L, p, end - p);
3575 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003576
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003577 /* Stores the request path. */
3578 lua_pushstring(L, "length");
3579 lua_pushinteger(L, txn->req.body_len);
3580 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003581
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003582 /* Create an array of HTTP request headers. */
3583 lua_pushstring(L, "headers");
3584 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3585 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003586
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003587 /* Create an empty array of HTTP request headers. */
3588 lua_pushstring(L, "response");
3589 lua_newtable(L);
3590 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003591
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003592 /* Pop a class stream metatable and affect it to the table. */
3593 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3594 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003595
3596 return 1;
3597}
3598
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003599/* If expected data not yet available, it returns a yield. This function
3600 * consumes the data in the buffer. It returns a string containing the
3601 * data. This string can be empty.
3602 */
3603__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003604{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003605 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3606 struct stream_interface *si = appctx->appctx->owner;
3607 struct channel *chn = si_ic(si);
3608 int ret;
3609 char *blk1;
3610 int len1;
3611 char *blk2;
3612 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003613
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003614 /* Maybe we cant send a 100-continue ? */
3615 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3616 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3617 /* if ret == -2 or -3 the channel closed or the message si too
3618 * big for the buffers. We cant send anything. So, we ignoring
3619 * the error, considers that the 100-continue is sent, and try
3620 * to receive.
3621 * If ret is -1, we dont have room in the buffer, so we yield.
3622 */
3623 if (ret == -1) {
3624 si_applet_cant_put(si);
3625 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3626 }
3627 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3628 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003629
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003630 /* Check for the end of the data. */
3631 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3632 luaL_pushresult(&appctx->b);
3633 return 1;
3634 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003635
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003636 /* Read the maximum amount of data avalaible. */
3637 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003638
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003639 /* Data not yet avalaible. return yield. */
3640 if (ret == 0) {
3641 si_applet_cant_get(si);
3642 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3643 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003644
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003645 /* End of data: commit the total strings and return. */
3646 if (ret < 0) {
3647 luaL_pushresult(&appctx->b);
3648 return 1;
3649 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003650
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003651 /* Ensure that the block 2 length is usable. */
3652 if (ret == 1)
3653 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003654
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003655 /* Copy the fisrt block caping to the length required. */
3656 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3657 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3658 luaL_addlstring(&appctx->b, blk1, len1);
3659 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003660
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003661 /* Copy the second block. */
3662 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3663 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3664 luaL_addlstring(&appctx->b, blk2, len2);
3665 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003666
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003667 /* Consume input channel output buffer data. */
3668 bo_skip(si_oc(si), len1 + len2);
3669 luaL_pushresult(&appctx->b);
3670 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003671}
3672
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003673/* Check arguments for the fucntion "hlua_channel_get_yield". */
3674__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003675{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003676 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003677
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003678 /* Initialise the string catenation. */
3679 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003680
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003681 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003682}
3683
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003684/* If expected data not yet available, it returns a yield. This function
3685 * consumes the data in the buffer. It returns a string containing the
3686 * data. This string can be empty.
3687 */
3688__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003689{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003690 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3691 struct stream_interface *si = appctx->appctx->owner;
3692 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3693 struct channel *chn = si_ic(si);
3694 int ret;
3695 char *blk1;
3696 int len1;
3697 char *blk2;
3698 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003699
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003700 /* Maybe we cant send a 100-continue ? */
3701 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3702 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3703 /* if ret == -2 or -3 the channel closed or the message si too
3704 * big for the buffers. We cant send anything. So, we ignoring
3705 * the error, considers that the 100-continue is sent, and try
3706 * to receive.
3707 * If ret is -1, we dont have room in the buffer, so we yield.
3708 */
3709 if (ret == -1) {
3710 si_applet_cant_put(si);
3711 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3712 }
3713 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3714 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003715
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003716 /* Read the maximum amount of data avalaible. */
3717 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003718
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003719 /* Data not yet avalaible. return yield. */
3720 if (ret == 0) {
3721 si_applet_cant_get(si);
3722 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3723 }
3724
3725 /* End of data: commit the total strings and return. */
3726 if (ret < 0) {
3727 luaL_pushresult(&appctx->b);
3728 return 1;
3729 }
3730
3731 /* Ensure that the block 2 length is usable. */
3732 if (ret == 1)
3733 len2 = 0;
3734
3735 /* Copy the fisrt block caping to the length required. */
3736 if (len1 > len)
3737 len1 = len;
3738 luaL_addlstring(&appctx->b, blk1, len1);
3739 len -= len1;
3740
3741 /* Copy the second block. */
3742 if (len2 > len)
3743 len2 = len;
3744 luaL_addlstring(&appctx->b, blk2, len2);
3745 len -= len2;
3746
3747 /* Consume input channel output buffer data. */
3748 bo_skip(si_oc(si), len1 + len2);
3749 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
3750 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
3751
3752 /* If we are no other data avalaible, yield waiting for new data. */
3753 if (len > 0) {
3754 lua_pushinteger(L, len);
3755 lua_replace(L, 2);
3756 si_applet_cant_get(si);
3757 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3758 }
3759
3760 /* return the result. */
3761 luaL_pushresult(&appctx->b);
3762 return 1;
3763}
3764
3765/* Check arguments for the fucntion "hlua_channel_get_yield". */
3766__LJMP static int hlua_applet_http_recv(lua_State *L)
3767{
3768 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3769 int len = -1;
3770
3771 /* Check arguments. */
3772 if (lua_gettop(L) > 2)
3773 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3774 if (lua_gettop(L) >= 2) {
3775 len = MAY_LJMP(luaL_checkinteger(L, 2));
3776 lua_pop(L, 1);
3777 }
3778
3779 /* Check the required length */
3780 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3781 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3782 lua_pushinteger(L, len);
3783
3784 /* Initialise the string catenation. */
3785 luaL_buffinit(L, &appctx->b);
3786
3787 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
3788}
3789
3790/* Append data in the output side of the buffer. This data is immediatly
3791 * sent. The fcuntion returns the ammount of data writed. If the buffer
3792 * cannot contains the data, the function yield. The function returns -1
3793 * if the channel is closed.
3794 */
3795__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
3796{
3797 size_t len;
3798 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3799 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3800 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3801 struct stream_interface *si = appctx->appctx->owner;
3802 struct channel *chn = si_ic(si);
3803 int max;
3804
3805 /* Get the max amount of data which can write as input in the channel. */
3806 max = channel_recv_max(chn);
3807 if (max > (len - l))
3808 max = len - l;
3809
3810 /* Copy data. */
3811 bi_putblk(chn, str + l, max);
3812
3813 /* update counters. */
3814 l += max;
3815 lua_pop(L, 1);
3816 lua_pushinteger(L, l);
3817
3818 /* If some data is not send, declares the situation to the
3819 * applet, and returns a yield.
3820 */
3821 if (l < len) {
3822 si_applet_cant_put(si);
3823 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
3824 }
3825
3826 return 1;
3827}
3828
3829/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
3830 * yield the LUA process, and resume it without checking the
3831 * input arguments.
3832 */
3833__LJMP static int hlua_applet_http_send(lua_State *L)
3834{
3835 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3836 size_t len;
3837 char hex[10];
3838
3839 MAY_LJMP(luaL_checklstring(L, 2, &len));
3840
3841 /* If transfer encoding chunked is selected, we surround the data
3842 * by chunk data.
3843 */
3844 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
3845 snprintf(hex, 9, "%x", (unsigned int)len);
3846 lua_pushfstring(L, "%s\r\n", hex);
3847 lua_insert(L, 2); /* swap the last 2 entries. */
3848 lua_pushstring(L, "\r\n");
3849 lua_concat(L, 3);
3850 }
3851
3852 /* This interger is used for followinf the amount of data sent. */
3853 lua_pushinteger(L, 0);
3854
3855 /* We want to send some data. Headers must be sent. */
3856 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
3857 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
3858 WILL_LJMP(lua_error(L));
3859 }
3860
3861 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
3862}
3863
3864__LJMP static int hlua_applet_http_addheader(lua_State *L)
3865{
3866 const char *name;
3867 int ret;
3868
3869 MAY_LJMP(hlua_checkapplet_http(L, 1));
3870 name = MAY_LJMP(luaL_checkstring(L, 2));
3871 MAY_LJMP(luaL_checkstring(L, 3));
3872
3873 /* Push in the stack the "response" entry. */
3874 ret = lua_getfield(L, 1, "response");
3875 if (ret != LUA_TTABLE) {
3876 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
3877 "is expected as an array. %s found", lua_typename(L, ret));
3878 WILL_LJMP(lua_error(L));
3879 }
3880
3881 /* check if the header is already registered if it is not
3882 * the case, register it.
3883 */
3884 ret = lua_getfield(L, -1, name);
3885 if (ret == LUA_TNIL) {
3886
3887 /* Entry not found. */
3888 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
3889
3890 /* Insert the new header name in the array in the top of the stack.
3891 * It left the new array in the top of the stack.
3892 */
3893 lua_newtable(L);
3894 lua_pushvalue(L, 2);
3895 lua_pushvalue(L, -2);
3896 lua_settable(L, -4);
3897
3898 } else if (ret != LUA_TTABLE) {
3899
3900 /* corruption error. */
3901 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
3902 "is expected as an array. %s found", name, lua_typename(L, ret));
3903 WILL_LJMP(lua_error(L));
3904 }
3905
3906 /* Now the top od thestack is an array of values. We push
3907 * the header value as new entry.
3908 */
3909 lua_pushvalue(L, 3);
3910 ret = lua_rawlen(L, -2);
3911 lua_rawseti(L, -2, ret + 1);
3912 lua_pushboolean(L, 1);
3913 return 1;
3914}
3915
3916__LJMP static int hlua_applet_http_status(lua_State *L)
3917{
3918 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3919 int status = MAY_LJMP(luaL_checkinteger(L, 2));
3920
3921 if (status < 100 || status > 599) {
3922 lua_pushboolean(L, 0);
3923 return 1;
3924 }
3925
3926 appctx->appctx->ctx.hlua_apphttp.status = status;
3927 lua_pushboolean(L, 1);
3928 return 1;
3929}
3930
3931/* We will build the status line and the headers of the HTTP response.
3932 * We will try send at once if its not possible, we give back the hand
3933 * waiting for more room.
3934 */
3935__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
3936{
3937 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3938 struct stream_interface *si = appctx->appctx->owner;
3939 struct channel *chn = si_ic(si);
3940 int ret;
3941 size_t len;
3942 const char *msg;
3943
3944 /* Get the message as the first argument on the stack. */
3945 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
3946
3947 /* Send the message at once. */
3948 ret = bi_putblk(chn, msg, len);
3949
3950 /* if ret == -2 or -3 the channel closed or the message si too
3951 * big for the buffers.
3952 */
3953 if (ret == -2 || ret == -3) {
3954 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
3955 WILL_LJMP(lua_error(L));
3956 }
3957
3958 /* If ret is -1, we dont have room in the buffer, so we yield. */
3959 if (ret == -1) {
3960 si_applet_cant_put(si);
3961 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
3962 }
3963
3964 /* Headers sent, set the flag. */
3965 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
3966 return 0;
3967}
3968
3969__LJMP static int hlua_applet_http_start_response(lua_State *L)
3970{
3971 struct chunk *tmp = get_trash_chunk();
3972 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003973 const char *name;
3974 const char *value;
3975 int id;
3976 int hdr_connection = 0;
3977 int hdr_contentlength = -1;
3978 int hdr_chunked = 0;
3979
3980 /* Use the same http version than the request. */
3981 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01003982 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003983 appctx->appctx->ctx.hlua_apphttp.status,
3984 get_reason(appctx->appctx->ctx.hlua_apphttp.status));
3985
3986 /* Get the array associated to the field "response" in the object AppletHTTP. */
3987 lua_pushvalue(L, 0);
3988 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
3989 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
3990 appctx->appctx->rule->arg.hlua_rule->fcn.name);
3991 WILL_LJMP(lua_error(L));
3992 }
3993
3994 /* Browse the list of headers. */
3995 lua_pushnil(L);
3996 while(lua_next(L, -2) != 0) {
3997
3998 /* We expect a string as -2. */
3999 if (lua_type(L, -2) != LUA_TSTRING) {
4000 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4001 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4002 lua_typename(L, lua_type(L, -2)));
4003 WILL_LJMP(lua_error(L));
4004 }
4005 name = lua_tostring(L, -2);
4006
4007 /* We expect an array as -1. */
4008 if (lua_type(L, -1) != LUA_TTABLE) {
4009 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4010 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4011 name,
4012 lua_typename(L, lua_type(L, -1)));
4013 WILL_LJMP(lua_error(L));
4014 }
4015
4016 /* Browse the table who is on the top of the stack. */
4017 lua_pushnil(L);
4018 while(lua_next(L, -2) != 0) {
4019
4020 /* We expect a number as -2. */
4021 if (lua_type(L, -2) != LUA_TNUMBER) {
4022 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4023 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4024 name,
4025 lua_typename(L, lua_type(L, -2)));
4026 WILL_LJMP(lua_error(L));
4027 }
4028 id = lua_tointeger(L, -2);
4029
4030 /* We expect a string as -2. */
4031 if (lua_type(L, -1) != LUA_TSTRING) {
4032 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4033 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4034 name, id,
4035 lua_typename(L, lua_type(L, -1)));
4036 WILL_LJMP(lua_error(L));
4037 }
4038 value = lua_tostring(L, -1);
4039
4040 /* Catenate a new header. */
4041 chunk_appendf(tmp, "%s: %s\r\n", name, value);
4042
4043 /* Protocol checks. */
4044
4045 /* Check if the header conneciton is present. */
4046 if (strcasecmp("connection", name) == 0)
4047 hdr_connection = 1;
4048
4049 /* Copy the header content length. The length conversion
4050 * is done without control. If it contains a ad value, this
4051 * is not our problem.
4052 */
4053 if (strcasecmp("content-length", name) == 0)
4054 hdr_contentlength = atoi(value);
4055
4056 /* Check if the client annouces a transfer-encoding chunked it self. */
4057 if (strcasecmp("transfer-encoding", name) == 0 &&
4058 strcasecmp("chunked", value) == 0)
4059 hdr_chunked = 1;
4060
4061 /* Remove the array from the stack, and get next element with a remaining string. */
4062 lua_pop(L, 1);
4063 }
4064
4065 /* Remove the array from the stack, and get next element with a remaining string. */
4066 lua_pop(L, 1);
4067 }
4068
4069 /* If the http protocol version is 1.1, we expect an header "connection" set
4070 * to "close" to be HAProxy/keeplive compliant. Otherwise, we expect nothing.
4071 * If the header conneciton is present, don't change it, if it is not present,
4072 * we must set.
4073 *
4074 * we set a "connection: close" header for ensuring that the keepalive will be
4075 * respected by haproxy. HAProcy considers that the application cloe the connection
4076 * and it keep the connection from the client open.
4077 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004078 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 && !hdr_connection)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004079 chunk_appendf(tmp, "Connection: close\r\n");
4080
4081 /* If we dont have a content-length set, we must announce a transfer enconding
4082 * chunked. This is required by haproxy for the keepalive compliance.
4083 * If the applet annouce a transfer-encoding chunked itslef, don't
4084 * do anything.
4085 */
4086 if (hdr_contentlength == -1 && hdr_chunked == 0) {
4087 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4088 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4089 }
4090
4091 /* Finalize headers. */
4092 chunk_appendf(tmp, "\r\n");
4093
4094 /* Remove the last entry and the array of headers */
4095 lua_pop(L, 2);
4096
4097 /* Push the headers block. */
4098 lua_pushlstring(L, tmp->str, tmp->len);
4099
4100 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4101}
4102
4103/*
4104 *
4105 *
4106 * Class HTTP
4107 *
4108 *
4109 */
4110
4111/* Returns a struct hlua_txn if the stack entry "ud" is
4112 * a class stream, otherwise it throws an error.
4113 */
4114__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4115{
4116 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
4117}
4118
4119/* This function creates and push in the stack a HTTP object
4120 * according with a current TXN.
4121 */
4122static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4123{
4124 struct hlua_txn *htxn;
4125
4126 /* Check stack size. */
4127 if (!lua_checkstack(L, 3))
4128 return 0;
4129
4130 /* Create the object: obj[0] = userdata.
4131 * Note that the base of the Converters object is the
4132 * same than the TXN object.
4133 */
4134 lua_newtable(L);
4135 htxn = lua_newuserdata(L, sizeof(*htxn));
4136 lua_rawseti(L, -2, 0);
4137
4138 htxn->s = txn->s;
4139 htxn->p = txn->p;
4140
4141 /* Pop a class stream metatable and affect it to the table. */
4142 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4143 lua_setmetatable(L, -2);
4144
4145 return 1;
4146}
4147
4148/* This function creates ans returns an array of HTTP headers.
4149 * This function does not fails. It is used as wrapper with the
4150 * 2 following functions.
4151 */
4152__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4153{
4154 const char *cur_ptr, *cur_next, *p;
4155 int old_idx, cur_idx;
4156 struct hdr_idx_elem *cur_hdr;
4157 const char *hn, *hv;
4158 int hnl, hvl;
4159 int type;
4160 const char *in;
4161 char *out;
4162 int len;
4163
4164 /* Create the table. */
4165 lua_newtable(L);
4166
4167 if (!htxn->s->txn)
4168 return 1;
4169
4170 /* Build array of headers. */
4171 old_idx = 0;
4172 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4173
4174 while (1) {
4175 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4176 if (!cur_idx)
4177 break;
4178 old_idx = cur_idx;
4179
4180 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4181 cur_ptr = cur_next;
4182 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4183
4184 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4185 * and the next header starts at cur_next. We'll check
4186 * this header in the list as well as against the default
4187 * rule.
4188 */
4189
4190 /* look for ': *'. */
4191 hn = cur_ptr;
4192 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4193 if (p >= cur_ptr+cur_hdr->len)
4194 continue;
4195 hnl = p - hn;
4196 p++;
4197 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4198 p++;
4199 if (p >= cur_ptr+cur_hdr->len)
4200 continue;
4201 hv = p;
4202 hvl = cur_ptr+cur_hdr->len-p;
4203
4204 /* Lowercase the key. Don't check the size of trash, it have
4205 * the size of one buffer and the input data contains in one
4206 * buffer.
4207 */
4208 out = trash.str;
4209 for (in=hn; in<hn+hnl; in++, out++)
4210 *out = tolower(*in);
4211 *out = '\0';
4212
4213 /* Check for existing entry:
4214 * assume that the table is on the top of the stack, and
4215 * push the key in the stack, the function lua_gettable()
4216 * perform the lookup.
4217 */
4218 lua_pushlstring(L, trash.str, hnl);
4219 lua_gettable(L, -2);
4220 type = lua_type(L, -1);
4221
4222 switch (type) {
4223 case LUA_TNIL:
4224 /* Table not found, create it. */
4225 lua_pop(L, 1); /* remove the nil value. */
4226 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4227 lua_newtable(L); /* create and push empty table. */
4228 lua_pushlstring(L, hv, hvl); /* push header value. */
4229 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4230 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4231 break;
4232
4233 case LUA_TTABLE:
4234 /* Entry found: push the value in the table. */
4235 len = lua_rawlen(L, -1);
4236 lua_pushlstring(L, hv, hvl); /* push header value. */
4237 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4238 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4239 break;
4240
4241 default:
4242 /* Other cases are errors. */
4243 hlua_pusherror(L, "internal error during the parsing of headers.");
4244 WILL_LJMP(lua_error(L));
4245 }
4246 }
4247
4248 return 1;
4249}
4250
4251__LJMP static int hlua_http_req_get_headers(lua_State *L)
4252{
4253 struct hlua_txn *htxn;
4254
4255 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4256 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4257
4258 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4259}
4260
4261__LJMP static int hlua_http_res_get_headers(lua_State *L)
4262{
4263 struct hlua_txn *htxn;
4264
4265 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4266 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4267
4268 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4269}
4270
4271/* This function replace full header, or just a value in
4272 * the request or in the response. It is a wrapper fir the
4273 * 4 following functions.
4274 */
4275__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4276 struct http_msg *msg, int action)
4277{
4278 size_t name_len;
4279 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4280 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4281 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4282 struct my_regex re;
4283
4284 if (!regex_comp(reg, &re, 1, 1, NULL))
4285 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4286
4287 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4288 regex_free(&re);
4289 return 0;
4290}
4291
4292__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4293{
4294 struct hlua_txn *htxn;
4295
4296 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4297 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4298
4299 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4300}
4301
4302__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4303{
4304 struct hlua_txn *htxn;
4305
4306 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4307 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4308
4309 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4310}
4311
4312__LJMP static int hlua_http_req_rep_val(lua_State *L)
4313{
4314 struct hlua_txn *htxn;
4315
4316 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4317 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4318
4319 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4320}
4321
4322__LJMP static int hlua_http_res_rep_val(lua_State *L)
4323{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004324 struct hlua_txn *htxn;
4325
4326 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4327 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4328
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004329 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004330}
4331
4332/* This function deletes all the occurences of an header.
4333 * It is a wrapper for the 2 following functions.
4334 */
4335__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4336{
4337 size_t len;
4338 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4339 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004340 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004341
4342 ctx.idx = 0;
4343 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4344 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4345 return 0;
4346}
4347
4348__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4349{
4350 struct hlua_txn *htxn;
4351
4352 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4353 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4354
Willy Tarreaueee5b512015-04-03 23:46:31 +02004355 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004356}
4357
4358__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4359{
4360 struct hlua_txn *htxn;
4361
4362 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4363 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4364
Willy Tarreaueee5b512015-04-03 23:46:31 +02004365 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004366}
4367
4368/* This function adds an header. It is a wrapper used by
4369 * the 2 following functions.
4370 */
4371__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4372{
4373 size_t name_len;
4374 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4375 size_t value_len;
4376 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4377 char *p;
4378
4379 /* Check length. */
4380 trash.len = value_len + name_len + 2;
4381 if (trash.len > trash.size)
4382 return 0;
4383
4384 /* Creates the header string. */
4385 p = trash.str;
4386 memcpy(p, name, name_len);
4387 p += name_len;
4388 *p = ':';
4389 p++;
4390 *p = ' ';
4391 p++;
4392 memcpy(p, value, value_len);
4393
Willy Tarreaueee5b512015-04-03 23:46:31 +02004394 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004395 trash.str, trash.len) != 0);
4396
4397 return 0;
4398}
4399
4400__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4401{
4402 struct hlua_txn *htxn;
4403
4404 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4405 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4406
Willy Tarreaueee5b512015-04-03 23:46:31 +02004407 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004408}
4409
4410__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4411{
4412 struct hlua_txn *htxn;
4413
4414 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4415 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4416
Willy Tarreaueee5b512015-04-03 23:46:31 +02004417 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004418}
4419
4420static int hlua_http_req_set_hdr(lua_State *L)
4421{
4422 struct hlua_txn *htxn;
4423
4424 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4425 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4426
Willy Tarreaueee5b512015-04-03 23:46:31 +02004427 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4428 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004429}
4430
4431static int hlua_http_res_set_hdr(lua_State *L)
4432{
4433 struct hlua_txn *htxn;
4434
4435 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4436 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4437
Willy Tarreaueee5b512015-04-03 23:46:31 +02004438 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4439 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004440}
4441
4442/* This function set the method. */
4443static int hlua_http_req_set_meth(lua_State *L)
4444{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004445 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004446 size_t name_len;
4447 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004448
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004449 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004450 return 1;
4451}
4452
4453/* This function set the method. */
4454static int hlua_http_req_set_path(lua_State *L)
4455{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004456 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004457 size_t name_len;
4458 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004459 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004460 return 1;
4461}
4462
4463/* This function set the query-string. */
4464static int hlua_http_req_set_query(lua_State *L)
4465{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004466 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004467 size_t name_len;
4468 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004469
4470 /* Check length. */
4471 if (name_len > trash.size - 1) {
4472 lua_pushboolean(L, 0);
4473 return 1;
4474 }
4475
4476 /* Add the mark question as prefix. */
4477 chunk_reset(&trash);
4478 trash.str[trash.len++] = '?';
4479 memcpy(trash.str + trash.len, name, name_len);
4480 trash.len += name_len;
4481
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004482 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004483 return 1;
4484}
4485
4486/* This function set the uri. */
4487static int hlua_http_req_set_uri(lua_State *L)
4488{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004489 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004490 size_t name_len;
4491 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004492
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004493 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004494 return 1;
4495}
4496
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004497/* This function set the response code. */
4498static int hlua_http_res_set_status(lua_State *L)
4499{
4500 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4501 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
4502
4503 http_set_status(code, htxn->s);
4504 return 0;
4505}
4506
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004507/*
4508 *
4509 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004510 * Class TXN
4511 *
4512 *
4513 */
4514
4515/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004516 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004517 */
4518__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4519{
4520 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
4521}
4522
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004523__LJMP static int hlua_set_var(lua_State *L)
4524{
4525 struct hlua_txn *htxn;
4526 const char *name;
4527 size_t len;
4528 struct sample smp;
4529
4530 MAY_LJMP(check_args(L, 3, "set_var"));
4531
4532 /* It is useles to retrieve the stream, but this function
4533 * runs only in a stream context.
4534 */
4535 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4536 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4537
4538 /* Converts the third argument in a sample. */
4539 hlua_lua2smp(L, 3, &smp);
4540
4541 /* Store the sample in a variable. */
4542 vars_set_by_name(name, len, htxn->s, &smp);
4543 return 0;
4544}
4545
4546__LJMP static int hlua_get_var(lua_State *L)
4547{
4548 struct hlua_txn *htxn;
4549 const char *name;
4550 size_t len;
4551 struct sample smp;
4552
4553 MAY_LJMP(check_args(L, 2, "get_var"));
4554
4555 /* It is useles to retrieve the stream, but this function
4556 * runs only in a stream context.
4557 */
4558 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4559 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4560
4561 if (!vars_get_by_name(name, len, htxn->s, &smp)) {
4562 lua_pushnil(L);
4563 return 1;
4564 }
4565
4566 return hlua_smp2lua(L, &smp);
4567}
4568
Willy Tarreau59551662015-03-10 14:23:13 +01004569__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004570{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004571 struct hlua *hlua;
4572
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004573 MAY_LJMP(check_args(L, 2, "set_priv"));
4574
Willy Tarreau87b09662015-04-03 00:22:06 +02004575 /* It is useles to retrieve the stream, but this function
4576 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004577 */
4578 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004579 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004580
4581 /* Remove previous value. */
4582 if (hlua->Mref != -1)
4583 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
4584
4585 /* Get and store new value. */
4586 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4587 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4588
4589 return 0;
4590}
4591
Willy Tarreau59551662015-03-10 14:23:13 +01004592__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004593{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004594 struct hlua *hlua;
4595
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004596 MAY_LJMP(check_args(L, 1, "get_priv"));
4597
Willy Tarreau87b09662015-04-03 00:22:06 +02004598 /* It is useles to retrieve the stream, but this function
4599 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004600 */
4601 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004602 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004603
4604 /* Push configuration index in the stack. */
4605 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4606
4607 return 1;
4608}
4609
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004610/* Create stack entry containing a class TXN. This function
4611 * return 0 if the stack does not contains free slots,
4612 * otherwise it returns 1.
4613 */
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004614static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004615{
Willy Tarreaude491382015-04-06 11:04:28 +02004616 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004617
4618 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004619 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004620 return 0;
4621
4622 /* NOTE: The allocation never fails. The failure
4623 * throw an error, and the function never returns.
4624 * if the throw is not avalaible, the process is aborted.
4625 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004626 /* Create the object: obj[0] = userdata. */
4627 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004628 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004629 lua_rawseti(L, -2, 0);
4630
Willy Tarreaude491382015-04-06 11:04:28 +02004631 htxn->s = s;
4632 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004633 htxn->dir = dir;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004634
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004635 /* Create the "f" field that contains a list of fetches. */
4636 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004637 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004638 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004639 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004640
4641 /* Create the "sf" field that contains a list of stringsafe fetches. */
4642 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004643 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004644 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004645 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004646
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004647 /* Create the "c" field that contains a list of converters. */
4648 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004649 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004650 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004651 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004652
4653 /* Create the "sc" field that contains a list of stringsafe converters. */
4654 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004655 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004656 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004657 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004658
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004659 /* Create the "req" field that contains the request channel object. */
4660 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004661 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004662 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004663 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004664
4665 /* Create the "res" field that contains the response channel object. */
4666 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004667 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004668 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004669 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004670
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004671 /* Creates the HTTP object is the current proxy allows http. */
4672 lua_pushstring(L, "http");
4673 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02004674 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004675 return 0;
4676 }
4677 else
4678 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004679 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004680
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004681 /* Pop a class sesison metatable and affect it to the userdata. */
4682 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
4683 lua_setmetatable(L, -2);
4684
4685 return 1;
4686}
4687
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004688__LJMP static int hlua_txn_deflog(lua_State *L)
4689{
4690 const char *msg;
4691 struct hlua_txn *htxn;
4692
4693 MAY_LJMP(check_args(L, 2, "deflog"));
4694 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4695 msg = MAY_LJMP(luaL_checkstring(L, 2));
4696
4697 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
4698 return 0;
4699}
4700
4701__LJMP static int hlua_txn_log(lua_State *L)
4702{
4703 int level;
4704 const char *msg;
4705 struct hlua_txn *htxn;
4706
4707 MAY_LJMP(check_args(L, 3, "log"));
4708 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4709 level = MAY_LJMP(luaL_checkinteger(L, 2));
4710 msg = MAY_LJMP(luaL_checkstring(L, 3));
4711
4712 if (level < 0 || level >= NB_LOG_LEVELS)
4713 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4714
4715 hlua_sendlog(htxn->s->be, level, msg);
4716 return 0;
4717}
4718
4719__LJMP static int hlua_txn_log_debug(lua_State *L)
4720{
4721 const char *msg;
4722 struct hlua_txn *htxn;
4723
4724 MAY_LJMP(check_args(L, 2, "Debug"));
4725 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4726 msg = MAY_LJMP(luaL_checkstring(L, 2));
4727 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
4728 return 0;
4729}
4730
4731__LJMP static int hlua_txn_log_info(lua_State *L)
4732{
4733 const char *msg;
4734 struct hlua_txn *htxn;
4735
4736 MAY_LJMP(check_args(L, 2, "Info"));
4737 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4738 msg = MAY_LJMP(luaL_checkstring(L, 2));
4739 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
4740 return 0;
4741}
4742
4743__LJMP static int hlua_txn_log_warning(lua_State *L)
4744{
4745 const char *msg;
4746 struct hlua_txn *htxn;
4747
4748 MAY_LJMP(check_args(L, 2, "Warning"));
4749 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4750 msg = MAY_LJMP(luaL_checkstring(L, 2));
4751 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
4752 return 0;
4753}
4754
4755__LJMP static int hlua_txn_log_alert(lua_State *L)
4756{
4757 const char *msg;
4758 struct hlua_txn *htxn;
4759
4760 MAY_LJMP(check_args(L, 2, "Alert"));
4761 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4762 msg = MAY_LJMP(luaL_checkstring(L, 2));
4763 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
4764 return 0;
4765}
4766
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004767__LJMP static int hlua_txn_set_loglevel(lua_State *L)
4768{
4769 struct hlua_txn *htxn;
4770 int ll;
4771
4772 MAY_LJMP(check_args(L, 2, "set_loglevel"));
4773 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4774 ll = MAY_LJMP(luaL_checkinteger(L, 2));
4775
4776 if (ll < 0 || ll > 7)
4777 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
4778
4779 htxn->s->logs.level = ll;
4780 return 0;
4781}
4782
4783__LJMP static int hlua_txn_set_tos(lua_State *L)
4784{
4785 struct hlua_txn *htxn;
4786 struct connection *cli_conn;
4787 int tos;
4788
4789 MAY_LJMP(check_args(L, 2, "set_tos"));
4790 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4791 tos = MAY_LJMP(luaL_checkinteger(L, 2));
4792
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004793 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004794 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
4795
4796 return 0;
4797}
4798
4799__LJMP static int hlua_txn_set_mark(lua_State *L)
4800{
4801#ifdef SO_MARK
4802 struct hlua_txn *htxn;
4803 struct connection *cli_conn;
4804 int mark;
4805
4806 MAY_LJMP(check_args(L, 2, "set_mark"));
4807 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4808 mark = MAY_LJMP(luaL_checkinteger(L, 2));
4809
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004810 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02004811 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004812#endif
4813 return 0;
4814}
4815
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004816/* This function is an Lua binding that send pending data
4817 * to the client, and close the stream interface.
4818 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004819__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004820{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004821 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01004822 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004823
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004824 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004825 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004826
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004827 ic = &htxn->s->req;
4828 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01004829
Willy Tarreau630ef452015-08-28 10:06:15 +02004830 if (htxn->s->txn) {
4831 /* HTTP mode, let's stay in sync with the stream */
4832 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
4833 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
4834 htxn->s->txn->req.sov = 0;
4835 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
4836 oc->analysers = AN_RES_HTTP_XFER_BODY;
4837 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
4838 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
4839
Willy Tarreau630ef452015-08-28 10:06:15 +02004840 /* Note that if we want to support keep-alive, we need
4841 * to bypass the close/shutr_now calls below, but that
4842 * may only be done if the HTTP request was already
4843 * processed and the connection header is known (ie
4844 * not during TCP rules).
4845 */
4846 }
4847
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004848 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01004849 channel_abort(ic);
4850 channel_auto_close(ic);
4851 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004852
4853 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01004854 channel_auto_read(oc);
4855 channel_auto_close(oc);
4856 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004857
Willy Tarreau0458b082015-08-28 09:40:04 +02004858 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004859
4860 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004861 return 0;
4862}
4863
4864__LJMP static int hlua_log(lua_State *L)
4865{
4866 int level;
4867 const char *msg;
4868
4869 MAY_LJMP(check_args(L, 2, "log"));
4870 level = MAY_LJMP(luaL_checkinteger(L, 1));
4871 msg = MAY_LJMP(luaL_checkstring(L, 2));
4872
4873 if (level < 0 || level >= NB_LOG_LEVELS)
4874 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4875
4876 hlua_sendlog(NULL, level, msg);
4877 return 0;
4878}
4879
4880__LJMP static int hlua_log_debug(lua_State *L)
4881{
4882 const char *msg;
4883
4884 MAY_LJMP(check_args(L, 1, "debug"));
4885 msg = MAY_LJMP(luaL_checkstring(L, 1));
4886 hlua_sendlog(NULL, LOG_DEBUG, msg);
4887 return 0;
4888}
4889
4890__LJMP static int hlua_log_info(lua_State *L)
4891{
4892 const char *msg;
4893
4894 MAY_LJMP(check_args(L, 1, "info"));
4895 msg = MAY_LJMP(luaL_checkstring(L, 1));
4896 hlua_sendlog(NULL, LOG_INFO, msg);
4897 return 0;
4898}
4899
4900__LJMP static int hlua_log_warning(lua_State *L)
4901{
4902 const char *msg;
4903
4904 MAY_LJMP(check_args(L, 1, "warning"));
4905 msg = MAY_LJMP(luaL_checkstring(L, 1));
4906 hlua_sendlog(NULL, LOG_WARNING, msg);
4907 return 0;
4908}
4909
4910__LJMP static int hlua_log_alert(lua_State *L)
4911{
4912 const char *msg;
4913
4914 MAY_LJMP(check_args(L, 1, "alert"));
4915 msg = MAY_LJMP(luaL_checkstring(L, 1));
4916 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004917 return 0;
4918}
4919
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004920__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004921{
4922 int wakeup_ms = lua_tointeger(L, -1);
4923 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004924 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004925 return 0;
4926}
4927
4928__LJMP static int hlua_sleep(lua_State *L)
4929{
4930 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004931 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004932
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004933 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004934
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004935 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004936 wakeup_ms = tick_add(now_ms, delay);
4937 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004938
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004939 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
4940 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004941}
4942
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004943__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004944{
4945 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004946 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004947
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004948 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004949
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004950 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004951 wakeup_ms = tick_add(now_ms, delay);
4952 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004953
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004954 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
4955 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004956}
4957
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004958/* This functionis an LUA binding. it permits to give back
4959 * the hand at the HAProxy scheduler. It is used when the
4960 * LUA processing consumes a lot of time.
4961 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004962__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004963{
4964 return 0;
4965}
4966
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004967__LJMP static int hlua_yield(lua_State *L)
4968{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004969 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
4970 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004971}
4972
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004973/* This function change the nice of the currently executed
4974 * task. It is used set low or high priority at the current
4975 * task.
4976 */
Willy Tarreau59551662015-03-10 14:23:13 +01004977__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004978{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004979 struct hlua *hlua;
4980 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004981
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004982 MAY_LJMP(check_args(L, 1, "set_nice"));
4983 hlua = hlua_gethlua(L);
4984 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004985
4986 /* If he task is not set, I'm in a start mode. */
4987 if (!hlua || !hlua->task)
4988 return 0;
4989
4990 if (nice < -1024)
4991 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004992 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004993 nice = 1024;
4994
4995 hlua->task->nice = nice;
4996 return 0;
4997}
4998
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004999/* This function is used as a calback of a task. It is called by the
5000 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5001 * return an E_AGAIN signal, the emmiter of this signal must set a
5002 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005003 *
5004 * Task wrapper are longjmp safe because the only one Lua code
5005 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005006 */
5007static struct task *hlua_process_task(struct task *task)
5008{
5009 struct hlua *hlua = task->context;
5010 enum hlua_exec status;
5011
5012 /* We need to remove the task from the wait queue before executing
5013 * the Lua code because we don't know if it needs to wait for
5014 * another timer or not in the case of E_AGAIN.
5015 */
5016 task_delete(task);
5017
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005018 /* If it is the first call to the task, we must initialize the
5019 * execution timeouts.
5020 */
5021 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005022 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005023
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005024 /* Execute the Lua code. */
5025 status = hlua_ctx_resume(hlua, 1);
5026
5027 switch (status) {
5028 /* finished or yield */
5029 case HLUA_E_OK:
5030 hlua_ctx_destroy(hlua);
5031 task_delete(task);
5032 task_free(task);
5033 break;
5034
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005035 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5036 if (hlua->wake_time != TICK_ETERNITY)
5037 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005038 break;
5039
5040 /* finished with error. */
5041 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005042 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005043 hlua_ctx_destroy(hlua);
5044 task_delete(task);
5045 task_free(task);
5046 break;
5047
5048 case HLUA_E_ERR:
5049 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005050 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005051 hlua_ctx_destroy(hlua);
5052 task_delete(task);
5053 task_free(task);
5054 break;
5055 }
5056 return NULL;
5057}
5058
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005059/* This function is an LUA binding that register LUA function to be
5060 * executed after the HAProxy configuration parsing and before the
5061 * HAProxy scheduler starts. This function expect only one LUA
5062 * argument that is a function. This function returns nothing, but
5063 * throws if an error is encountered.
5064 */
5065__LJMP static int hlua_register_init(lua_State *L)
5066{
5067 struct hlua_init_function *init;
5068 int ref;
5069
5070 MAY_LJMP(check_args(L, 1, "register_init"));
5071
5072 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5073
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005074 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005075 if (!init)
5076 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5077
5078 init->function_ref = ref;
5079 LIST_ADDQ(&hlua_init_functions, &init->l);
5080 return 0;
5081}
5082
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005083/* This functio is an LUA binding. It permits to register a task
5084 * executed in parallel of the main HAroxy activity. The task is
5085 * created and it is set in the HAProxy scheduler. It can be called
5086 * from the "init" section, "post init" or during the runtime.
5087 *
5088 * Lua prototype:
5089 *
5090 * <none> core.register_task(<function>)
5091 */
5092static int hlua_register_task(lua_State *L)
5093{
5094 struct hlua *hlua;
5095 struct task *task;
5096 int ref;
5097
5098 MAY_LJMP(check_args(L, 1, "register_task"));
5099
5100 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5101
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005102 hlua = calloc(1, sizeof(*hlua));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005103 if (!hlua)
5104 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5105
5106 task = task_new();
5107 task->context = hlua;
5108 task->process = hlua_process_task;
5109
5110 if (!hlua_ctx_init(hlua, task))
5111 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5112
5113 /* Restore the function in the stack. */
5114 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5115 hlua->nargs = 0;
5116
5117 /* Schedule task. */
5118 task_schedule(task, now_ms);
5119
5120 return 0;
5121}
5122
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005123/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5124 * doesn't allow "yield" functions because the HAProxy engine cannot
5125 * resume converters.
5126 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005127static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005128{
5129 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005130 struct stream *stream = smp->strm;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005131
Willy Tarreau87b09662015-04-03 00:22:06 +02005132 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005133 * Lua context can be not initialized. This behavior
5134 * permits to save performances because a systematic
5135 * Lua initialization cause 5% performances loss.
5136 */
Willy Tarreau87b09662015-04-03 00:22:06 +02005137 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005138 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005139 return 0;
5140 }
5141
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005142 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005143 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005144
5145 /* The following Lua calls can fail. */
5146 if (!SET_SAFE_LJMP(stream->hlua.T)) {
5147 SEND_ERR(stream->be, "Lua converter '%s': critical error.\n", fcn->name);
5148 return 0;
5149 }
5150
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005151 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005152 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005153 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005154 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005155 return 0;
5156 }
5157
5158 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005159 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005160
5161 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005162 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005163 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005164 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005165 return 0;
5166 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005167 hlua_smp2lua(stream->hlua.T, smp);
5168 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005169
5170 /* push keywords in the stack. */
5171 if (arg_p) {
5172 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02005173 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005174 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005175 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005176 return 0;
5177 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005178 hlua_arg2lua(stream->hlua.T, arg_p);
5179 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005180 }
5181 }
5182
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005183 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005184 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005185
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005186 /* At this point the execution is safe. */
5187 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005188 }
5189
5190 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005191 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005192 /* finished. */
5193 case HLUA_E_OK:
5194 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005195 hlua_lua2smp(stream->hlua.T, -1, smp);
5196 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005197 return 1;
5198
5199 /* yield. */
5200 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005201 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005202 return 0;
5203
5204 /* finished with error. */
5205 case HLUA_E_ERRMSG:
5206 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005207 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
5208 fcn->name, lua_tostring(stream->hlua.T, -1));
Willy Tarreau87b09662015-04-03 00:22:06 +02005209 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005210 return 0;
5211
5212 case HLUA_E_ERR:
5213 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005214 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005215
5216 default:
5217 return 0;
5218 }
5219}
5220
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005221/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5222 * doesn't allow "yield" functions because the HAProxy engine cannot
5223 * resume sample-fetches.
5224 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005225static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5226 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005227{
5228 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005229 struct stream *stream = smp->strm;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005230
Willy Tarreau87b09662015-04-03 00:22:06 +02005231 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005232 * Lua context can be not initialized. This behavior
5233 * permits to save performances because a systematic
5234 * Lua initialization cause 5% performances loss.
5235 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005236 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005237 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005238 return 0;
5239 }
5240
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005241 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005242 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005243
5244 /* The following Lua calls can fail. */
5245 if (!SET_SAFE_LJMP(stream->hlua.T)) {
5246 SEND_ERR(smp->px, "Lua sample-fetch '%s': critical error.\n", fcn->name);
5247 return 0;
5248 }
5249
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005250 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005251 if (!lua_checkstack(stream->hlua.T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005252 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005253 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005254 return 0;
5255 }
5256
5257 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005258 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005259
5260 /* push arguments in the stack. */
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005261 if (!hlua_txn_new(stream->hlua.T, stream, smp->px, smp->opt & SMP_OPT_DIR)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005262 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005263 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005264 return 0;
5265 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005266 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005267
5268 /* push keywords in the stack. */
5269 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5270 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005271 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005272 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005273 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005274 return 0;
5275 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005276 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005277 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005278 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005279 return 0;
5280 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005281 hlua_arg2lua(stream->hlua.T, arg_p);
5282 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005283 }
5284
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005285 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005286 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005287
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005288 /* At this point the execution is safe. */
5289 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005290 }
5291
5292 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005293 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005294 /* finished. */
5295 case HLUA_E_OK:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005296 if (!hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005297 return 0;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005298 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005299 hlua_lua2smp(stream->hlua.T, -1, smp);
5300 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005301
5302 /* Set the end of execution flag. */
5303 smp->flags &= ~SMP_F_MAY_CHANGE;
5304 return 1;
5305
5306 /* yield. */
5307 case HLUA_E_AGAIN:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005308 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005309 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005310 return 0;
5311
5312 /* finished with error. */
5313 case HLUA_E_ERRMSG:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005314 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005315 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005316 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
5317 fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005318 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005319 return 0;
5320
5321 case HLUA_E_ERR:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005322 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005323 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005324 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005325
5326 default:
5327 return 0;
5328 }
5329}
5330
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005331/* This function is an LUA binding used for registering
5332 * "sample-conv" functions. It expects a converter name used
5333 * in the haproxy configuration file, and an LUA function.
5334 */
5335__LJMP static int hlua_register_converters(lua_State *L)
5336{
5337 struct sample_conv_kw_list *sck;
5338 const char *name;
5339 int ref;
5340 int len;
5341 struct hlua_function *fcn;
5342
5343 MAY_LJMP(check_args(L, 2, "register_converters"));
5344
5345 /* First argument : converter name. */
5346 name = MAY_LJMP(luaL_checkstring(L, 1));
5347
5348 /* Second argument : lua function. */
5349 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5350
5351 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005352 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005353 if (!sck)
5354 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005355 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005356 if (!fcn)
5357 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5358
5359 /* Fill fcn. */
5360 fcn->name = strdup(name);
5361 if (!fcn->name)
5362 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5363 fcn->function_ref = ref;
5364
5365 /* List head */
5366 sck->list.n = sck->list.p = NULL;
5367
5368 /* converter keyword. */
5369 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005370 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005371 if (!sck->kw[0].kw)
5372 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5373
5374 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5375 sck->kw[0].process = hlua_sample_conv_wrapper;
5376 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
5377 sck->kw[0].val_args = NULL;
5378 sck->kw[0].in_type = SMP_T_STR;
5379 sck->kw[0].out_type = SMP_T_STR;
5380 sck->kw[0].private = fcn;
5381
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005382 /* Register this new converter */
5383 sample_register_convs(sck);
5384
5385 return 0;
5386}
5387
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005388/* This fucntion is an LUA binding used for registering
5389 * "sample-fetch" functions. It expects a converter name used
5390 * in the haproxy configuration file, and an LUA function.
5391 */
5392__LJMP static int hlua_register_fetches(lua_State *L)
5393{
5394 const char *name;
5395 int ref;
5396 int len;
5397 struct sample_fetch_kw_list *sfk;
5398 struct hlua_function *fcn;
5399
5400 MAY_LJMP(check_args(L, 2, "register_fetches"));
5401
5402 /* First argument : sample-fetch name. */
5403 name = MAY_LJMP(luaL_checkstring(L, 1));
5404
5405 /* Second argument : lua function. */
5406 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5407
5408 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005409 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005410 if (!sfk)
5411 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005412 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005413 if (!fcn)
5414 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5415
5416 /* Fill fcn. */
5417 fcn->name = strdup(name);
5418 if (!fcn->name)
5419 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5420 fcn->function_ref = ref;
5421
5422 /* List head */
5423 sfk->list.n = sfk->list.p = NULL;
5424
5425 /* sample-fetch keyword. */
5426 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005427 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005428 if (!sfk->kw[0].kw)
5429 return luaL_error(L, "lua out of memory error.");
5430
5431 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5432 sfk->kw[0].process = hlua_sample_fetch_wrapper;
5433 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
5434 sfk->kw[0].val_args = NULL;
5435 sfk->kw[0].out_type = SMP_T_STR;
5436 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5437 sfk->kw[0].val = 0;
5438 sfk->kw[0].private = fcn;
5439
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005440 /* Register this new fetch. */
5441 sample_register_fetches(sfk);
5442
5443 return 0;
5444}
5445
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005446/* This function is a wrapper to execute each LUA function declared
5447 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005448 * return ACT_RET_CONT if the processing is finished (with or without
5449 * error) and return ACT_RET_YIELD if the function must be called again
5450 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005451 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005452static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005453 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005454{
5455 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005456 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005457 int dir;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005458
5459 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01005460 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
5461 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
5462 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
5463 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005464 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005465 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005466 return ACT_RET_CONT;
5467 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005468
Willy Tarreau87b09662015-04-03 00:22:06 +02005469 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005470 * Lua context can be not initialized. This behavior
5471 * permits to save performances because a systematic
5472 * Lua initialization cause 5% performances loss.
5473 */
5474 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005475 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005476 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005477 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005478 }
5479
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005480 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01005481 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005482
5483 /* The following Lua calls can fail. */
5484 if (!SET_SAFE_LJMP(s->hlua.T)) {
5485 SEND_ERR(px, "Lua function '%s': critical error.\n",
5486 rule->arg.hlua_rule->fcn.name);
5487 return ACT_RET_CONT;
5488 }
5489
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005490 /* Check stack available size. */
5491 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005492 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005493 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005494 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005495 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005496 }
5497
5498 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005499 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005500
Willy Tarreau87b09662015-04-03 00:22:06 +02005501 /* Create and and push object stream in the stack. */
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005502 if (!hlua_txn_new(s->hlua.T, s, px, dir)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005503 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005504 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005505 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005506 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005507 }
5508 s->hlua.nargs = 1;
5509
5510 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005511 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005512 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005513 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005514 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005515 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005516 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005517 }
5518 lua_pushstring(s->hlua.T, *arg);
5519 s->hlua.nargs++;
5520 }
5521
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005522 /* Now the execution is safe. */
5523 RESET_SAFE_LJMP(s->hlua.T);
5524
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005525 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005526 s->hlua.max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005527 }
5528
5529 /* Execute the function. */
Willy Tarreau528192d2015-09-27 10:48:01 +02005530 switch (hlua_ctx_resume(&s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005531 /* finished. */
5532 case HLUA_E_OK:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005533 if (!hlua_check_proto(s, dir))
5534 return ACT_RET_ERR;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005535 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005536
5537 /* yield. */
5538 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005539 /* Set timeout in the required channel. */
5540 if (s->hlua.wake_time != TICK_ETERNITY) {
5541 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005542 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005543 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005544 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005545 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005546 /* Some actions can be wake up when a "write" event
5547 * is detected on a response channel. This is useful
5548 * only for actions targetted on the requests.
5549 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01005550 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005551 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005552 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005553 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005554 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01005555 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005556 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005557 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005558
5559 /* finished with error. */
5560 case HLUA_E_ERRMSG:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005561 if (!hlua_check_proto(s, dir))
5562 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005563 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005564 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005565 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005566 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005567 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005568
5569 case HLUA_E_ERR:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005570 if (!hlua_check_proto(s, dir))
5571 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005572 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005573 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005574 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005575
5576 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005577 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005578 }
5579}
5580
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005581struct task *hlua_applet_wakeup(struct task *t)
5582{
5583 struct appctx *ctx = t->context;
5584 struct stream_interface *si = ctx->owner;
5585
5586 /* If the applet is wake up without any expected work, the sheduler
5587 * remove it from the run queue. This flag indicate that the applet
5588 * is waiting for write. If the buffer is full, the main processing
5589 * will send some data and after call the applet, otherwise it call
5590 * the applet ASAP.
5591 */
5592 si_applet_cant_put(si);
5593 appctx_wakeup(ctx);
5594 return NULL;
5595}
5596
5597static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5598{
5599 struct stream_interface *si = ctx->owner;
5600 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5601 struct task *task;
5602 char **arg;
5603
5604 HLUA_INIT(hlua);
5605 ctx->ctx.hlua_apptcp.flags = 0;
5606
5607 /* Create task used by signal to wakeup applets. */
5608 task = task_new();
5609 if (!task) {
5610 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5611 ctx->rule->arg.hlua_rule->fcn.name);
5612 return 0;
5613 }
5614 task->nice = 0;
5615 task->context = ctx;
5616 task->process = hlua_applet_wakeup;
5617 ctx->ctx.hlua_apptcp.task = task;
5618
5619 /* In the execution wrappers linked with a stream, the
5620 * Lua context can be not initialized. This behavior
5621 * permits to save performances because a systematic
5622 * Lua initialization cause 5% performances loss.
5623 */
5624 if (!hlua_ctx_init(hlua, task)) {
5625 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
5626 ctx->rule->arg.hlua_rule->fcn.name);
5627 return 0;
5628 }
5629
5630 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005631 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005632
5633 /* The following Lua calls can fail. */
5634 if (!SET_SAFE_LJMP(hlua->T)) {
5635 SEND_ERR(px, "Lua applet tcp '%s': critical error.\n",
5636 ctx->rule->arg.hlua_rule->fcn.name);
5637 RESET_SAFE_LJMP(hlua->T);
5638 return 0;
5639 }
5640
5641 /* Check stack available size. */
5642 if (!lua_checkstack(hlua->T, 1)) {
5643 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5644 ctx->rule->arg.hlua_rule->fcn.name);
5645 RESET_SAFE_LJMP(hlua->T);
5646 return 0;
5647 }
5648
5649 /* Restore the function in the stack. */
5650 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5651
5652 /* Create and and push object stream in the stack. */
5653 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
5654 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5655 ctx->rule->arg.hlua_rule->fcn.name);
5656 RESET_SAFE_LJMP(hlua->T);
5657 return 0;
5658 }
5659 hlua->nargs = 1;
5660
5661 /* push keywords in the stack. */
5662 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5663 if (!lua_checkstack(hlua->T, 1)) {
5664 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5665 ctx->rule->arg.hlua_rule->fcn.name);
5666 RESET_SAFE_LJMP(hlua->T);
5667 return 0;
5668 }
5669 lua_pushstring(hlua->T, *arg);
5670 hlua->nargs++;
5671 }
5672
5673 RESET_SAFE_LJMP(hlua->T);
5674
5675 /* Wakeup the applet ASAP. */
5676 si_applet_cant_get(si);
5677 si_applet_cant_put(si);
5678
5679 return 1;
5680}
5681
5682static void hlua_applet_tcp_fct(struct appctx *ctx)
5683{
5684 struct stream_interface *si = ctx->owner;
5685 struct stream *strm = si_strm(si);
5686 struct channel *res = si_ic(si);
5687 struct act_rule *rule = ctx->rule;
5688 struct proxy *px = strm->be;
5689 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5690
5691 /* The applet execution is already done. */
5692 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
5693 return;
5694
5695 /* If the stream is disconnect or closed, ldo nothing. */
5696 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5697 return;
5698
5699 /* Execute the function. */
5700 switch (hlua_ctx_resume(hlua, 1)) {
5701 /* finished. */
5702 case HLUA_E_OK:
5703 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5704
5705 /* log time */
5706 strm->logs.tv_request = now;
5707
5708 /* eat the whole request */
5709 bo_skip(si_oc(si), si_ob(si)->o);
5710 res->flags |= CF_READ_NULL;
5711 si_shutr(si);
5712 return;
5713
5714 /* yield. */
5715 case HLUA_E_AGAIN:
5716 return;
5717
5718 /* finished with error. */
5719 case HLUA_E_ERRMSG:
5720 /* Display log. */
5721 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
5722 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
5723 lua_pop(hlua->T, 1);
5724 goto error;
5725
5726 case HLUA_E_ERR:
5727 /* Display log. */
5728 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
5729 rule->arg.hlua_rule->fcn.name);
5730 goto error;
5731
5732 default:
5733 goto error;
5734 }
5735
5736error:
5737
5738 /* For all other cases, just close the stream. */
5739 si_shutw(si);
5740 si_shutr(si);
5741 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5742}
5743
5744static void hlua_applet_tcp_release(struct appctx *ctx)
5745{
5746 task_free(ctx->ctx.hlua_apptcp.task);
5747 ctx->ctx.hlua_apptcp.task = NULL;
5748 hlua_ctx_destroy(&ctx->ctx.hlua_apptcp.hlua);
5749}
5750
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005751/* The function returns 1 if the initialisation is complete, 0 if
5752 * an errors occurs and -1 if more data are required for initializing
5753 * the applet.
5754 */
5755static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5756{
5757 struct stream_interface *si = ctx->owner;
5758 struct channel *req = si_oc(si);
5759 struct http_msg *msg;
5760 struct http_txn *txn;
5761 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5762 char **arg;
5763 struct hdr_ctx hdr;
5764 struct task *task;
5765 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
5766
5767 /* Wait for a full HTTP request. */
5768 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
5769 if (smp.flags & SMP_F_MAY_CHANGE)
5770 return -1;
5771 return 0;
5772 }
5773 txn = strm->txn;
5774 msg = &txn->req;
5775
Willy Tarreau0078bfc2015-10-07 20:20:28 +02005776 /* We want two things in HTTP mode :
5777 * - enforce server-close mode if we were in keep-alive, so that the
5778 * applet is released after each response ;
5779 * - enable request body transfer to the applet in order to resync
5780 * with the response body.
5781 */
5782 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
5783 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02005784
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005785 HLUA_INIT(hlua);
5786 ctx->ctx.hlua_apphttp.left_bytes = -1;
5787 ctx->ctx.hlua_apphttp.flags = 0;
5788
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01005789 if (txn->req.flags & HTTP_MSGF_VER_11)
5790 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
5791
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005792 /* Create task used by signal to wakeup applets. */
5793 task = task_new();
5794 if (!task) {
5795 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
5796 ctx->rule->arg.hlua_rule->fcn.name);
5797 return 0;
5798 }
5799 task->nice = 0;
5800 task->context = ctx;
5801 task->process = hlua_applet_wakeup;
5802 ctx->ctx.hlua_apphttp.task = task;
5803
5804 /* In the execution wrappers linked with a stream, the
5805 * Lua context can be not initialized. This behavior
5806 * permits to save performances because a systematic
5807 * Lua initialization cause 5% performances loss.
5808 */
5809 if (!hlua_ctx_init(hlua, task)) {
5810 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
5811 ctx->rule->arg.hlua_rule->fcn.name);
5812 return 0;
5813 }
5814
5815 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005816 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005817
5818 /* The following Lua calls can fail. */
5819 if (!SET_SAFE_LJMP(hlua->T)) {
5820 SEND_ERR(px, "Lua applet http '%s': critical error.\n",
5821 ctx->rule->arg.hlua_rule->fcn.name);
5822 return 0;
5823 }
5824
5825 /* Check stack available size. */
5826 if (!lua_checkstack(hlua->T, 1)) {
5827 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5828 ctx->rule->arg.hlua_rule->fcn.name);
5829 RESET_SAFE_LJMP(hlua->T);
5830 return 0;
5831 }
5832
5833 /* Restore the function in the stack. */
5834 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5835
5836 /* Create and and push object stream in the stack. */
5837 if (!hlua_applet_http_new(hlua->T, ctx)) {
5838 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5839 ctx->rule->arg.hlua_rule->fcn.name);
5840 RESET_SAFE_LJMP(hlua->T);
5841 return 0;
5842 }
5843 hlua->nargs = 1;
5844
5845 /* Look for a 100-continue expected. */
5846 if (msg->flags & HTTP_MSGF_VER_11) {
5847 hdr.idx = 0;
5848 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
5849 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
5850 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
5851 }
5852
5853 /* push keywords in the stack. */
5854 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5855 if (!lua_checkstack(hlua->T, 1)) {
5856 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5857 ctx->rule->arg.hlua_rule->fcn.name);
5858 RESET_SAFE_LJMP(hlua->T);
5859 return 0;
5860 }
5861 lua_pushstring(hlua->T, *arg);
5862 hlua->nargs++;
5863 }
5864
5865 RESET_SAFE_LJMP(hlua->T);
5866
5867 /* Wakeup the applet when data is ready for read. */
5868 si_applet_cant_get(si);
5869
5870 return 1;
5871}
5872
5873static void hlua_applet_http_fct(struct appctx *ctx)
5874{
5875 struct stream_interface *si = ctx->owner;
5876 struct stream *strm = si_strm(si);
5877 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005878 struct act_rule *rule = ctx->rule;
5879 struct proxy *px = strm->be;
5880 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5881 char *blk1;
5882 int len1;
5883 char *blk2;
5884 int len2;
5885 int ret;
5886
5887 /* If the stream is disconnect or closed, ldo nothing. */
5888 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5889 return;
5890
5891 /* Set the currently running flag. */
5892 if (!HLUA_IS_RUNNING(hlua) &&
5893 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
5894
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005895 /* Wait for full HTTP analysys. */
5896 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
5897 si_applet_cant_get(si);
5898 return;
5899 }
5900
5901 /* Store the max amount of bytes that we can read. */
5902 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
5903
5904 /* We need to flush the request header. This left the body
5905 * for the Lua.
5906 */
5907
5908 /* Read the maximum amount of data avalaible. */
5909 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
5910 if (ret == -1)
5911 return;
5912
5913 /* No data available, ask for more data. */
5914 if (ret == 1)
5915 len2 = 0;
5916 if (ret == 0)
5917 len1 = 0;
5918 if (len1 + len2 < strm->txn->req.eoh + 2) {
5919 si_applet_cant_get(si);
5920 return;
5921 }
5922
5923 /* skip the requests bytes. */
5924 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
5925 }
5926
5927 /* Executes The applet if it is not done. */
5928 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
5929
5930 /* Execute the function. */
5931 switch (hlua_ctx_resume(hlua, 1)) {
5932 /* finished. */
5933 case HLUA_E_OK:
5934 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
5935 break;
5936
5937 /* yield. */
5938 case HLUA_E_AGAIN:
5939 return;
5940
5941 /* finished with error. */
5942 case HLUA_E_ERRMSG:
5943 /* Display log. */
5944 SEND_ERR(px, "Lua applet http '%s': %s.\n",
5945 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
5946 lua_pop(hlua->T, 1);
5947 goto error;
5948
5949 case HLUA_E_ERR:
5950 /* Display log. */
5951 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
5952 rule->arg.hlua_rule->fcn.name);
5953 goto error;
5954
5955 default:
5956 goto error;
5957 }
5958 }
5959
5960 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
5961
5962 /* We must send the final chunk. */
5963 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
5964 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
5965
5966 /* sent last chunk at once. */
5967 ret = bi_putblk(res, "0\r\n\r\n", 5);
5968
5969 /* critical error. */
5970 if (ret == -2 || ret == -3) {
5971 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
5972 rule->arg.hlua_rule->fcn.name);
5973 goto error;
5974 }
5975
5976 /* no enough space error. */
5977 if (ret == -1) {
5978 si_applet_cant_put(si);
5979 return;
5980 }
5981
5982 /* set the last chunk sent. */
5983 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
5984 }
5985
5986 /* close the connection. */
5987
5988 /* status / log */
5989 strm->txn->status = ctx->ctx.hlua_apphttp.status;
5990 strm->logs.tv_request = now;
5991
5992 /* eat the whole request */
5993 bo_skip(si_oc(si), si_ob(si)->o);
5994 res->flags |= CF_READ_NULL;
5995 si_shutr(si);
5996
5997 return;
5998 }
5999
6000error:
6001
6002 /* If we are in HTTP mode, and we are not send any
6003 * data, return a 500 server error in best effort:
6004 * if there are no room avalaible in the buffer,
6005 * just close the connection.
6006 */
6007 bi_putblk(res, error_500, strlen(error_500));
6008 if (!(strm->flags & SF_ERR_MASK))
6009 strm->flags |= SF_ERR_RESOURCE;
6010 si_shutw(si);
6011 si_shutr(si);
6012 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6013}
6014
6015static void hlua_applet_http_release(struct appctx *ctx)
6016{
6017 task_free(ctx->ctx.hlua_apphttp.task);
6018 ctx->ctx.hlua_apphttp.task = NULL;
6019 hlua_ctx_destroy(&ctx->ctx.hlua_apphttp.hlua);
6020}
6021
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006022/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6023 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006024 *
6025 * This function can fail with an abort() due to an Lua critical error.
6026 * We are in the configuration parsing process of HAProxy, this abort() is
6027 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006028 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006029static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6030 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006031{
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006032 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6033
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006034 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006035 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006036 if (!rule->arg.hlua_rule) {
6037 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006038 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006039 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006040
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006041 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006042 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006043
6044 /* TODO: later accept arguments. */
6045 rule->arg.hlua_rule->args = NULL;
6046
Thierry FOURNIER42148732015-09-02 17:17:33 +02006047 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006048 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006049 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006050}
6051
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006052static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6053 struct act_rule *rule, char **err)
6054{
6055 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6056
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006057 /* HTTP applets are forbidden in tcp-request rules.
6058 * HTTP applet request requires everything initilized by
6059 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6060 * The applet will be immediately initilized, but its before
6061 * the call of this analyzer.
6062 */
6063 if (rule->from != ACT_F_HTTP_REQ) {
6064 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6065 return ACT_RET_PRS_ERR;
6066 }
6067
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006068 /* Memory for the rule. */
6069 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6070 if (!rule->arg.hlua_rule) {
6071 memprintf(err, "out of memory error");
6072 return ACT_RET_PRS_ERR;
6073 }
6074
6075 /* Reference the Lua function and store the reference. */
6076 rule->arg.hlua_rule->fcn = *fcn;
6077
6078 /* TODO: later accept arguments. */
6079 rule->arg.hlua_rule->args = NULL;
6080
6081 /* Add applet pointer in the rule. */
6082 rule->applet.obj_type = OBJ_TYPE_APPLET;
6083 rule->applet.name = fcn->name;
6084 rule->applet.init = hlua_applet_http_init;
6085 rule->applet.fct = hlua_applet_http_fct;
6086 rule->applet.release = hlua_applet_http_release;
6087 rule->applet.timeout = hlua_timeout_applet;
6088
6089 return ACT_RET_PRS_OK;
6090}
6091
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006092/* This function is an LUA binding used for registering
6093 * "sample-conv" functions. It expects a converter name used
6094 * in the haproxy configuration file, and an LUA function.
6095 */
6096__LJMP static int hlua_register_action(lua_State *L)
6097{
6098 struct action_kw_list *akl;
6099 const char *name;
6100 int ref;
6101 int len;
6102 struct hlua_function *fcn;
6103
Thierry FOURNIERed0bdaa2015-12-20 19:51:06 +01006104 MAY_LJMP(check_args(L, 3, "register_action"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006105
6106 /* First argument : converter name. */
6107 name = MAY_LJMP(luaL_checkstring(L, 1));
6108
6109 /* Second argument : environment. */
6110 if (lua_type(L, 2) != LUA_TTABLE)
6111 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6112
6113 /* Third argument : lua function. */
6114 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6115
6116 /* browse the second argulent as an array. */
6117 lua_pushnil(L);
6118 while (lua_next(L, 2) != 0) {
6119 if (lua_type(L, -1) != LUA_TSTRING)
6120 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6121
6122 /* Check required environment. Only accepted "http" or "tcp". */
6123 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006124 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006125 if (!akl)
6126 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006127 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006128 if (!fcn)
6129 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6130
6131 /* Fill fcn. */
6132 fcn->name = strdup(name);
6133 if (!fcn->name)
6134 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6135 fcn->function_ref = ref;
6136
6137 /* List head */
6138 akl->list.n = akl->list.p = NULL;
6139
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006140 /* action keyword. */
6141 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006142 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006143 if (!akl->kw[0].kw)
6144 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6145
6146 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6147
6148 akl->kw[0].match_pfx = 0;
6149 akl->kw[0].private = fcn;
6150 akl->kw[0].parse = action_register_lua;
6151
6152 /* select the action registering point. */
6153 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6154 tcp_req_cont_keywords_register(akl);
6155 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6156 tcp_res_cont_keywords_register(akl);
6157 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6158 http_req_keywords_register(akl);
6159 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6160 http_res_keywords_register(akl);
6161 else
6162 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6163 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6164 "are expected.", lua_tostring(L, -1)));
6165
6166 /* pop the environment string. */
6167 lua_pop(L, 1);
6168 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006169 return ACT_RET_PRS_OK;
6170}
6171
6172static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6173 struct act_rule *rule, char **err)
6174{
6175 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6176
6177 /* Memory for the rule. */
6178 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6179 if (!rule->arg.hlua_rule) {
6180 memprintf(err, "out of memory error");
6181 return ACT_RET_PRS_ERR;
6182 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006183
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006184 /* Reference the Lua function and store the reference. */
6185 rule->arg.hlua_rule->fcn = *fcn;
6186
6187 /* TODO: later accept arguments. */
6188 rule->arg.hlua_rule->args = NULL;
6189
6190 /* Add applet pointer in the rule. */
6191 rule->applet.obj_type = OBJ_TYPE_APPLET;
6192 rule->applet.name = fcn->name;
6193 rule->applet.init = hlua_applet_tcp_init;
6194 rule->applet.fct = hlua_applet_tcp_fct;
6195 rule->applet.release = hlua_applet_tcp_release;
6196 rule->applet.timeout = hlua_timeout_applet;
6197
6198 return 0;
6199}
6200
6201/* This function is an LUA binding used for registering
6202 * "sample-conv" functions. It expects a converter name used
6203 * in the haproxy configuration file, and an LUA function.
6204 */
6205__LJMP static int hlua_register_service(lua_State *L)
6206{
6207 struct action_kw_list *akl;
6208 const char *name;
6209 const char *env;
6210 int ref;
6211 int len;
6212 struct hlua_function *fcn;
6213
6214 MAY_LJMP(check_args(L, 3, "register_service"));
6215
6216 /* First argument : converter name. */
6217 name = MAY_LJMP(luaL_checkstring(L, 1));
6218
6219 /* Second argument : environment. */
6220 env = MAY_LJMP(luaL_checkstring(L, 2));
6221
6222 /* Third argument : lua function. */
6223 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6224
6225 /* Check required environment. Only accepted "http" or "tcp". */
6226 /* Allocate and fill the sample fetch keyword struct. */
6227 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6228 if (!akl)
6229 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6230 fcn = calloc(1, sizeof(*fcn));
6231 if (!fcn)
6232 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6233
6234 /* Fill fcn. */
6235 len = strlen("<lua.>") + strlen(name) + 1;
6236 fcn->name = calloc(1, len);
6237 if (!fcn->name)
6238 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6239 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6240 fcn->function_ref = ref;
6241
6242 /* List head */
6243 akl->list.n = akl->list.p = NULL;
6244
6245 /* converter keyword. */
6246 len = strlen("lua.") + strlen(name) + 1;
6247 akl->kw[0].kw = calloc(1, len);
6248 if (!akl->kw[0].kw)
6249 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6250
6251 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6252
6253 if (strcmp(env, "tcp") == 0)
6254 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006255 else if (strcmp(env, "http") == 0)
6256 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006257 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006258 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6259 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006260
6261 akl->kw[0].match_pfx = 0;
6262 akl->kw[0].private = fcn;
6263
6264 /* End of array. */
6265 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6266
6267 /* Register this new converter */
6268 service_keywords_register(akl);
6269
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006270 return 0;
6271}
6272
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006273static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
6274 struct proxy *defpx, const char *file, int line,
6275 char **err, unsigned int *timeout)
6276{
6277 const char *error;
6278
6279 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
6280 if (error && *error != '\0') {
6281 memprintf(err, "%s: invalid timeout", args[0]);
6282 return -1;
6283 }
6284 return 0;
6285}
6286
6287static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
6288 struct proxy *defpx, const char *file, int line,
6289 char **err)
6290{
6291 return hlua_read_timeout(args, section_type, curpx, defpx,
6292 file, line, err, &hlua_timeout_session);
6293}
6294
6295static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
6296 struct proxy *defpx, const char *file, int line,
6297 char **err)
6298{
6299 return hlua_read_timeout(args, section_type, curpx, defpx,
6300 file, line, err, &hlua_timeout_task);
6301}
6302
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006303static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
6304 struct proxy *defpx, const char *file, int line,
6305 char **err)
6306{
6307 return hlua_read_timeout(args, section_type, curpx, defpx,
6308 file, line, err, &hlua_timeout_applet);
6309}
6310
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006311static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
6312 struct proxy *defpx, const char *file, int line,
6313 char **err)
6314{
6315 char *error;
6316
6317 hlua_nb_instruction = strtoll(args[1], &error, 10);
6318 if (*error != '\0') {
6319 memprintf(err, "%s: invalid number", args[0]);
6320 return -1;
6321 }
6322 return 0;
6323}
6324
Willy Tarreau32f61e22015-03-18 17:54:59 +01006325static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
6326 struct proxy *defpx, const char *file, int line,
6327 char **err)
6328{
6329 char *error;
6330
6331 if (*(args[1]) == 0) {
6332 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
6333 return -1;
6334 }
6335 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
6336 if (*error != '\0') {
6337 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
6338 return -1;
6339 }
6340 return 0;
6341}
6342
6343
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006344/* This function is called by the main configuration key "lua-load". It loads and
6345 * execute an lua file during the parsing of the HAProxy configuration file. It is
6346 * the main lua entry point.
6347 *
6348 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
6349 * occured, otherwise it returns 0.
6350 *
6351 * In some error case, LUA set an error message in top of the stack. This function
6352 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006353 *
6354 * This function can fail with an abort() due to an Lua critical error.
6355 * We are in the configuration parsing process of HAProxy, this abort() is
6356 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006357 */
6358static int hlua_load(char **args, int section_type, struct proxy *curpx,
6359 struct proxy *defpx, const char *file, int line,
6360 char **err)
6361{
6362 int error;
6363
6364 /* Just load and compile the file. */
6365 error = luaL_loadfile(gL.T, args[1]);
6366 if (error) {
6367 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
6368 lua_pop(gL.T, 1);
6369 return -1;
6370 }
6371
6372 /* If no syntax error where detected, execute the code. */
6373 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
6374 switch (error) {
6375 case LUA_OK:
6376 break;
6377 case LUA_ERRRUN:
6378 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
6379 lua_pop(gL.T, 1);
6380 return -1;
6381 case LUA_ERRMEM:
6382 memprintf(err, "lua out of memory error\n");
6383 return -1;
6384 case LUA_ERRERR:
6385 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
6386 lua_pop(gL.T, 1);
6387 return -1;
6388 case LUA_ERRGCMM:
6389 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
6390 lua_pop(gL.T, 1);
6391 return -1;
6392 default:
6393 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
6394 lua_pop(gL.T, 1);
6395 return -1;
6396 }
6397
6398 return 0;
6399}
6400
6401/* configuration keywords declaration */
6402static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006403 { CFG_GLOBAL, "lua-load", hlua_load },
6404 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
6405 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02006406 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006407 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01006408 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006409 { 0, NULL, NULL },
6410}};
6411
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006412/* This function can fail with an abort() due to an Lua critical error.
6413 * We are in the initialisation process of HAProxy, this abort() is
6414 * tolerated.
6415 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006416int hlua_post_init()
6417{
6418 struct hlua_init_function *init;
6419 const char *msg;
6420 enum hlua_exec ret;
6421
6422 list_for_each_entry(init, &hlua_init_functions, l) {
6423 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
6424 ret = hlua_ctx_resume(&gL, 0);
6425 switch (ret) {
6426 case HLUA_E_OK:
6427 lua_pop(gL.T, -1);
6428 return 1;
6429 case HLUA_E_AGAIN:
6430 Alert("lua init: yield not allowed.\n");
6431 return 0;
6432 case HLUA_E_ERRMSG:
6433 msg = lua_tostring(gL.T, -1);
6434 Alert("lua init: %s.\n", msg);
6435 return 0;
6436 case HLUA_E_ERR:
6437 default:
6438 Alert("lua init: unknown runtime error.\n");
6439 return 0;
6440 }
6441 }
6442 return 1;
6443}
6444
Willy Tarreau32f61e22015-03-18 17:54:59 +01006445/* The memory allocator used by the Lua stack. <ud> is a pointer to the
6446 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
6447 * is the previously allocated size or the kind of object in case of a new
6448 * allocation. <nsize> is the requested new size.
6449 */
6450static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
6451{
6452 struct hlua_mem_allocator *zone = ud;
6453
6454 if (nsize == 0) {
6455 /* it's a free */
6456 if (ptr)
6457 zone->allocated -= osize;
6458 free(ptr);
6459 return NULL;
6460 }
6461
6462 if (!ptr) {
6463 /* it's a new allocation */
6464 if (zone->limit && zone->allocated + nsize > zone->limit)
6465 return NULL;
6466
6467 ptr = malloc(nsize);
6468 if (ptr)
6469 zone->allocated += nsize;
6470 return ptr;
6471 }
6472
6473 /* it's a realloc */
6474 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
6475 return NULL;
6476
6477 ptr = realloc(ptr, nsize);
6478 if (ptr)
6479 zone->allocated += nsize - osize;
6480 return ptr;
6481}
6482
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006483/* Ithis function can fail with an abort() due to an Lua critical error.
6484 * We are in the initialisation process of HAProxy, this abort() is
6485 * tolerated.
6486 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01006487void hlua_init(void)
6488{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006489 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006490 int idx;
6491 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006492 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006493 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006494#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006495 struct srv_kw *kw;
6496 int tmp_error;
6497 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01006498 char *args[] = { /* SSL client configuration. */
6499 "ssl",
6500 "verify",
6501 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01006502 NULL
6503 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006504#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006505
Willy Tarreau87b09662015-04-03 00:22:06 +02006506 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006507 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
6508
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006509 /* Register configuration keywords. */
6510 cfg_register_keywords(&cfg_kws);
6511
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006512 /* Init main lua stack. */
6513 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01006514 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006515 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006516 gL.T = luaL_newstate();
6517 hlua_sethlua(&gL);
6518 gL.Tref = LUA_REFNIL;
6519 gL.task = NULL;
6520
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006521 /* From this point, until the end of the initialisation fucntion,
6522 * the Lua function can fail with an abort. We are in the initialisation
6523 * process of HAProxy, this abort() is tolerated.
6524 */
6525
Willy Tarreau32f61e22015-03-18 17:54:59 +01006526 /* change the memory allocators to track memory usage */
6527 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
6528
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006529 /* Initialise lua. */
6530 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006531
6532 /*
6533 *
6534 * Create "core" object.
6535 *
6536 */
6537
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01006538 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006539 lua_newtable(gL.T);
6540
6541 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006542 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006543 hlua_class_const_int(gL.T, log_levels[i], i);
6544
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006545 /* Register special functions. */
6546 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006547 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006548 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006549 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006550 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006551 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006552 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01006553 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006554 hlua_class_function(gL.T, "sleep", hlua_sleep);
6555 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01006556 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
6557 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
6558 hlua_class_function(gL.T, "set_map", hlua_set_map);
6559 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006560 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006561 hlua_class_function(gL.T, "log", hlua_log);
6562 hlua_class_function(gL.T, "Debug", hlua_log_debug);
6563 hlua_class_function(gL.T, "Info", hlua_log_info);
6564 hlua_class_function(gL.T, "Warning", hlua_log_warning);
6565 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02006566 hlua_class_function(gL.T, "done", hlua_done);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006567
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006568 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006569
6570 /*
6571 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006572 * Register class Map
6573 *
6574 */
6575
6576 /* This table entry is the object "Map" base. */
6577 lua_newtable(gL.T);
6578
6579 /* register pattern types. */
6580 for (i=0; i<PAT_MATCH_NUM; i++)
6581 hlua_class_const_int(gL.T, pat_match_names[i], i);
6582
6583 /* register constructor. */
6584 hlua_class_function(gL.T, "new", hlua_map_new);
6585
6586 /* Create and fill the metatable. */
6587 lua_newtable(gL.T);
6588
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006589 /* Create the __tostring identifier */
6590 lua_pushstring(gL.T, "__tostring");
6591 lua_pushstring(gL.T, CLASS_MAP);
6592 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6593 lua_rawset(gL.T, -3);
6594
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006595 /* Create and fille the __index entry. */
6596 lua_pushstring(gL.T, "__index");
6597 lua_newtable(gL.T);
6598
6599 /* Register . */
6600 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
6601 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
6602
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006603 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006604
6605 /* Register previous table in the registry with reference and named entry. */
6606 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6607 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6608 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
6609 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6610
6611 /* Assign the metatable to the mai Map object. */
6612 lua_setmetatable(gL.T, -2);
6613
6614 /* Set a name to the table. */
6615 lua_setglobal(gL.T, "Map");
6616
6617 /*
6618 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006619 * Register class Channel
6620 *
6621 */
6622
6623 /* Create and fill the metatable. */
6624 lua_newtable(gL.T);
6625
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006626 /* Create the __tostring identifier */
6627 lua_pushstring(gL.T, "__tostring");
6628 lua_pushstring(gL.T, CLASS_CHANNEL);
6629 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6630 lua_rawset(gL.T, -3);
6631
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006632 /* Create and fille the __index entry. */
6633 lua_pushstring(gL.T, "__index");
6634 lua_newtable(gL.T);
6635
6636 /* Register . */
6637 hlua_class_function(gL.T, "get", hlua_channel_get);
6638 hlua_class_function(gL.T, "dup", hlua_channel_dup);
6639 hlua_class_function(gL.T, "getline", hlua_channel_getline);
6640 hlua_class_function(gL.T, "set", hlua_channel_set);
6641 hlua_class_function(gL.T, "append", hlua_channel_append);
6642 hlua_class_function(gL.T, "send", hlua_channel_send);
6643 hlua_class_function(gL.T, "forward", hlua_channel_forward);
6644 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
6645 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
6646
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006647 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006648
6649 /* Register previous table in the registry with reference and named entry. */
6650 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6651 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
6652 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6653
6654 /*
6655 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006656 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006657 *
6658 */
6659
6660 /* Create and fill the metatable. */
6661 lua_newtable(gL.T);
6662
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006663 /* Create the __tostring identifier */
6664 lua_pushstring(gL.T, "__tostring");
6665 lua_pushstring(gL.T, CLASS_FETCHES);
6666 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6667 lua_rawset(gL.T, -3);
6668
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006669 /* Create and fille the __index entry. */
6670 lua_pushstring(gL.T, "__index");
6671 lua_newtable(gL.T);
6672
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006673 /* Browse existing fetches and create the associated
6674 * object method.
6675 */
6676 sf = NULL;
6677 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
6678
6679 /* Dont register the keywork if the arguments check function are
6680 * not safe during the runtime.
6681 */
6682 if ((sf->val_args != NULL) &&
6683 (sf->val_args != val_payload_lv) &&
6684 (sf->val_args != val_hdr))
6685 continue;
6686
6687 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
6688 * by an underscore.
6689 */
6690 strncpy(trash.str, sf->kw, trash.size);
6691 trash.str[trash.size - 1] = '\0';
6692 for (p = trash.str; *p; p++)
6693 if (*p == '.' || *p == '-' || *p == '+')
6694 *p = '_';
6695
6696 /* Register the function. */
6697 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01006698 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006699 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006700 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006701 }
6702
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006703 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006704
6705 /* Register previous table in the registry with reference and named entry. */
6706 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6707 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
6708 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6709
6710 /*
6711 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006712 * Register class Converters
6713 *
6714 */
6715
6716 /* Create and fill the metatable. */
6717 lua_newtable(gL.T);
6718
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006719 /* Create the __tostring identifier */
6720 lua_pushstring(gL.T, "__tostring");
6721 lua_pushstring(gL.T, CLASS_CONVERTERS);
6722 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6723 lua_rawset(gL.T, -3);
6724
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006725 /* Create and fill the __index entry. */
6726 lua_pushstring(gL.T, "__index");
6727 lua_newtable(gL.T);
6728
6729 /* Browse existing converters and create the associated
6730 * object method.
6731 */
6732 sc = NULL;
6733 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
6734 /* Dont register the keywork if the arguments check function are
6735 * not safe during the runtime.
6736 */
6737 if (sc->val_args != NULL)
6738 continue;
6739
6740 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
6741 * by an underscore.
6742 */
6743 strncpy(trash.str, sc->kw, trash.size);
6744 trash.str[trash.size - 1] = '\0';
6745 for (p = trash.str; *p; p++)
6746 if (*p == '.' || *p == '-' || *p == '+')
6747 *p = '_';
6748
6749 /* Register the function. */
6750 lua_pushstring(gL.T, trash.str);
6751 lua_pushlightuserdata(gL.T, sc);
6752 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006753 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006754 }
6755
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006756 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006757
6758 /* Register previous table in the registry with reference and named entry. */
6759 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6760 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
6761 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6762
6763 /*
6764 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006765 * Register class HTTP
6766 *
6767 */
6768
6769 /* Create and fill the metatable. */
6770 lua_newtable(gL.T);
6771
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006772 /* Create the __tostring identifier */
6773 lua_pushstring(gL.T, "__tostring");
6774 lua_pushstring(gL.T, CLASS_HTTP);
6775 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6776 lua_rawset(gL.T, -3);
6777
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006778 /* Create and fille the __index entry. */
6779 lua_pushstring(gL.T, "__index");
6780 lua_newtable(gL.T);
6781
6782 /* Register Lua functions. */
6783 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
6784 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
6785 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
6786 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
6787 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
6788 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
6789 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
6790 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
6791 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
6792 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
6793
6794 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
6795 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
6796 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
6797 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
6798 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
6799 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006800 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006801
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006802 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006803
6804 /* Register previous table in the registry with reference and named entry. */
6805 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6806 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
6807 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6808
6809 /*
6810 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006811 * Register class AppletTCP
6812 *
6813 */
6814
6815 /* Create and fill the metatable. */
6816 lua_newtable(gL.T);
6817
6818 /* Create the __tostring identifier */
6819 lua_pushstring(gL.T, "__tostring");
6820 lua_pushstring(gL.T, CLASS_APPLET_TCP);
6821 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6822 lua_rawset(gL.T, -3);
6823
6824 /* Create and fille the __index entry. */
6825 lua_pushstring(gL.T, "__index");
6826 lua_newtable(gL.T);
6827
6828 /* Register Lua functions. */
6829 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
6830 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
6831 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
6832
6833 lua_settable(gL.T, -3);
6834
6835 /* Register previous table in the registry with reference and named entry. */
6836 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6837 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_APPLET_TCP); /* register class session. */
6838 class_applet_tcp_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6839
6840 /*
6841 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006842 * Register class AppletHTTP
6843 *
6844 */
6845
6846 /* Create and fill the metatable. */
6847 lua_newtable(gL.T);
6848
6849 /* Create the __tostring identifier */
6850 lua_pushstring(gL.T, "__tostring");
6851 lua_pushstring(gL.T, CLASS_APPLET_HTTP);
6852 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6853 lua_rawset(gL.T, -3);
6854
6855 /* Create and fille the __index entry. */
6856 lua_pushstring(gL.T, "__index");
6857 lua_newtable(gL.T);
6858
6859 /* Register Lua functions. */
6860 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
6861 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
6862 hlua_class_function(gL.T, "send", hlua_applet_http_send);
6863 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
6864 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
6865 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
6866
6867 lua_settable(gL.T, -3);
6868
6869 /* Register previous table in the registry with reference and named entry. */
6870 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6871 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_APPLET_HTTP); /* register class session. */
6872 class_applet_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6873
6874 /*
6875 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006876 * Register class TXN
6877 *
6878 */
6879
6880 /* Create and fill the metatable. */
6881 lua_newtable(gL.T);
6882
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006883 /* Create the __tostring identifier */
6884 lua_pushstring(gL.T, "__tostring");
6885 lua_pushstring(gL.T, CLASS_TXN);
6886 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6887 lua_rawset(gL.T, -3);
6888
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006889 /* Create and fille the __index entry. */
6890 lua_pushstring(gL.T, "__index");
6891 lua_newtable(gL.T);
6892
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006893 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01006894 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
6895 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006896 hlua_class_function(gL.T, "set_var", hlua_set_var);
6897 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006898 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006899 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
6900 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
6901 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006902 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
6903 hlua_class_function(gL.T, "log", hlua_txn_log);
6904 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
6905 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
6906 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
6907 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006908
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006909 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006910
6911 /* Register previous table in the registry with reference and named entry. */
6912 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6913 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
6914 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006915
6916 /*
6917 *
6918 * Register class Socket
6919 *
6920 */
6921
6922 /* Create and fill the metatable. */
6923 lua_newtable(gL.T);
6924
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006925 /* Create the __tostring identifier */
6926 lua_pushstring(gL.T, "__tostring");
6927 lua_pushstring(gL.T, CLASS_SOCKET);
6928 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6929 lua_rawset(gL.T, -3);
6930
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006931 /* Create and fille the __index entry. */
6932 lua_pushstring(gL.T, "__index");
6933 lua_newtable(gL.T);
6934
Baptiste Assmann84bb4932015-03-02 21:40:06 +01006935#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006936 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01006937#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006938 hlua_class_function(gL.T, "connect", hlua_socket_connect);
6939 hlua_class_function(gL.T, "send", hlua_socket_send);
6940 hlua_class_function(gL.T, "receive", hlua_socket_receive);
6941 hlua_class_function(gL.T, "close", hlua_socket_close);
6942 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
6943 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
6944 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
6945 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
6946
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006947 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006948
6949 /* Register the garbage collector entry. */
6950 lua_pushstring(gL.T, "__gc");
6951 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006952 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006953
6954 /* Register previous table in the registry with reference and named entry. */
6955 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6956 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6957 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
6958 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
6959
6960 /* Proxy and server configuration initialisation. */
6961 memset(&socket_proxy, 0, sizeof(socket_proxy));
6962 init_new_proxy(&socket_proxy);
6963 socket_proxy.parent = NULL;
6964 socket_proxy.last_change = now.tv_sec;
6965 socket_proxy.id = "LUA-SOCKET";
6966 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
6967 socket_proxy.maxconn = 0;
6968 socket_proxy.accept = NULL;
6969 socket_proxy.options2 |= PR_O2_INDEPSTR;
6970 socket_proxy.srv = NULL;
6971 socket_proxy.conn_retries = 0;
6972 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
6973
6974 /* Init TCP server: unchanged parameters */
6975 memset(&socket_tcp, 0, sizeof(socket_tcp));
6976 socket_tcp.next = NULL;
6977 socket_tcp.proxy = &socket_proxy;
6978 socket_tcp.obj_type = OBJ_TYPE_SERVER;
6979 LIST_INIT(&socket_tcp.actconns);
6980 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02006981 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02006982 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02006983 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006984 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
6985 socket_tcp.last_change = 0;
6986 socket_tcp.id = "LUA-TCP-CONN";
6987 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
6988 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
6989 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
6990
6991 /* XXX: Copy default parameter from default server,
6992 * but the default server is not initialized.
6993 */
6994 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
6995 socket_tcp.minconn = socket_proxy.defsrv.minconn;
6996 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
6997 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
6998 socket_tcp.onerror = socket_proxy.defsrv.onerror;
6999 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7000 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7001 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7002 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7003 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7004
7005 socket_tcp.check.status = HCHK_STATUS_INI;
7006 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7007 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7008 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7009 socket_tcp.check.server = &socket_tcp;
7010
7011 socket_tcp.agent.status = HCHK_STATUS_INI;
7012 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7013 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7014 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7015 socket_tcp.agent.server = &socket_tcp;
7016
7017 socket_tcp.xprt = &raw_sock;
7018
7019#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007020 /* Init TCP server: unchanged parameters */
7021 memset(&socket_ssl, 0, sizeof(socket_ssl));
7022 socket_ssl.next = NULL;
7023 socket_ssl.proxy = &socket_proxy;
7024 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7025 LIST_INIT(&socket_ssl.actconns);
7026 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007027 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007028 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007029 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007030 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
7031 socket_ssl.last_change = 0;
7032 socket_ssl.id = "LUA-SSL-CONN";
7033 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7034 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7035 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7036
7037 /* XXX: Copy default parameter from default server,
7038 * but the default server is not initialized.
7039 */
7040 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7041 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7042 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7043 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7044 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7045 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7046 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7047 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7048 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7049 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7050
7051 socket_ssl.check.status = HCHK_STATUS_INI;
7052 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7053 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7054 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7055 socket_ssl.check.server = &socket_ssl;
7056
7057 socket_ssl.agent.status = HCHK_STATUS_INI;
7058 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7059 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7060 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7061 socket_ssl.agent.server = &socket_ssl;
7062
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007063 socket_ssl.use_ssl = 1;
7064 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007065
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007066 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007067 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7068 /*
7069 *
7070 * If the keyword is not known, we can search in the registered
7071 * server keywords. This is usefull to configure special SSL
7072 * features like client certificates and ssl_verify.
7073 *
7074 */
7075 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7076 if (tmp_error != 0) {
7077 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7078 abort(); /* This must be never arrives because the command line
7079 not editable by the user. */
7080 }
7081 idx += kw->skip;
7082 }
7083 }
7084
7085 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007086 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007087#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007088}