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