blob: 2682129b58481f05073a42170ec3e8bb968e9315 [file] [log] [blame]
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001#include <sys/socket.h>
2
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01006#include <lauxlib.h>
7#include <lua.h>
8#include <lualib.h>
9
Thierry FOURNIER463119c2015-03-10 00:35:36 +010010#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
11#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010012#endif
13
Thierry FOURNIER380d0932015-01-23 14:27:52 +010014#include <ebpttree.h>
15
16#include <common/cfgparse.h>
17
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010018#include <types/connection.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010019#include <types/hlua.h>
20#include <types/proxy.h>
21
Thierry FOURNIER55da1652015-01-23 11:36:30 +010022#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020023#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010024#include <proto/channel.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010025#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010026#include <proto/hlua.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020027#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010028#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010029#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010030#include <proto/payload.h>
31#include <proto/proto_http.h>
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010032#include <proto/proto_tcp.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010033#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010034#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010035#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020036#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020037#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010038#include <proto/ssl_sock.h>
39#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010040#include <proto/task.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020041#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010042
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010043/* Lua uses longjmp to perform yield or throwing errors. This
44 * macro is used only for identifying the function that can
45 * not return because a longjmp is executed.
46 * __LJMP marks a prototype of hlua file that can use longjmp.
47 * WILL_LJMP() marks an lua function that will use longjmp.
48 * MAY_LJMP() marks an lua function that may use longjmp.
49 */
50#define __LJMP
51#define WILL_LJMP(func) func
52#define MAY_LJMP(func) func
53
Thierry FOURNIERbabae282015-09-17 11:36:37 +020054/* This couple of function executes securely some Lua calls outside of
55 * the lua runtime environment. Each Lua call can return a longjmp
56 * if it encounter a memory error.
57 *
58 * Lua documentation extract:
59 *
60 * If an error happens outside any protected environment, Lua calls
61 * a panic function (see lua_atpanic) and then calls abort, thus
62 * exiting the host application. Your panic function can avoid this
63 * exit by never returning (e.g., doing a long jump to your own
64 * recovery point outside Lua).
65 *
66 * The panic function runs as if it were a message handler (see
67 * §2.3); in particular, the error message is at the top of the
68 * stack. However, there is no guarantee about stack space. To push
69 * anything on the stack, the panic function must first check the
70 * available space (see §4.2).
71 *
72 * We must check all the Lua entry point. This includes:
73 * - The include/proto/hlua.h exported functions
74 * - the task wrapper function
75 * - The action wrapper function
76 * - The converters wrapper function
77 * - The sample-fetch wrapper functions
78 *
79 * It is tolerated that the initilisation function returns an abort.
80 * Before each Lua abort, an error message is writed on stderr.
81 *
82 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
83 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
84 * because they must be exists in the program stack when the longjmp
85 * is called.
86 */
87jmp_buf safe_ljmp_env;
88static int hlua_panic_safe(lua_State *L) { return 0; }
89static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
90
91#define SET_SAFE_LJMP(__L) \
92 ({ \
93 int ret; \
94 if (setjmp(safe_ljmp_env) != 0) { \
95 lua_atpanic(__L, hlua_panic_safe); \
96 ret = 0; \
97 } else { \
98 lua_atpanic(__L, hlua_panic_ljmp); \
99 ret = 1; \
100 } \
101 ret; \
102 })
103
104/* If we are the last function catching Lua errors, we
105 * must reset the panic function.
106 */
107#define RESET_SAFE_LJMP(__L) \
108 do { \
109 lua_atpanic(__L, hlua_panic_safe); \
110 } while(0)
111
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100112/* The main Lua execution context. */
113struct hlua gL;
114
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100115/* This is the memory pool containing all the signal structs. These
116 * struct are used to store each requiered signal between two tasks.
117 */
118struct pool_head *pool2_hlua_com;
119
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100120/* Used for Socket connection. */
121static struct proxy socket_proxy;
122static struct server socket_tcp;
123#ifdef USE_OPENSSL
124static struct server socket_ssl;
125#endif
126
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100127/* List head of the function called at the initialisation time. */
128struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
129
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100130/* The following variables contains the reference of the different
131 * Lua classes. These references are useful for identify metadata
132 * associated with an object.
133 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100134static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100135static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100136static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100137static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100138static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100139static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200140static int class_map_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100141
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100142/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200143 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100144 * short timeout. Lua linked with tasks doesn't have a timeout
145 * because a task may remain alive during all the haproxy execution.
146 */
147static unsigned int hlua_timeout_session = 4000; /* session timeout. */
148static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
149
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100150/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
151 * it is used for preventing infinite loops.
152 *
153 * I test the scheer with an infinite loop containing one incrementation
154 * and one test. I run this loop between 10 seconds, I raise a ceil of
155 * 710M loops from one interrupt each 9000 instructions, so I fix the value
156 * to one interrupt each 10 000 instructions.
157 *
158 * configured | Number of
159 * instructions | loops executed
160 * between two | in milions
161 * forced yields |
162 * ---------------+---------------
163 * 10 | 160
164 * 500 | 670
165 * 1000 | 680
166 * 5000 | 700
167 * 7000 | 700
168 * 8000 | 700
169 * 9000 | 710 <- ceil
170 * 10000 | 710
171 * 100000 | 710
172 * 1000000 | 710
173 *
174 */
175static unsigned int hlua_nb_instruction = 10000;
176
Willy Tarreau32f61e22015-03-18 17:54:59 +0100177/* Descriptor for the memory allocation state. If limit is not null, it will
178 * be enforced on any memory allocation.
179 */
180struct hlua_mem_allocator {
181 size_t allocated;
182 size_t limit;
183};
184
185static struct hlua_mem_allocator hlua_global_allocator;
186
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100187/* These functions converts types between HAProxy internal args or
188 * sample and LUA types. Another function permits to check if the
189 * LUA stack contains arguments according with an required ARG_T
190 * format.
191 */
192static int hlua_arg2lua(lua_State *L, const struct arg *arg);
193static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100194__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
195 unsigned int mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100196static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100197static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100198static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
199
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200200#define SEND_ERR(__be, __fmt, __args...) \
201 do { \
202 send_log(__be, LOG_ERR, __fmt, ## __args); \
203 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
204 Alert(__fmt, ## __args); \
205 } while (0)
206
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100207/* Used to check an Lua function type in the stack. It creates and
208 * returns a reference of the function. This function throws an
209 * error if the rgument is not a "function".
210 */
211__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
212{
213 if (!lua_isfunction(L, argno)) {
214 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
215 WILL_LJMP(luaL_argerror(L, argno, msg));
216 }
217 lua_pushvalue(L, argno);
218 return luaL_ref(L, LUA_REGISTRYINDEX);
219}
220
221/* The three following functions are useful for adding entries
222 * in a table. These functions takes a string and respectively an
223 * integer, a string or a function and add it to the table in the
224 * top of the stack.
225 *
226 * These functions throws an error if no more stack size is
227 * available.
228 */
229__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100230 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100231{
232 if (!lua_checkstack(L, 2))
233 WILL_LJMP(luaL_error(L, "full stack"));
234 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100235 lua_pushinteger(L, value);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200236 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100237}
238__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
239 const char *value)
240{
241 if (!lua_checkstack(L, 2))
242 WILL_LJMP(luaL_error(L, "full stack"));
243 lua_pushstring(L, name);
244 lua_pushstring(L, value);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200245 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100246}
247__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
248 int (*function)(lua_State *L))
249{
250 if (!lua_checkstack(L, 2))
251 WILL_LJMP(luaL_error(L, "full stack"));
252 lua_pushstring(L, name);
253 lua_pushcclosure(L, function, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200254 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100255}
256
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +0200257__LJMP static int hlua_dump_object(struct lua_State *L)
258{
259 const char *name = (const char *)lua_tostring(L, lua_upvalueindex(1));
260 lua_pushfstring(L, "HAProxy class %s", name);
261 return 1;
262}
263
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100264/* This function check the number of arguments available in the
265 * stack. If the number of arguments available is not the same
266 * then <nb> an error is throwed.
267 */
268__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
269{
270 if (lua_gettop(L) == nb)
271 return;
272 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
273}
274
275/* Return true if the data in stack[<ud>] is an object of
276 * type <class_ref>.
277 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100278static int hlua_metaistype(lua_State *L, int ud, int class_ref)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100279{
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100280 if (!lua_getmetatable(L, ud))
281 return 0;
282
283 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
284 if (!lua_rawequal(L, -1, -2)) {
285 lua_pop(L, 2);
286 return 0;
287 }
288
289 lua_pop(L, 2);
290 return 1;
291}
292
293/* Return an object of the expected type, or throws an error. */
294__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
295{
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100296 void *p;
297
298 /* Check if the stack entry is an array. */
299 if (!lua_istable(L, ud))
300 WILL_LJMP(luaL_argerror(L, ud, NULL));
301 /* Check if the metadata have the expected type. */
302 if (!hlua_metaistype(L, ud, class_ref))
303 WILL_LJMP(luaL_argerror(L, ud, NULL));
304 /* Push on the stack at the entry [0] of the table. */
305 lua_rawgeti(L, ud, 0);
306 /* Check if this entry is userdata. */
307 p = lua_touserdata(L, -1);
308 if (!p)
309 WILL_LJMP(luaL_argerror(L, ud, NULL));
310 /* Remove the entry returned by lua_rawgeti(). */
311 lua_pop(L, 1);
312 /* Return the associated struct. */
313 return p;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100314}
315
316/* This fucntion push an error string prefixed by the file name
317 * and the line number where the error is encountered.
318 */
319static int hlua_pusherror(lua_State *L, const char *fmt, ...)
320{
321 va_list argp;
322 va_start(argp, fmt);
323 luaL_where(L, 1);
324 lua_pushvfstring(L, fmt, argp);
325 va_end(argp);
326 lua_concat(L, 2);
327 return 1;
328}
329
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100330/* This function register a new signal. "lua" is the current lua
331 * execution context. It contains a pointer to the associated task.
332 * "link" is a list head attached to an other task that must be wake
333 * the lua task if an event occurs. This is useful with external
334 * events like TCP I/O or sleep functions. This funcion allocate
335 * memory for the signal.
336 */
337static int hlua_com_new(struct hlua *lua, struct list *link)
338{
339 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
340 if (!com)
341 return 0;
342 LIST_ADDQ(&lua->com, &com->purge_me);
343 LIST_ADDQ(link, &com->wake_me);
344 com->task = lua->task;
345 return 1;
346}
347
348/* This function purge all the pending signals when the LUA execution
349 * is finished. This prevent than a coprocess try to wake a deleted
350 * task. This function remove the memory associated to the signal.
351 */
352static void hlua_com_purge(struct hlua *lua)
353{
354 struct hlua_com *com, *back;
355
356 /* Delete all pending communication signals. */
357 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
358 LIST_DEL(&com->purge_me);
359 LIST_DEL(&com->wake_me);
360 pool_free2(pool2_hlua_com, com);
361 }
362}
363
364/* This function sends signals. It wakes all the tasks attached
365 * to a list head, and remove the signal, and free the used
366 * memory.
367 */
368static void hlua_com_wake(struct list *wake)
369{
370 struct hlua_com *com, *back;
371
372 /* Wake task and delete all pending communication signals. */
373 list_for_each_entry_safe(com, back, wake, wake_me) {
374 LIST_DEL(&com->purge_me);
375 LIST_DEL(&com->wake_me);
376 task_wakeup(com->task, TASK_WOKEN_MSG);
377 pool_free2(pool2_hlua_com, com);
378 }
379}
380
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100381/* This functions is used with sample fetch and converters. It
382 * converts the HAProxy configuration argument in a lua stack
383 * values.
384 *
385 * It takes an array of "arg", and each entry of the array is
386 * converted and pushed in the LUA stack.
387 */
388static int hlua_arg2lua(lua_State *L, const struct arg *arg)
389{
390 switch (arg->type) {
391 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100392 case ARGT_TIME:
393 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100394 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100395 break;
396
397 case ARGT_STR:
398 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
399 break;
400
401 case ARGT_IPV4:
402 case ARGT_IPV6:
403 case ARGT_MSK4:
404 case ARGT_MSK6:
405 case ARGT_FE:
406 case ARGT_BE:
407 case ARGT_TAB:
408 case ARGT_SRV:
409 case ARGT_USR:
410 case ARGT_MAP:
411 default:
412 lua_pushnil(L);
413 break;
414 }
415 return 1;
416}
417
418/* This function take one entrie in an LUA stack at the index "ud",
419 * and try to convert it in an HAProxy argument entry. This is useful
420 * with sample fetch wrappers. The input arguments are gived to the
421 * lua wrapper and converted as arg list by thi function.
422 */
423static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
424{
425 switch (lua_type(L, ud)) {
426
427 case LUA_TNUMBER:
428 case LUA_TBOOLEAN:
429 arg->type = ARGT_SINT;
430 arg->data.sint = lua_tointeger(L, ud);
431 break;
432
433 case LUA_TSTRING:
434 arg->type = ARGT_STR;
435 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
436 break;
437
438 case LUA_TUSERDATA:
439 case LUA_TNIL:
440 case LUA_TTABLE:
441 case LUA_TFUNCTION:
442 case LUA_TTHREAD:
443 case LUA_TLIGHTUSERDATA:
444 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200445 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100446 break;
447 }
448 return 1;
449}
450
451/* the following functions are used to convert a struct sample
452 * in Lua type. This useful to convert the return of the
453 * fetchs or converters.
454 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100455static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100456{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200457 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100458 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100459 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200460 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100461 break;
462
463 case SMP_T_BIN:
464 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200465 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100466 break;
467
468 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200469 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100470 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
471 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
472 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
473 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
474 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
475 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
476 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
477 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
478 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200479 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100480 break;
481 default:
482 lua_pushnil(L);
483 break;
484 }
485 break;
486
487 case SMP_T_IPV4:
488 case SMP_T_IPV6:
489 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200490 if (sample_casts[smp->data.type][SMP_T_STR] &&
491 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200492 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100493 else
494 lua_pushnil(L);
495 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100496 default:
497 lua_pushnil(L);
498 break;
499 }
500 return 1;
501}
502
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100503/* the following functions are used to convert a struct sample
504 * in Lua strings. This is useful to convert the return of the
505 * fetchs or converters.
506 */
507static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
508{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200509 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100510
511 case SMP_T_BIN:
512 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200513 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100514 break;
515
516 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200517 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100518 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
519 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
520 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
521 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
522 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
523 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
524 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
525 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
526 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200527 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100528 break;
529 default:
530 lua_pushstring(L, "");
531 break;
532 }
533 break;
534
535 case SMP_T_SINT:
536 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100537 case SMP_T_IPV4:
538 case SMP_T_IPV6:
539 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200540 if (sample_casts[smp->data.type][SMP_T_STR] &&
541 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200542 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100543 else
544 lua_pushstring(L, "");
545 break;
546 default:
547 lua_pushstring(L, "");
548 break;
549 }
550 return 1;
551}
552
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100553/* the following functions are used to convert an Lua type in a
554 * struct sample. This is useful to provide data from a converter
555 * to the LUA code.
556 */
557static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
558{
559 switch (lua_type(L, ud)) {
560
561 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200562 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200563 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100564 break;
565
566
567 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200568 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200569 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100570 break;
571
572 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200573 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100574 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200575 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100576 break;
577
578 case LUA_TUSERDATA:
579 case LUA_TNIL:
580 case LUA_TTABLE:
581 case LUA_TFUNCTION:
582 case LUA_TTHREAD:
583 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200584 case LUA_TNONE:
585 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200586 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200587 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100588 break;
589 }
590 return 1;
591}
592
593/* This function check the "argp" builded by another conversion function
594 * is in accord with the expected argp defined by the "mask". The fucntion
595 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100596 *
597 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
598 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100599 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100600__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
601 unsigned int mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100602{
603 int min_arg;
604 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100605 struct proxy *px;
606 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100607
608 idx = 0;
609 min_arg = ARGM(mask);
610 mask >>= ARGM_BITS;
611
612 while (1) {
613
614 /* Check oversize. */
615 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100616 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100617 }
618
619 /* Check for mandatory arguments. */
620 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100621 if (idx < min_arg) {
622
623 /* If miss other argument than the first one, we return an error. */
624 if (idx > 0)
625 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
626
627 /* If first argument have a certain type, some default values
628 * may be used. See the function smp_resolve_args().
629 */
630 switch (mask & ARGT_MASK) {
631
632 case ARGT_FE:
633 if (!(p->cap & PR_CAP_FE))
634 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
635 argp[idx].data.prx = p;
636 argp[idx].type = ARGT_FE;
637 argp[idx+1].type = ARGT_STOP;
638 break;
639
640 case ARGT_BE:
641 if (!(p->cap & PR_CAP_BE))
642 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
643 argp[idx].data.prx = p;
644 argp[idx].type = ARGT_BE;
645 argp[idx+1].type = ARGT_STOP;
646 break;
647
648 case ARGT_TAB:
649 argp[idx].data.prx = p;
650 argp[idx].type = ARGT_TAB;
651 argp[idx+1].type = ARGT_STOP;
652 break;
653
654 default:
655 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
656 break;
657 }
658 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100659 return 0;
660 }
661
662 /* Check for exceed the number of requiered argument. */
663 if ((mask & ARGT_MASK) == ARGT_STOP &&
664 argp[idx].type != ARGT_STOP) {
665 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
666 }
667
668 if ((mask & ARGT_MASK) == ARGT_STOP &&
669 argp[idx].type == ARGT_STOP) {
670 return 0;
671 }
672
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100673 /* Convert some argument types. */
674 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100675 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100676 if (argp[idx].type != ARGT_SINT)
677 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
678 argp[idx].type = ARGT_SINT;
679 break;
680
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100681 case ARGT_TIME:
682 if (argp[idx].type != ARGT_SINT)
683 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200684 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100685 break;
686
687 case ARGT_SIZE:
688 if (argp[idx].type != ARGT_SINT)
689 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200690 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100691 break;
692
693 case ARGT_FE:
694 if (argp[idx].type != ARGT_STR)
695 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
696 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
697 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200698 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100699 if (!argp[idx].data.prx)
700 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
701 argp[idx].type = ARGT_FE;
702 break;
703
704 case ARGT_BE:
705 if (argp[idx].type != ARGT_STR)
706 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
707 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
708 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200709 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100710 if (!argp[idx].data.prx)
711 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
712 argp[idx].type = ARGT_BE;
713 break;
714
715 case ARGT_TAB:
716 if (argp[idx].type != ARGT_STR)
717 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
718 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
719 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200720 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100721 if (!argp[idx].data.prx)
722 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
723 argp[idx].type = ARGT_TAB;
724 break;
725
726 case ARGT_SRV:
727 if (argp[idx].type != ARGT_STR)
728 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
729 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
730 trash.str[argp[idx].data.str.len] = 0;
731 sname = strrchr(trash.str, '/');
732 if (sname) {
733 *sname++ = '\0';
734 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200735 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100736 if (!px)
737 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
738 }
739 else {
740 sname = trash.str;
741 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100742 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100743 argp[idx].data.srv = findserver(px, sname);
744 if (!argp[idx].data.srv)
745 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
746 argp[idx].type = ARGT_SRV;
747 break;
748
749 case ARGT_IPV4:
750 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
751 trash.str[argp[idx].data.str.len] = 0;
752 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
753 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
754 argp[idx].type = ARGT_IPV4;
755 break;
756
757 case ARGT_MSK4:
758 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
759 trash.str[argp[idx].data.str.len] = 0;
760 if (!str2mask(trash.str, &argp[idx].data.ipv4))
761 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
762 argp[idx].type = ARGT_MSK4;
763 break;
764
765 case ARGT_IPV6:
766 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
767 trash.str[argp[idx].data.str.len] = 0;
768 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
769 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
770 argp[idx].type = ARGT_IPV6;
771 break;
772
773 case ARGT_MSK6:
774 case ARGT_MAP:
775 case ARGT_REG:
776 case ARGT_USR:
777 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100778 break;
779 }
780
781 /* Check for type of argument. */
782 if ((mask & ARGT_MASK) != argp[idx].type) {
783 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
784 arg_type_names[(mask & ARGT_MASK)],
785 arg_type_names[argp[idx].type & ARGT_MASK]);
786 WILL_LJMP(luaL_argerror(L, first + idx, msg));
787 }
788
789 /* Next argument. */
790 mask >>= ARGT_BITS;
791 idx++;
792 }
793}
794
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100795/*
796 * The following functions are used to make correspondance between the the
797 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100798 *
799 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100800 * - hlua_sethlua : create the association between hlua context and lua_state.
801 */
802static inline struct hlua *hlua_gethlua(lua_State *L)
803{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100804 struct hlua **hlua = lua_getextraspace(L);
805 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100806}
807static inline void hlua_sethlua(struct hlua *hlua)
808{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100809 struct hlua **hlua_store = lua_getextraspace(hlua->T);
810 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100811}
812
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100813/* This function is used to send logs. It try to send on screen (stderr)
814 * and on the default syslog server.
815 */
816static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
817{
818 struct tm tm;
819 char *p;
820
821 /* Cleanup the log message. */
822 p = trash.str;
823 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200824 if (p >= trash.str + trash.size - 1) {
825 /* Break the message if exceed the buffer size. */
826 *(p-4) = ' ';
827 *(p-3) = '.';
828 *(p-2) = '.';
829 *(p-1) = '.';
830 break;
831 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100832 if (isprint(*msg))
833 *p = *msg;
834 else
835 *p = '.';
836 }
837 *p = '\0';
838
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200839 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100840 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200841 get_localtime(date.tv_sec, &tm);
842 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100843 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
844 (int)getpid(), trash.str);
845 fflush(stderr);
846 }
847}
848
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100849/* This function just ensure that the yield will be always
850 * returned with a timeout and permit to set some flags
851 */
852__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100853 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100854{
855 struct hlua *hlua = hlua_gethlua(L);
856
857 /* Set the wake timeout. If timeout is required, we set
858 * the expiration time.
859 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100860 hlua->wake_time = tick_first(timeout, hlua->expire);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100861
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100862 hlua->flags |= flags;
863
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100864 /* Process the yield. */
865 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
866}
867
Willy Tarreau87b09662015-04-03 00:22:06 +0200868/* This function initialises the Lua environment stored in the stream.
869 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100870 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200871 *
872 * This function is particular. it initialises a new Lua thread. If the
873 * initialisation fails (example: out of memory error), the lua function
874 * throws an error (longjmp).
875 *
876 * This function manipulates two Lua stack: the main and the thread. Only
877 * the main stack can fail. The thread is not manipulated. This function
878 * MUST NOT manipulate the created thread stack state, because is not
879 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100880 */
881int hlua_ctx_init(struct hlua *lua, struct task *task)
882{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200883 if (!SET_SAFE_LJMP(gL.T)) {
884 lua->Tref = LUA_REFNIL;
885 return 0;
886 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100887 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100888 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100889 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100890 lua->T = lua_newthread(gL.T);
891 if (!lua->T) {
892 lua->Tref = LUA_REFNIL;
893 return 0;
894 }
895 hlua_sethlua(lua);
896 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
897 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200898 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100899 return 1;
900}
901
Willy Tarreau87b09662015-04-03 00:22:06 +0200902/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100903 * is destroyed. The destroy also the memory context. The struct "lua"
904 * is not freed.
905 */
906void hlua_ctx_destroy(struct hlua *lua)
907{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100908 if (!lua->T)
909 return;
910
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100911 /* Purge all the pending signals. */
912 hlua_com_purge(lua);
913
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100914 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
915 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200916
917 /* Forces a garbage collecting process. If the Lua program is finished
918 * without error, we run the GC on the thread pointer. Its freed all
919 * the unused memory.
920 * If the thread is finnish with an error or is currently yielded,
921 * it seems that the GC applied on the thread doesn't clean anything,
922 * so e run the GC on the main thread.
923 * NOTE: maybe this action locks all the Lua threads untiml the en of
924 * the garbage collection.
925 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200926 if (lua->flags & HLUA_MUST_GC) {
927 lua_gc(lua->T, LUA_GCCOLLECT, 0);
928 if (lua_status(lua->T) != LUA_OK)
929 lua_gc(gL.T, LUA_GCCOLLECT, 0);
930 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200931
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200932 lua->T = NULL;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100933}
934
935/* This function is used to restore the Lua context when a coroutine
936 * fails. This function copy the common memory between old coroutine
937 * and the new coroutine. The old coroutine is destroyed, and its
938 * replaced by the new coroutine.
939 * If the flag "keep_msg" is set, the last entry of the old is assumed
940 * as string error message and it is copied in the new stack.
941 */
942static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
943{
944 lua_State *T;
945 int new_ref;
946
947 /* Renew the main LUA stack doesn't have sense. */
948 if (lua == &gL)
949 return 0;
950
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100951 /* New Lua coroutine. */
952 T = lua_newthread(gL.T);
953 if (!T)
954 return 0;
955
956 /* Copy last error message. */
957 if (keep_msg)
958 lua_xmove(lua->T, T, 1);
959
960 /* Copy data between the coroutines. */
961 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
962 lua_xmove(lua->T, T, 1);
963 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
964
965 /* Destroy old data. */
966 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
967
968 /* The thread is garbage collected by Lua. */
969 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
970
971 /* Fill the struct with the new coroutine values. */
972 lua->Mref = new_ref;
973 lua->T = T;
974 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
975
976 /* Set context. */
977 hlua_sethlua(lua);
978
979 return 1;
980}
981
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100982void hlua_hook(lua_State *L, lua_Debug *ar)
983{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100984 struct hlua *hlua = hlua_gethlua(L);
985
986 /* Lua cannot yield when its returning from a function,
987 * so, we can fix the interrupt hook to 1 instruction,
988 * expecting that the function is finnished.
989 */
990 if (lua_gethookmask(L) & LUA_MASKRET) {
991 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
992 return;
993 }
994
995 /* restore the interrupt condition. */
996 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
997
998 /* If we interrupt the Lua processing in yieldable state, we yield.
999 * If the state is not yieldable, trying yield causes an error.
1000 */
1001 if (lua_isyieldable(L))
1002 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
1003
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001004 /* If we cannot yield, update the clock and check the timeout. */
1005 tv_update_date(0, 1);
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001006 if (tick_is_expired(hlua->expire, now_ms)) {
1007 lua_pushfstring(L, "execution timeout");
1008 WILL_LJMP(lua_error(L));
1009 }
1010
1011 /* Try to interrupt the process at the end of the current
1012 * unyieldable function.
1013 */
1014 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001015}
1016
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001017/* This function start or resumes the Lua stack execution. If the flag
1018 * "yield_allowed" if no set and the LUA stack execution returns a yield
1019 * The function return an error.
1020 *
1021 * The function can returns 4 values:
1022 * - HLUA_E_OK : The execution is terminated without any errors.
1023 * - HLUA_E_AGAIN : The execution must continue at the next associated
1024 * task wakeup.
1025 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
1026 * the top of the stack.
1027 * - HLUA_E_ERR : An error has occured without error message.
1028 *
1029 * If an error occured, the stack is renewed and it is ready to run new
1030 * LUA code.
1031 */
1032static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1033{
1034 int ret;
1035 const char *msg;
1036
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001037 /* If we want to resume the task, then check first the execution timeout.
1038 * if it is reached, we can interrupt the Lua processing.
1039 */
1040 if (tick_is_expired(lua->expire, now_ms))
1041 goto timeout_reached;
1042
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001043resume_execution:
1044
1045 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1046 * instructions. it is used for preventing infinite loops.
1047 */
1048 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1049
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001050 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001051 HLUA_SET_RUN(lua);
1052 HLUA_CLR_CTRLYIELD(lua);
1053 HLUA_CLR_WAKERESWR(lua);
1054 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001055
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001056 /* Call the function. */
1057 ret = lua_resume(lua->T, gL.T, lua->nargs);
1058 switch (ret) {
1059
1060 case LUA_OK:
1061 ret = HLUA_E_OK;
1062 break;
1063
1064 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001065 /* Check if the execution timeout is expired. It it is the case, we
1066 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001067 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001068 if (tick_is_expired(lua->expire, now_ms)) {
1069
1070timeout_reached:
1071
1072 lua_settop(lua->T, 0); /* Empty the stack. */
1073 if (!lua_checkstack(lua->T, 1)) {
1074 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001075 break;
1076 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001077 lua_pushfstring(lua->T, "execution timeout");
1078 ret = HLUA_E_ERRMSG;
1079 break;
1080 }
1081 /* Process the forced yield. if the general yield is not allowed or
1082 * if no task were associated this the current Lua execution
1083 * coroutine, we resume the execution. Else we want to return in the
1084 * scheduler and we want to be waked up again, to continue the
1085 * current Lua execution. So we schedule our own task.
1086 */
1087 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001088 if (!yield_allowed || !lua->task)
1089 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001090 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001091 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001092 if (!yield_allowed) {
1093 lua_settop(lua->T, 0); /* Empty the stack. */
1094 if (!lua_checkstack(lua->T, 1)) {
1095 ret = HLUA_E_ERR;
1096 break;
1097 }
1098 lua_pushfstring(lua->T, "yield not allowed");
1099 ret = HLUA_E_ERRMSG;
1100 break;
1101 }
1102 ret = HLUA_E_AGAIN;
1103 break;
1104
1105 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001106
1107 /* Special exit case. The traditionnal exit is returned as an error
1108 * because the errors ares the only one mean to return immediately
1109 * from and lua execution.
1110 */
1111 if (lua->flags & HLUA_EXIT) {
1112 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001113 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001114 break;
1115 }
1116
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001117 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001118 if (!lua_checkstack(lua->T, 1)) {
1119 ret = HLUA_E_ERR;
1120 break;
1121 }
1122 msg = lua_tostring(lua->T, -1);
1123 lua_settop(lua->T, 0); /* Empty the stack. */
1124 lua_pop(lua->T, 1);
1125 if (msg)
1126 lua_pushfstring(lua->T, "runtime error: %s", msg);
1127 else
1128 lua_pushfstring(lua->T, "unknown runtime error");
1129 ret = HLUA_E_ERRMSG;
1130 break;
1131
1132 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001133 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001134 lua_settop(lua->T, 0); /* Empty the stack. */
1135 if (!lua_checkstack(lua->T, 1)) {
1136 ret = HLUA_E_ERR;
1137 break;
1138 }
1139 lua_pushfstring(lua->T, "out of memory error");
1140 ret = HLUA_E_ERRMSG;
1141 break;
1142
1143 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001144 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001145 if (!lua_checkstack(lua->T, 1)) {
1146 ret = HLUA_E_ERR;
1147 break;
1148 }
1149 msg = lua_tostring(lua->T, -1);
1150 lua_settop(lua->T, 0); /* Empty the stack. */
1151 lua_pop(lua->T, 1);
1152 if (msg)
1153 lua_pushfstring(lua->T, "message handler error: %s", msg);
1154 else
1155 lua_pushfstring(lua->T, "message handler error");
1156 ret = HLUA_E_ERRMSG;
1157 break;
1158
1159 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001160 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001161 lua_settop(lua->T, 0); /* Empty the stack. */
1162 if (!lua_checkstack(lua->T, 1)) {
1163 ret = HLUA_E_ERR;
1164 break;
1165 }
1166 lua_pushfstring(lua->T, "unknonwn error");
1167 ret = HLUA_E_ERRMSG;
1168 break;
1169 }
1170
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001171 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001172 if (lua->flags & HLUA_MUST_GC &&
1173 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001174 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1175
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001176 switch (ret) {
1177 case HLUA_E_AGAIN:
1178 break;
1179
1180 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001181 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001182 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001183 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001184 break;
1185
1186 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001187 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001188 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001189 hlua_ctx_renew(lua, 0);
1190 break;
1191
1192 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001193 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001194 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001195 break;
1196 }
1197
1198 return ret;
1199}
1200
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001201/* This function exit the current code. */
1202__LJMP static int hlua_done(lua_State *L)
1203{
1204 struct hlua *hlua = hlua_gethlua(L);
1205
1206 hlua->flags |= HLUA_EXIT;
1207 WILL_LJMP(lua_error(L));
1208
1209 return 0;
1210}
1211
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001212/* This function is an LUA binding. It provides a function
1213 * for deleting ACL from a referenced ACL file.
1214 */
1215__LJMP static int hlua_del_acl(lua_State *L)
1216{
1217 const char *name;
1218 const char *key;
1219 struct pat_ref *ref;
1220
1221 MAY_LJMP(check_args(L, 2, "del_acl"));
1222
1223 name = MAY_LJMP(luaL_checkstring(L, 1));
1224 key = MAY_LJMP(luaL_checkstring(L, 2));
1225
1226 ref = pat_ref_lookup(name);
1227 if (!ref)
1228 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
1229
1230 pat_ref_delete(ref, key);
1231 return 0;
1232}
1233
1234/* This function is an LUA binding. It provides a function
1235 * for deleting map entry from a referenced map file.
1236 */
1237static int hlua_del_map(lua_State *L)
1238{
1239 const char *name;
1240 const char *key;
1241 struct pat_ref *ref;
1242
1243 MAY_LJMP(check_args(L, 2, "del_map"));
1244
1245 name = MAY_LJMP(luaL_checkstring(L, 1));
1246 key = MAY_LJMP(luaL_checkstring(L, 2));
1247
1248 ref = pat_ref_lookup(name);
1249 if (!ref)
1250 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
1251
1252 pat_ref_delete(ref, key);
1253 return 0;
1254}
1255
1256/* This function is an LUA binding. It provides a function
1257 * for adding ACL pattern from a referenced ACL file.
1258 */
1259static int hlua_add_acl(lua_State *L)
1260{
1261 const char *name;
1262 const char *key;
1263 struct pat_ref *ref;
1264
1265 MAY_LJMP(check_args(L, 2, "add_acl"));
1266
1267 name = MAY_LJMP(luaL_checkstring(L, 1));
1268 key = MAY_LJMP(luaL_checkstring(L, 2));
1269
1270 ref = pat_ref_lookup(name);
1271 if (!ref)
1272 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
1273
1274 if (pat_ref_find_elt(ref, key) == NULL)
1275 pat_ref_add(ref, key, NULL, NULL);
1276 return 0;
1277}
1278
1279/* This function is an LUA binding. It provides a function
1280 * for setting map pattern and sample from a referenced map
1281 * file.
1282 */
1283static int hlua_set_map(lua_State *L)
1284{
1285 const char *name;
1286 const char *key;
1287 const char *value;
1288 struct pat_ref *ref;
1289
1290 MAY_LJMP(check_args(L, 3, "set_map"));
1291
1292 name = MAY_LJMP(luaL_checkstring(L, 1));
1293 key = MAY_LJMP(luaL_checkstring(L, 2));
1294 value = MAY_LJMP(luaL_checkstring(L, 3));
1295
1296 ref = pat_ref_lookup(name);
1297 if (!ref)
1298 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
1299
1300 if (pat_ref_find_elt(ref, key) != NULL)
1301 pat_ref_set(ref, key, value, NULL);
1302 else
1303 pat_ref_add(ref, key, value, NULL);
1304 return 0;
1305}
1306
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001307/* A class is a lot of memory that contain data. This data can be a table,
1308 * an integer or user data. This data is associated with a metatable. This
1309 * metatable have an original version registred in the global context with
1310 * the name of the object (_G[<name>] = <metable> ).
1311 *
1312 * A metable is a table that modify the standard behavior of a standard
1313 * access to the associated data. The entries of this new metatable are
1314 * defined as is:
1315 *
1316 * http://lua-users.org/wiki/MetatableEvents
1317 *
1318 * __index
1319 *
1320 * we access an absent field in a table, the result is nil. This is
1321 * true, but it is not the whole truth. Actually, such access triggers
1322 * the interpreter to look for an __index metamethod: If there is no
1323 * such method, as usually happens, then the access results in nil;
1324 * otherwise, the metamethod will provide the result.
1325 *
1326 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1327 * the key does not appear in the table, but the metatable has an __index
1328 * property:
1329 *
1330 * - if the value is a function, the function is called, passing in the
1331 * table and the key; the return value of that function is returned as
1332 * the result.
1333 *
1334 * - if the value is another table, the value of the key in that table is
1335 * asked for and returned (and if it doesn't exist in that table, but that
1336 * table's metatable has an __index property, then it continues on up)
1337 *
1338 * - Use "rawget(myTable,key)" to skip this metamethod.
1339 *
1340 * http://www.lua.org/pil/13.4.1.html
1341 *
1342 * __newindex
1343 *
1344 * Like __index, but control property assignment.
1345 *
1346 * __mode - Control weak references. A string value with one or both
1347 * of the characters 'k' and 'v' which specifies that the the
1348 * keys and/or values in the table are weak references.
1349 *
1350 * __call - Treat a table like a function. When a table is followed by
1351 * parenthesis such as "myTable( 'foo' )" and the metatable has
1352 * a __call key pointing to a function, that function is invoked
1353 * (passing any specified arguments) and the return value is
1354 * returned.
1355 *
1356 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1357 * called, if the metatable for myTable has a __metatable
1358 * key, the value of that key is returned instead of the
1359 * actual metatable.
1360 *
1361 * __tostring - Control string representation. When the builtin
1362 * "tostring( myTable )" function is called, if the metatable
1363 * for myTable has a __tostring property set to a function,
1364 * that function is invoked (passing myTable to it) and the
1365 * return value is used as the string representation.
1366 *
1367 * __len - Control table length. When the table length is requested using
1368 * the length operator ( '#' ), if the metatable for myTable has
1369 * a __len key pointing to a function, that function is invoked
1370 * (passing myTable to it) and the return value used as the value
1371 * of "#myTable".
1372 *
1373 * __gc - Userdata finalizer code. When userdata is set to be garbage
1374 * collected, if the metatable has a __gc field pointing to a
1375 * function, that function is first invoked, passing the userdata
1376 * to it. The __gc metamethod is not called for tables.
1377 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1378 *
1379 * Special metamethods for redefining standard operators:
1380 * http://www.lua.org/pil/13.1.html
1381 *
1382 * __add "+"
1383 * __sub "-"
1384 * __mul "*"
1385 * __div "/"
1386 * __unm "!"
1387 * __pow "^"
1388 * __concat ".."
1389 *
1390 * Special methods for redfining standar relations
1391 * http://www.lua.org/pil/13.2.html
1392 *
1393 * __eq "=="
1394 * __lt "<"
1395 * __le "<="
1396 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001397
1398/*
1399 *
1400 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001401 * Class Map
1402 *
1403 *
1404 */
1405
1406/* Returns a struct hlua_map if the stack entry "ud" is
1407 * a class session, otherwise it throws an error.
1408 */
1409__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1410{
1411 return (struct map_descriptor *)MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
1412}
1413
1414/* This function is the map constructor. It don't need
1415 * the class Map object. It creates and return a new Map
1416 * object. It must be called only during "body" or "init"
1417 * context because it process some filesystem accesses.
1418 */
1419__LJMP static int hlua_map_new(struct lua_State *L)
1420{
1421 const char *fn;
1422 int match = PAT_MATCH_STR;
1423 struct sample_conv conv;
1424 const char *file = "";
1425 int line = 0;
1426 lua_Debug ar;
1427 char *err = NULL;
1428 struct arg args[2];
1429
1430 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1431 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1432
1433 fn = MAY_LJMP(luaL_checkstring(L, 1));
1434
1435 if (lua_gettop(L) >= 2) {
1436 match = MAY_LJMP(luaL_checkinteger(L, 2));
1437 if (match < 0 || match >= PAT_MATCH_NUM)
1438 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1439 }
1440
1441 /* Get Lua filename and line number. */
1442 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1443 lua_getinfo(L, "Sl", &ar); /* get info about it */
1444 if (ar.currentline > 0) { /* is there info? */
1445 file = ar.short_src;
1446 line = ar.currentline;
1447 }
1448 }
1449
1450 /* fill fake sample_conv struct. */
1451 conv.kw = ""; /* unused. */
1452 conv.process = NULL; /* unused. */
1453 conv.arg_mask = 0; /* unused. */
1454 conv.val_args = NULL; /* unused. */
1455 conv.out_type = SMP_T_STR;
1456 conv.private = (void *)(long)match;
1457 switch (match) {
1458 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1459 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1460 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1461 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1462 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1463 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1464 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001465 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001466 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1467 default:
1468 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1469 }
1470
1471 /* fill fake args. */
1472 args[0].type = ARGT_STR;
1473 args[0].data.str.str = (char *)fn;
1474 args[1].type = ARGT_STOP;
1475
1476 /* load the map. */
1477 if (!sample_load_map(args, &conv, file, line, &err)) {
1478 /* error case: we cant use luaL_error because we must
1479 * free the err variable.
1480 */
1481 luaL_where(L, 1);
1482 lua_pushfstring(L, "'new': %s.", err);
1483 lua_concat(L, 2);
1484 free(err);
1485 WILL_LJMP(lua_error(L));
1486 }
1487
1488 /* create the lua object. */
1489 lua_newtable(L);
1490 lua_pushlightuserdata(L, args[0].data.map);
1491 lua_rawseti(L, -2, 0);
1492
1493 /* Pop a class Map metatable and affect it to the userdata. */
1494 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1495 lua_setmetatable(L, -2);
1496
1497
1498 return 1;
1499}
1500
1501__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1502{
1503 struct map_descriptor *desc;
1504 struct pattern *pat;
1505 struct sample smp;
1506
1507 MAY_LJMP(check_args(L, 2, "lookup"));
1508 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001509 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001510 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001511 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001512 }
1513 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001514 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001515 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001516 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 +02001517 }
1518
1519 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001520 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001521 if (str)
1522 lua_pushstring(L, "");
1523 else
1524 lua_pushnil(L);
1525 return 1;
1526 }
1527
1528 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001529 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001530 return 1;
1531}
1532
1533__LJMP static int hlua_map_lookup(struct lua_State *L)
1534{
1535 return _hlua_map_lookup(L, 0);
1536}
1537
1538__LJMP static int hlua_map_slookup(struct lua_State *L)
1539{
1540 return _hlua_map_lookup(L, 1);
1541}
1542
1543/*
1544 *
1545 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001546 * Class Socket
1547 *
1548 *
1549 */
1550
1551__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1552{
1553 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1554}
1555
1556/* This function is the handler called for each I/O on the established
1557 * connection. It is used for notify space avalaible to send or data
1558 * received.
1559 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001560static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001561{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001562 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001563 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001564
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001565 /* If the connection object is not avalaible, close all the
1566 * streams and wakeup everithing waiting for.
1567 */
1568 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001569 si_shutw(si);
1570 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001571 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001572 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1573 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001574 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001575 }
1576
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001577 /* If we cant write, wakeup the pending write signals. */
1578 if (channel_output_closed(si_ic(si)))
1579 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1580
1581 /* If we cant read, wakeup the pending read signals. */
1582 if (channel_input_closed(si_oc(si)))
1583 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1584
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001585 /* if the connection is not estabkished, inform the stream that we want
1586 * to be notified whenever the connection completes.
1587 */
1588 if (!(c->flags & CO_FL_CONNECTED)) {
1589 si_applet_cant_get(si);
1590 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001591 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001592 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001593
1594 /* This function is called after the connect. */
1595 appctx->ctx.hlua.connected = 1;
1596
1597 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001598 if (channel_may_recv(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001599 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1600
1601 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001602 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001603 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1604}
1605
Willy Tarreau87b09662015-04-03 00:22:06 +02001606/* This function is called when the "struct stream" is destroyed.
1607 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001608 * Wake all the pending signals.
1609 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001610static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001611{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001612 /* Remove my link in the original object. */
1613 if (appctx->ctx.hlua.socket)
1614 appctx->ctx.hlua.socket->s = NULL;
1615
1616 /* Wake all the task waiting for me. */
1617 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1618 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1619}
1620
1621/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001622 * uses this object. If the stream does not exists, just quit.
1623 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001624 * pending signal can rest in the read and write lists. destroy
1625 * it.
1626 */
1627__LJMP static int hlua_socket_gc(lua_State *L)
1628{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001629 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001630 struct appctx *appctx;
1631
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001632 MAY_LJMP(check_args(L, 1, "__gc"));
1633
1634 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001635 if (!socket->s)
1636 return 0;
1637
Willy Tarreau87b09662015-04-03 00:22:06 +02001638 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001639 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001640 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001641 socket->s = NULL;
1642 appctx->ctx.hlua.socket = NULL;
1643
1644 return 0;
1645}
1646
1647/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001648 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001649 */
1650__LJMP static int hlua_socket_close(lua_State *L)
1651{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001652 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001653 struct appctx *appctx;
1654
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001655 MAY_LJMP(check_args(L, 1, "close"));
1656
1657 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001658 if (!socket->s)
1659 return 0;
1660
Willy Tarreau87b09662015-04-03 00:22:06 +02001661 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001662 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001663 appctx = objt_appctx(socket->s->si[0].end);
1664 appctx->ctx.hlua.socket = NULL;
1665 socket->s = NULL;
1666
1667 return 0;
1668}
1669
1670/* This Lua function assumes that the stack contain three parameters.
1671 * 1 - USERDATA containing a struct socket
1672 * 2 - INTEGER with values of the macro defined below
1673 * If the integer is -1, we must read at most one line.
1674 * If the integer is -2, we ust read all the data until the
1675 * end of the stream.
1676 * If the integer is positive value, we must read a number of
1677 * bytes corresponding to this value.
1678 */
1679#define HLSR_READ_LINE (-1)
1680#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001681__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001682{
1683 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1684 int wanted = lua_tointeger(L, 2);
1685 struct hlua *hlua = hlua_gethlua(L);
1686 struct appctx *appctx;
1687 int len;
1688 int nblk;
1689 char *blk1;
1690 int len1;
1691 char *blk2;
1692 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001693 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001694 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001695
1696 /* Check if this lua stack is schedulable. */
1697 if (!hlua || !hlua->task)
1698 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1699 "'frontend', 'backend' or 'task'"));
1700
1701 /* check for connection closed. If some data where read, return it. */
1702 if (!socket->s)
1703 goto connection_closed;
1704
Willy Tarreau94aa6172015-03-13 14:19:06 +01001705 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001706 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001707 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001708 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001709 if (nblk < 0) /* Connection close. */
1710 goto connection_closed;
1711 if (nblk == 0) /* No data avalaible. */
1712 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001713
1714 /* remove final \r\n. */
1715 if (nblk == 1) {
1716 if (blk1[len1-1] == '\n') {
1717 len1--;
1718 skip_at_end++;
1719 if (blk1[len1-1] == '\r') {
1720 len1--;
1721 skip_at_end++;
1722 }
1723 }
1724 }
1725 else {
1726 if (blk2[len2-1] == '\n') {
1727 len2--;
1728 skip_at_end++;
1729 if (blk2[len2-1] == '\r') {
1730 len2--;
1731 skip_at_end++;
1732 }
1733 }
1734 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001735 }
1736
1737 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001738 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001739 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001740 if (nblk < 0) /* Connection close. */
1741 goto connection_closed;
1742 if (nblk == 0) /* No data avalaible. */
1743 goto connection_empty;
1744 }
1745
1746 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001747 /* Read a block of 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 if (len1 > wanted) {
1755 nblk = 1;
1756 len1 = wanted;
1757 } if (nblk == 2 && len1 + len2 > wanted)
1758 len2 = wanted - len1;
1759 }
1760
1761 len = len1;
1762
1763 luaL_addlstring(&socket->b, blk1, len1);
1764 if (nblk == 2) {
1765 len += len2;
1766 luaL_addlstring(&socket->b, blk2, len2);
1767 }
1768
1769 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001770 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001771
1772 /* Don't wait anything. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001773 stream_int_notify(&socket->s->si[0]);
1774 stream_int_update_applet(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001775
1776 /* If the pattern reclaim to read all the data
1777 * in the connection, got out.
1778 */
1779 if (wanted == HLSR_READ_ALL)
1780 goto connection_empty;
1781 else if (wanted >= 0 && len < wanted)
1782 goto connection_empty;
1783
1784 /* Return result. */
1785 luaL_pushresult(&socket->b);
1786 return 1;
1787
1788connection_closed:
1789
1790 /* If the buffer containds data. */
1791 if (socket->b.n > 0) {
1792 luaL_pushresult(&socket->b);
1793 return 1;
1794 }
1795 lua_pushnil(L);
1796 lua_pushstring(L, "connection closed.");
1797 return 2;
1798
1799connection_empty:
1800
1801 appctx = objt_appctx(socket->s->si[0].end);
1802 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1803 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001804 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001805 return 0;
1806}
1807
1808/* This Lus function gets two parameters. The first one can be string
1809 * or a number. If the string is "*l", the user require one line. If
1810 * the string is "*a", the user require all the content of the stream.
1811 * If the value is a number, the user require a number of bytes equal
1812 * to the value. The default value is "*l" (a line).
1813 *
1814 * This paraeter with a variable type is converted in integer. This
1815 * integer takes this values:
1816 * -1 : read a line
1817 * -2 : read all the stream
1818 * >0 : amount if bytes.
1819 *
1820 * The second parameter is optinal. It contains a string that must be
1821 * concatenated with the read data.
1822 */
1823__LJMP static int hlua_socket_receive(struct lua_State *L)
1824{
1825 int wanted = HLSR_READ_LINE;
1826 const char *pattern;
1827 int type;
1828 char *error;
1829 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001830 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001831
1832 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1833 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1834
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001835 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001836
1837 /* check for pattern. */
1838 if (lua_gettop(L) >= 2) {
1839 type = lua_type(L, 2);
1840 if (type == LUA_TSTRING) {
1841 pattern = lua_tostring(L, 2);
1842 if (strcmp(pattern, "*a") == 0)
1843 wanted = HLSR_READ_ALL;
1844 else if (strcmp(pattern, "*l") == 0)
1845 wanted = HLSR_READ_LINE;
1846 else {
1847 wanted = strtoll(pattern, &error, 10);
1848 if (*error != '\0')
1849 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1850 }
1851 }
1852 else if (type == LUA_TNUMBER) {
1853 wanted = lua_tointeger(L, 2);
1854 if (wanted < 0)
1855 WILL_LJMP(luaL_error(L, "Unsupported size."));
1856 }
1857 }
1858
1859 /* Set pattern. */
1860 lua_pushinteger(L, wanted);
1861 lua_replace(L, 2);
1862
1863 /* init bufffer, and fiil it wih prefix. */
1864 luaL_buffinit(L, &socket->b);
1865
1866 /* Check prefix. */
1867 if (lua_gettop(L) >= 3) {
1868 if (lua_type(L, 3) != LUA_TSTRING)
1869 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1870 pattern = lua_tolstring(L, 3, &len);
1871 luaL_addlstring(&socket->b, pattern, len);
1872 }
1873
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001874 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001875}
1876
1877/* Write the Lua input string in the output buffer.
1878 * This fucntion returns a yield if no space are available.
1879 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001880static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001881{
1882 struct hlua_socket *socket;
1883 struct hlua *hlua = hlua_gethlua(L);
1884 struct appctx *appctx;
1885 size_t buf_len;
1886 const char *buf;
1887 int len;
1888 int send_len;
1889 int sent;
1890
1891 /* Check if this lua stack is schedulable. */
1892 if (!hlua || !hlua->task)
1893 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1894 "'frontend', 'backend' or 'task'"));
1895
1896 /* Get object */
1897 socket = MAY_LJMP(hlua_checksocket(L, 1));
1898 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001899 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001900
1901 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001902 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001903 lua_pushinteger(L, -1);
1904 return 1;
1905 }
1906
1907 /* Update the input buffer data. */
1908 buf += sent;
1909 send_len = buf_len - sent;
1910
1911 /* All the data are sent. */
1912 if (sent >= buf_len)
1913 return 1; /* Implicitly return the length sent. */
1914
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001915 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1916 * the request buffer if its not required.
1917 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001918 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001919 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001920 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001921 goto hlua_socket_write_yield_return;
1922 }
1923 }
1924
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001925 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001926 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001927 if (len <= 0)
1928 goto hlua_socket_write_yield_return;
1929
1930 /* send data */
1931 if (len < send_len)
1932 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001933 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001934
1935 /* "Not enough space" (-1), "Buffer too little to contain
1936 * the data" (-2) are not expected because the available length
1937 * is tested.
1938 * Other unknown error are also not expected.
1939 */
1940 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001941 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001942 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001943
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001944 MAY_LJMP(hlua_socket_close(L));
1945 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001946 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001947 return 1;
1948 }
1949
1950 /* update buffers. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001951 stream_int_notify(&socket->s->si[0]);
1952 stream_int_update_applet(&socket->s->si[0]);
1953
Willy Tarreau94aa6172015-03-13 14:19:06 +01001954 socket->s->req.rex = TICK_ETERNITY;
1955 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001956
1957 /* Update length sent. */
1958 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001959 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001960
1961 /* All the data buffer is sent ? */
1962 if (sent + len >= buf_len)
1963 return 1;
1964
1965hlua_socket_write_yield_return:
1966 appctx = objt_appctx(socket->s->si[0].end);
1967 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1968 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001969 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001970 return 0;
1971}
1972
1973/* This function initiate the send of data. It just check the input
1974 * parameters and push an integer in the Lua stack that contain the
1975 * amount of data writed in the buffer. This is used by the function
1976 * "hlua_socket_write_yield" that can yield.
1977 *
1978 * The Lua function gets between 3 and 4 parameters. The first one is
1979 * the associated object. The second is a string buffer. The third is
1980 * a facultative integer that represents where is the buffer position
1981 * of the start of the data that can send. The first byte is the
1982 * position "1". The default value is "1". The fourth argument is a
1983 * facultative integer that represents where is the buffer position
1984 * of the end of the data that can send. The default is the last byte.
1985 */
1986static int hlua_socket_send(struct lua_State *L)
1987{
1988 int i;
1989 int j;
1990 const char *buf;
1991 size_t buf_len;
1992
1993 /* Check number of arguments. */
1994 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1995 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1996
1997 /* Get the string. */
1998 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1999
2000 /* Get and check j. */
2001 if (lua_gettop(L) == 4) {
2002 j = MAY_LJMP(luaL_checkinteger(L, 4));
2003 if (j < 0)
2004 j = buf_len + j + 1;
2005 if (j > buf_len)
2006 j = buf_len + 1;
2007 lua_pop(L, 1);
2008 }
2009 else
2010 j = buf_len;
2011
2012 /* Get and check i. */
2013 if (lua_gettop(L) == 3) {
2014 i = MAY_LJMP(luaL_checkinteger(L, 3));
2015 if (i < 0)
2016 i = buf_len + i + 1;
2017 if (i > buf_len)
2018 i = buf_len + 1;
2019 lua_pop(L, 1);
2020 } else
2021 i = 1;
2022
2023 /* Check bth i and j. */
2024 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002025 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002026 return 1;
2027 }
2028 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002029 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002030 return 1;
2031 }
2032 if (i == 0)
2033 i = 1;
2034 if (j == 0)
2035 j = 1;
2036
2037 /* Pop the string. */
2038 lua_pop(L, 1);
2039
2040 /* Update the buffer length. */
2041 buf += i - 1;
2042 buf_len = j - i + 1;
2043 lua_pushlstring(L, buf, buf_len);
2044
2045 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002046 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002047
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002048 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002049}
2050
Willy Tarreau22b0a682015-06-17 19:43:49 +02002051#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002052__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2053{
2054 static char buffer[SOCKET_INFO_MAX_LEN];
2055 int ret;
2056 int len;
2057 char *p;
2058
2059 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2060 if (ret <= 0) {
2061 lua_pushnil(L);
2062 return 1;
2063 }
2064
2065 if (ret == AF_UNIX) {
2066 lua_pushstring(L, buffer+1);
2067 return 1;
2068 }
2069 else if (ret == AF_INET6) {
2070 buffer[0] = '[';
2071 len = strlen(buffer);
2072 buffer[len] = ']';
2073 len++;
2074 buffer[len] = ':';
2075 len++;
2076 p = buffer;
2077 }
2078 else if (ret == AF_INET) {
2079 p = buffer + 1;
2080 len = strlen(p);
2081 p[len] = ':';
2082 len++;
2083 }
2084 else {
2085 lua_pushnil(L);
2086 return 1;
2087 }
2088
2089 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2090 lua_pushnil(L);
2091 return 1;
2092 }
2093
2094 lua_pushstring(L, p);
2095 return 1;
2096}
2097
2098/* Returns information about the peer of the connection. */
2099__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2100{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002101 struct hlua_socket *socket;
2102 struct connection *conn;
2103
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002104 MAY_LJMP(check_args(L, 1, "getpeername"));
2105
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002106 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002107
2108 /* Check if the tcp object is avalaible. */
2109 if (!socket->s) {
2110 lua_pushnil(L);
2111 return 1;
2112 }
2113
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002114 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002115 if (!conn) {
2116 lua_pushnil(L);
2117 return 1;
2118 }
2119
2120 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
2121 unsigned int salen = sizeof(conn->addr.to);
2122 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
2123 lua_pushnil(L);
2124 return 1;
2125 }
2126 conn->flags |= CO_FL_ADDR_TO_SET;
2127 }
2128
2129 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2130}
2131
2132/* Returns information about my connection side. */
2133static int hlua_socket_getsockname(struct lua_State *L)
2134{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002135 struct hlua_socket *socket;
2136 struct connection *conn;
2137
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002138 MAY_LJMP(check_args(L, 1, "getsockname"));
2139
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002140 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002141
2142 /* Check if the tcp object is avalaible. */
2143 if (!socket->s) {
2144 lua_pushnil(L);
2145 return 1;
2146 }
2147
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002148 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002149 if (!conn) {
2150 lua_pushnil(L);
2151 return 1;
2152 }
2153
2154 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2155 unsigned int salen = sizeof(conn->addr.from);
2156 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2157 lua_pushnil(L);
2158 return 1;
2159 }
2160 conn->flags |= CO_FL_ADDR_FROM_SET;
2161 }
2162
2163 return hlua_socket_info(L, &conn->addr.from);
2164}
2165
2166/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002167static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002168 .obj_type = OBJ_TYPE_APPLET,
2169 .name = "<LUA_TCP>",
2170 .fct = hlua_socket_handler,
2171 .release = hlua_socket_release,
2172};
2173
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002174__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002175{
2176 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2177 struct hlua *hlua = hlua_gethlua(L);
2178 struct appctx *appctx;
2179
2180 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002181 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002182 lua_pushnil(L);
2183 lua_pushstring(L, "Can't connect");
2184 return 2;
2185 }
2186
2187 appctx = objt_appctx(socket->s->si[0].end);
2188
2189 /* Check for connection established. */
2190 if (appctx->ctx.hlua.connected) {
2191 lua_pushinteger(L, 1);
2192 return 1;
2193 }
2194
2195 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2196 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002197 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002198 return 0;
2199}
2200
2201/* This function fail or initite the connection. */
2202__LJMP static int hlua_socket_connect(struct lua_State *L)
2203{
2204 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002205 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002206 const char *ip;
2207 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002208 struct hlua *hlua;
2209 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002210 int low, high;
2211 struct sockaddr_storage *addr;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002212
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002213 if (lua_gettop(L) < 2)
2214 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002215
2216 /* Get args. */
2217 socket = MAY_LJMP(hlua_checksocket(L, 1));
2218 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002219 if (lua_gettop(L) >= 3)
2220 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002221
Willy Tarreau973a5422015-08-05 21:47:23 +02002222 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002223 if (!conn)
2224 WILL_LJMP(luaL_error(L, "connect: internal error"));
2225
Willy Tarreau3adac082015-09-26 17:51:09 +02002226 /* needed for the connection not to be closed */
2227 conn->target = socket->s->target;
2228
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002229 /* Parse ip address. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002230 addr = str2sa_range(ip, &low, &high, NULL, NULL, NULL, 0);
2231 if (!addr)
2232 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
2233 if (low != high)
2234 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
2235 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002236
2237 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002238 if (low == 0) {
2239 if (conn->addr.to.ss_family == AF_INET) {
2240 if (port == -1)
2241 WILL_LJMP(luaL_error(L, "connect: port missing"));
2242 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2243 } else if (conn->addr.to.ss_family == AF_INET6) {
2244 if (port == -1)
2245 WILL_LJMP(luaL_error(L, "connect: port missing"));
2246 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2247 }
2248 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002249
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002250 hlua = hlua_gethlua(L);
2251 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002252
2253 /* inform the stream that we want to be notified whenever the
2254 * connection completes.
2255 */
2256 si_applet_cant_get(&socket->s->si[0]);
2257 si_applet_cant_put(&socket->s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002258 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002259
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002260 hlua->flags |= HLUA_MUST_GC;
2261
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002262 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2263 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002264 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002265
2266 return 0;
2267}
2268
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002269#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002270__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2271{
2272 struct hlua_socket *socket;
2273
2274 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2275 socket = MAY_LJMP(hlua_checksocket(L, 1));
2276 socket->s->target = &socket_ssl.obj_type;
2277 return MAY_LJMP(hlua_socket_connect(L));
2278}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002279#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002280
2281__LJMP static int hlua_socket_setoption(struct lua_State *L)
2282{
2283 return 0;
2284}
2285
2286__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2287{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002288 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002289 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002290
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002291 MAY_LJMP(check_args(L, 2, "settimeout"));
2292
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002293 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002294 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002295
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002296 socket->s->req.rto = tmout;
2297 socket->s->req.wto = tmout;
2298 socket->s->res.rto = tmout;
2299 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002300
2301 return 0;
2302}
2303
2304__LJMP static int hlua_socket_new(lua_State *L)
2305{
2306 struct hlua_socket *socket;
2307 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002308 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002309 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002310 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311
2312 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002313 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002314 hlua_pusherror(L, "socket: full stack");
2315 goto out_fail_conf;
2316 }
2317
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002318 /* Create the object: obj[0] = userdata. */
2319 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002320 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002321 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002322 memset(socket, 0, sizeof(*socket));
2323
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002324 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002325 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002326 hlua_pusherror(L, "socket: uninitialized pools.");
2327 goto out_fail_conf;
2328 }
2329
Willy Tarreau87b09662015-04-03 00:22:06 +02002330 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002331 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2332 lua_setmetatable(L, -2);
2333
Willy Tarreaud420a972015-04-06 00:39:18 +02002334 /* Create the applet context */
2335 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002336 if (!appctx) {
2337 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002338 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002339 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002340
Willy Tarreaud420a972015-04-06 00:39:18 +02002341 appctx->ctx.hlua.socket = socket;
2342 appctx->ctx.hlua.connected = 0;
2343 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2344 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002345
Willy Tarreaud420a972015-04-06 00:39:18 +02002346 /* Now create a session, task and stream for this applet */
2347 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2348 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002349 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002350 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002351 }
2352
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002353 task = task_new();
2354 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002355 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002356 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002357 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002358 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002359
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002360 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002361 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002362 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002363 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002364 }
2365
Willy Tarreaud420a972015-04-06 00:39:18 +02002366 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002367 socket->s = strm;
2368 strm->hlua.T = NULL;
2369 strm->hlua.Tref = LUA_REFNIL;
2370 strm->hlua.Mref = LUA_REFNIL;
2371 strm->hlua.nargs = 0;
2372 strm->hlua.flags = 0;
2373 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002374
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002375 /* Configure "right" stream interface. this "si" is used to connect
2376 * and retrieve data from the server. The connection is initialized
2377 * with the "struct server".
2378 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002379 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002380
2381 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002382 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2383 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002384
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002385 /* Update statistics counters. */
2386 socket_proxy.feconn++; /* beconn will be increased later */
2387 jobs++;
2388 totalconn++;
2389
2390 /* Return yield waiting for connection. */
2391 return 1;
2392
Willy Tarreaud420a972015-04-06 00:39:18 +02002393 out_fail_stream:
2394 task_free(task);
2395 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002396 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002397 out_fail_sess:
2398 appctx_free(appctx);
2399 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002400 WILL_LJMP(lua_error(L));
2401 return 0;
2402}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002403
2404/*
2405 *
2406 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002407 * Class Channel
2408 *
2409 *
2410 */
2411
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002412/* The state between the channel data and the HTTP parser state can be
2413 * unconsistent, so reset the parser and call it again. Warning, this
2414 * action not revalidate the request and not send a 400 if the modified
2415 * resuest is not valid.
2416 *
2417 * This function never fails. If dir is 0 we are a request, if it is 1
2418 * its a response.
2419 */
2420static void hlua_resynchonize_proto(struct stream *stream, int dir)
2421{
2422 /* Protocol HTTP. */
2423 if (stream->be->mode == PR_MODE_HTTP) {
2424
2425 if (dir == 0)
2426 http_txn_reset_req(stream->txn);
2427 else if (dir == 1)
2428 http_txn_reset_res(stream->txn);
2429
2430 if (stream->txn->hdr_idx.v)
2431 hdr_idx_init(&stream->txn->hdr_idx);
2432
2433 if (dir == 0)
2434 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
2435 else if (dir == 1)
2436 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2437 }
2438}
2439
2440/* Check the protocole integrity after the Lua manipulations.
2441 * Close the stream and returns 0 if fails, otherwise returns 1.
2442 */
2443static int hlua_check_proto(struct stream *stream, int dir)
2444{
2445 const struct chunk msg = { .len = 0 };
2446
Willy Tarreau9af89f72015-09-26 11:50:08 +02002447 /* Protocol HTTP. The message parsing state must match the request or
2448 * response state. The problem that may happen is that Lua modifies
2449 * the request or response message *after* it was parsed, and corrupted
2450 * it so that it could not be processed anymore. We just need to verify
2451 * if the parser is still expected to run or not.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002452 */
2453 if (stream->be->mode == PR_MODE_HTTP) {
Willy Tarreau9af89f72015-09-26 11:50:08 +02002454 if (dir == 0 &&
2455 !(stream->req.analysers & AN_REQ_WAIT_HTTP) &&
2456 stream->txn->req.msg_state < HTTP_MSG_BODY) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002457 stream_int_retnclose(&stream->si[0], &msg);
2458 return 0;
2459 }
Willy Tarreau9af89f72015-09-26 11:50:08 +02002460 else if (dir == 1 &&
2461 !(stream->res.analysers & AN_RES_WAIT_HTTP) &&
2462 stream->txn->rsp.msg_state < HTTP_MSG_BODY) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002463 stream_int_retnclose(&stream->si[0], &msg);
2464 return 0;
2465 }
2466 }
2467 return 1;
2468}
2469
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002470/* Returns the struct hlua_channel join to the class channel in the
2471 * stack entry "ud" or throws an argument error.
2472 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002473__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002474{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002475 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002476}
2477
Willy Tarreau47860ed2015-03-10 14:07:50 +01002478/* Pushes the channel onto the top of the stack. If the stask does not have a
2479 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002480 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002481static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002482{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002483 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002484 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002485 return 0;
2486
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002487 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002488 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002489 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002490
2491 /* Pop a class sesison metatable and affect it to the userdata. */
2492 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2493 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002494 return 1;
2495}
2496
2497/* Duplicate all the data present in the input channel and put it
2498 * in a string LUA variables. Returns -1 and push a nil value in
2499 * the stack if the channel is closed and all the data are consumed,
2500 * returns 0 if no data are available, otherwise it returns the length
2501 * of the builded string.
2502 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002503static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002504{
2505 char *blk1;
2506 char *blk2;
2507 int len1;
2508 int len2;
2509 int ret;
2510 luaL_Buffer b;
2511
Willy Tarreau47860ed2015-03-10 14:07:50 +01002512 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002513 if (unlikely(ret == 0))
2514 return 0;
2515
2516 if (unlikely(ret < 0)) {
2517 lua_pushnil(L);
2518 return -1;
2519 }
2520
2521 luaL_buffinit(L, &b);
2522 luaL_addlstring(&b, blk1, len1);
2523 if (unlikely(ret == 2))
2524 luaL_addlstring(&b, blk2, len2);
2525 luaL_pushresult(&b);
2526
2527 if (unlikely(ret == 2))
2528 return len1 + len2;
2529 return len1;
2530}
2531
2532/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2533 * a yield. This function keep the data in the buffer.
2534 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002535__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002536{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002537 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002538
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002539 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2540
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002541 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002542 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002543 return 1;
2544}
2545
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002546/* Check arguments for the function "hlua_channel_dup_yield". */
2547__LJMP static int hlua_channel_dup(lua_State *L)
2548{
2549 MAY_LJMP(check_args(L, 1, "dup"));
2550 MAY_LJMP(hlua_checkchannel(L, 1));
2551 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2552}
2553
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002554/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2555 * a yield. This function consumes the data in the buffer. It returns
2556 * a string containing the data or a nil pointer if no data are available
2557 * and the channel is closed.
2558 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002559__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002560{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002561 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002562 int ret;
2563
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002564 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002565
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002566 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002567 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002568 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002569
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002570 if (unlikely(ret == -1))
2571 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002572
Willy Tarreau47860ed2015-03-10 14:07:50 +01002573 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002574 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002575 return 1;
2576}
2577
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002578/* Check arguments for the fucntion "hlua_channel_get_yield". */
2579__LJMP static int hlua_channel_get(lua_State *L)
2580{
2581 MAY_LJMP(check_args(L, 1, "get"));
2582 MAY_LJMP(hlua_checkchannel(L, 1));
2583 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2584}
2585
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002586/* This functions consumes and returns one line. If the channel is closed,
2587 * and the last data does not contains a final '\n', the data are returned
2588 * without the final '\n'. When no more data are avalaible, it returns nil
2589 * value.
2590 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002591__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002592{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002593 char *blk1;
2594 char *blk2;
2595 int len1;
2596 int len2;
2597 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002598 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002599 int ret;
2600 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002601
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002602 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2603
Willy Tarreau47860ed2015-03-10 14:07:50 +01002604 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002605 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002606 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002607
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002608 if (ret == -1) {
2609 lua_pushnil(L);
2610 return 1;
2611 }
2612
2613 luaL_buffinit(L, &b);
2614 luaL_addlstring(&b, blk1, len1);
2615 len = len1;
2616 if (unlikely(ret == 2)) {
2617 luaL_addlstring(&b, blk2, len2);
2618 len += len2;
2619 }
2620 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002621 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002622 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002623 return 1;
2624}
2625
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002626/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2627__LJMP static int hlua_channel_getline(lua_State *L)
2628{
2629 MAY_LJMP(check_args(L, 1, "getline"));
2630 MAY_LJMP(hlua_checkchannel(L, 1));
2631 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2632}
2633
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002634/* This function takes a string as input, and append it at the
2635 * input side of channel. If the data is too big, but a space
2636 * is probably available after sending some data, the function
2637 * yield. If the data is bigger than the buffer, or if the
2638 * channel is closed, it returns -1. otherwise, it returns the
2639 * amount of data writed.
2640 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002641__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002642{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002643 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002644 size_t len;
2645 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2646 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2647 int ret;
2648 int max;
2649
Willy Tarreau47860ed2015-03-10 14:07:50 +01002650 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002651 if (max > len - l)
2652 max = len - l;
2653
Willy Tarreau47860ed2015-03-10 14:07:50 +01002654 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002655 if (ret == -2 || ret == -3) {
2656 lua_pushinteger(L, -1);
2657 return 1;
2658 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002659 if (ret == -1) {
2660 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002661 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002662 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002663 l += ret;
2664 lua_pop(L, 1);
2665 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002666 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002667
Willy Tarreau47860ed2015-03-10 14:07:50 +01002668 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2669 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002670 /* There are no space avalaible, and the output buffer is empty.
2671 * in this case, we cannot add more data, so we cannot yield,
2672 * we return the amount of copyied data.
2673 */
2674 return 1;
2675 }
2676 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002677 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002678 return 1;
2679}
2680
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002681/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002682 * of the writed string, or -1 if the channel is closed or if the
2683 * buffer size is too little for the data.
2684 */
2685__LJMP static int hlua_channel_append(lua_State *L)
2686{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002687 size_t len;
2688
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002689 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002690 MAY_LJMP(hlua_checkchannel(L, 1));
2691 MAY_LJMP(luaL_checklstring(L, 2, &len));
2692 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002693 lua_pushinteger(L, 0);
2694
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002695 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002696}
2697
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002698/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002699 * his process by cleaning the buffer. The result is a replacement
2700 * of the current data. It returns the length of the writed string,
2701 * or -1 if the channel is closed or if the buffer size is too
2702 * little for the data.
2703 */
2704__LJMP static int hlua_channel_set(lua_State *L)
2705{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002706 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002707
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002708 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002709 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002710 lua_pushinteger(L, 0);
2711
Willy Tarreau47860ed2015-03-10 14:07:50 +01002712 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002713
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002714 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002715}
2716
2717/* Append data in the output side of the buffer. This data is immediatly
2718 * sent. The fcuntion returns the ammount of data writed. If the buffer
2719 * cannot contains the data, the function yield. The function returns -1
2720 * if the channel is closed.
2721 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002722__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002723{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002724 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002725 size_t len;
2726 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2727 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2728 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002729 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002730
Willy Tarreau47860ed2015-03-10 14:07:50 +01002731 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002732 lua_pushinteger(L, -1);
2733 return 1;
2734 }
2735
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002736 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2737 * the request buffer if its not required.
2738 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002739 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002740 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002741 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002742 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002743 }
2744 }
2745
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002746 /* the writed data will be immediatly sent, so we can check
2747 * the avalaible space without taking in account the reserve.
2748 * The reserve is guaranted for the processing of incoming
2749 * data, because the buffer will be flushed.
2750 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002751 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002752
2753 /* If there are no space avalaible, and the output buffer is empty.
2754 * in this case, we cannot add more data, so we cannot yield,
2755 * we return the amount of copyied data.
2756 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002757 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002758 return 1;
2759
2760 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002761 if (max > len - l)
2762 max = len - l;
2763
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002764 /* The buffer avalaible size may be not contiguous. This test
2765 * detects a non contiguous buffer and realign it.
2766 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002767 if (bi_space_for_replace(chn->buf) < max)
2768 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002769
2770 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002771 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002772
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002773 /* buffer replace considers that the input part is filled.
2774 * so, I must forward these new data in the output part.
2775 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002776 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002777
2778 l += max;
2779 lua_pop(L, 1);
2780 lua_pushinteger(L, l);
2781
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002782 /* If there are no space avalaible, and the output buffer is empty.
2783 * in this case, we cannot add more data, so we cannot yield,
2784 * we return the amount of copyied data.
2785 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002786 max = chn->buf->size - buffer_len(chn->buf);
2787 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002788 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002789
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002790 if (l < len) {
2791 /* If we are waiting for space in the response buffer, we
2792 * must set the flag WAKERESWR. This flag required the task
2793 * wake up if any activity is detected on the response buffer.
2794 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002795 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002796 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002797 else
2798 HLUA_SET_WAKEREQWR(hlua);
2799 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002800 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002801
2802 return 1;
2803}
2804
2805/* Just a wraper of "_hlua_channel_send". This wrapper permits
2806 * yield the LUA process, and resume it without checking the
2807 * input arguments.
2808 */
2809__LJMP static int hlua_channel_send(lua_State *L)
2810{
2811 MAY_LJMP(check_args(L, 2, "send"));
2812 lua_pushinteger(L, 0);
2813
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002814 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002815}
2816
2817/* This function forward and amount of butes. The data pass from
2818 * the input side of the buffer to the output side, and can be
2819 * forwarded. This function never fails.
2820 *
2821 * The Lua function takes an amount of bytes to be forwarded in
2822 * imput. It returns the number of bytes forwarded.
2823 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002824__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002825{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002826 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002827 int len;
2828 int l;
2829 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002830 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002831
2832 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2833 len = MAY_LJMP(luaL_checkinteger(L, 2));
2834 l = MAY_LJMP(luaL_checkinteger(L, -1));
2835
2836 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002837 if (max > chn->buf->i)
2838 max = chn->buf->i;
2839 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002840 l += max;
2841
2842 lua_pop(L, 1);
2843 lua_pushinteger(L, l);
2844
2845 /* Check if it miss bytes to forward. */
2846 if (l < len) {
2847 /* The the input channel or the output channel are closed, we
2848 * must return the amount of data forwarded.
2849 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002850 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002851 return 1;
2852
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002853 /* If we are waiting for space data in the response buffer, we
2854 * must set the flag WAKERESWR. This flag required the task
2855 * wake up if any activity is detected on the response buffer.
2856 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002857 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002858 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002859 else
2860 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002861
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002862 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002863 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002864 }
2865
2866 return 1;
2867}
2868
2869/* Just check the input and prepare the stack for the previous
2870 * function "hlua_channel_forward_yield"
2871 */
2872__LJMP static int hlua_channel_forward(lua_State *L)
2873{
2874 MAY_LJMP(check_args(L, 2, "forward"));
2875 MAY_LJMP(hlua_checkchannel(L, 1));
2876 MAY_LJMP(luaL_checkinteger(L, 2));
2877
2878 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002879 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002880}
2881
2882/* Just returns the number of bytes available in the input
2883 * side of the buffer. This function never fails.
2884 */
2885__LJMP static int hlua_channel_get_in_len(lua_State *L)
2886{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002887 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002888
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002889 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002890 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002891 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002892 return 1;
2893}
2894
2895/* Just returns the number of bytes available in the output
2896 * side of the buffer. This function never fails.
2897 */
2898__LJMP static int hlua_channel_get_out_len(lua_State *L)
2899{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002900 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002901
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002902 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002903 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002904 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002905 return 1;
2906}
2907
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002908/*
2909 *
2910 *
2911 * Class Fetches
2912 *
2913 *
2914 */
2915
2916/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002917 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002918 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002919__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002920{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002921 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002922}
2923
2924/* This function creates and push in the stack a fetch object according
2925 * with a current TXN.
2926 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002927static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002928{
Willy Tarreau7073c472015-04-06 11:15:40 +02002929 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002930
2931 /* Check stack size. */
2932 if (!lua_checkstack(L, 3))
2933 return 0;
2934
2935 /* Create the object: obj[0] = userdata.
2936 * Note that the base of the Fetches object is the
2937 * transaction object.
2938 */
2939 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002940 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002941 lua_rawseti(L, -2, 0);
2942
Willy Tarreau7073c472015-04-06 11:15:40 +02002943 hsmp->s = txn->s;
2944 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002945 hsmp->stringsafe = stringsafe;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002946
2947 /* Pop a class sesison metatable and affect it to the userdata. */
2948 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2949 lua_setmetatable(L, -2);
2950
2951 return 1;
2952}
2953
2954/* This function is an LUA binding. It is called with each sample-fetch.
2955 * It uses closure argument to store the associated sample-fetch. It
2956 * returns only one argument or throws an error. An error is thrown
2957 * only if an error is encountered during the argument parsing. If
2958 * the "sample-fetch" function fails, nil is returned.
2959 */
2960__LJMP static int hlua_run_sample_fetch(lua_State *L)
2961{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002962 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002963 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002964 struct arg args[ARGM_NBARGS + 1];
2965 int i;
2966 struct sample smp;
2967
2968 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002969 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002970
2971 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002972 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002973
2974 /* Get extra arguments. */
2975 for (i = 0; i < lua_gettop(L) - 1; i++) {
2976 if (i >= ARGM_NBARGS)
2977 break;
2978 hlua_lua2arg(L, i + 2, &args[i]);
2979 }
2980 args[i].type = ARGT_STOP;
2981
2982 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002983 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002984
2985 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002986 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002987 lua_pushfstring(L, "error in arguments");
2988 WILL_LJMP(lua_error(L));
2989 }
2990
2991 /* Initialise the sample. */
2992 memset(&smp, 0, sizeof(smp));
2993
2994 /* Run the sample fetch process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02002995 smp.px = hsmp->p;
2996 smp.sess = hsmp->s->sess;
2997 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02002998 smp.opt = 0;
Thierry FOURNIER0786d052015-05-11 15:42:45 +02002999 if (!f->process(args, &smp, f->kw, f->private)) {
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003000 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003001 lua_pushstring(L, "");
3002 else
3003 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003004 return 1;
3005 }
3006
3007 /* Convert the returned sample in lua value. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003008 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003009 hlua_smp2lua_str(L, &smp);
3010 else
3011 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003012 return 1;
3013}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003014
3015/*
3016 *
3017 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003018 * Class Converters
3019 *
3020 *
3021 */
3022
3023/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003024 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003025 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003026__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003027{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003028 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003029}
3030
3031/* This function creates and push in the stack a Converters object
3032 * according with a current TXN.
3033 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003034static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003035{
Willy Tarreau7073c472015-04-06 11:15:40 +02003036 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003037
3038 /* Check stack size. */
3039 if (!lua_checkstack(L, 3))
3040 return 0;
3041
3042 /* Create the object: obj[0] = userdata.
3043 * Note that the base of the Converters object is the
3044 * same than the TXN object.
3045 */
3046 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003047 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003048 lua_rawseti(L, -2, 0);
3049
Willy Tarreau7073c472015-04-06 11:15:40 +02003050 hsmp->s = txn->s;
3051 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02003052 hsmp->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003053
Willy Tarreau87b09662015-04-03 00:22:06 +02003054 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003055 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3056 lua_setmetatable(L, -2);
3057
3058 return 1;
3059}
3060
3061/* This function is an LUA binding. It is called with each converter.
3062 * It uses closure argument to store the associated converter. It
3063 * returns only one argument or throws an error. An error is thrown
3064 * only if an error is encountered during the argument parsing. If
3065 * the converter function function fails, nil is returned.
3066 */
3067__LJMP static int hlua_run_sample_conv(lua_State *L)
3068{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003069 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003070 struct sample_conv *conv;
3071 struct arg args[ARGM_NBARGS + 1];
3072 int i;
3073 struct sample smp;
3074
3075 /* Get closure arguments. */
3076 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
3077
3078 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003079 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003080
3081 /* Get extra arguments. */
3082 for (i = 0; i < lua_gettop(L) - 2; i++) {
3083 if (i >= ARGM_NBARGS)
3084 break;
3085 hlua_lua2arg(L, i + 3, &args[i]);
3086 }
3087 args[i].type = ARGT_STOP;
3088
3089 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003090 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003091
3092 /* Run the special args checker. */
3093 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3094 hlua_pusherror(L, "error in arguments");
3095 WILL_LJMP(lua_error(L));
3096 }
3097
3098 /* Initialise the sample. */
3099 if (!hlua_lua2smp(L, 2, &smp)) {
3100 hlua_pusherror(L, "error in the input argument");
3101 WILL_LJMP(lua_error(L));
3102 }
3103
3104 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003105 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003106 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003107 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003108 WILL_LJMP(lua_error(L));
3109 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003110 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3111 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003112 hlua_pusherror(L, "error during the input argument casting");
3113 WILL_LJMP(lua_error(L));
3114 }
3115
3116 /* Run the sample conversion process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02003117 smp.px = hsmp->p;
3118 smp.sess = hsmp->s->sess;
3119 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02003120 smp.opt = 0;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003121 if (!conv->process(args, &smp, conv->private)) {
Willy Tarreauda5f1082015-04-06 11:17:13 +02003122 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003123 lua_pushstring(L, "");
3124 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003125 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003126 return 1;
3127 }
3128
3129 /* Convert the returned sample in lua value. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003130 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003131 hlua_smp2lua_str(L, &smp);
3132 else
3133 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003134 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003135}
3136
3137/*
3138 *
3139 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003140 * Class HTTP
3141 *
3142 *
3143 */
3144
3145/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003146 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003147 */
3148__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
3149{
3150 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
3151}
3152
3153/* This function creates and push in the stack a HTTP object
3154 * according with a current TXN.
3155 */
3156static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
3157{
Willy Tarreau9a8ad862015-04-06 11:14:06 +02003158 struct hlua_txn *htxn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003159
3160 /* Check stack size. */
3161 if (!lua_checkstack(L, 3))
3162 return 0;
3163
3164 /* Create the object: obj[0] = userdata.
3165 * Note that the base of the Converters object is the
3166 * same than the TXN object.
3167 */
3168 lua_newtable(L);
Willy Tarreau9a8ad862015-04-06 11:14:06 +02003169 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003170 lua_rawseti(L, -2, 0);
3171
Willy Tarreau9a8ad862015-04-06 11:14:06 +02003172 htxn->s = txn->s;
3173 htxn->p = txn->p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003174
Willy Tarreau87b09662015-04-03 00:22:06 +02003175 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003176 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
3177 lua_setmetatable(L, -2);
3178
3179 return 1;
3180}
3181
3182/* This function creates ans returns an array of HTTP headers.
3183 * This function does not fails. It is used as wrapper with the
3184 * 2 following functions.
3185 */
3186__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3187{
3188 const char *cur_ptr, *cur_next, *p;
3189 int old_idx, cur_idx;
3190 struct hdr_idx_elem *cur_hdr;
3191 const char *hn, *hv;
3192 int hnl, hvl;
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003193 int type;
3194 const char *in;
3195 char *out;
3196 int len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003197
3198 /* Create the table. */
3199 lua_newtable(L);
3200
Willy Tarreaueee5b512015-04-03 23:46:31 +02003201 if (!htxn->s->txn)
3202 return 1;
3203
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003204 /* Build array of headers. */
3205 old_idx = 0;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003206 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003207
3208 while (1) {
Willy Tarreaueee5b512015-04-03 23:46:31 +02003209 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003210 if (!cur_idx)
3211 break;
3212 old_idx = cur_idx;
3213
Willy Tarreaueee5b512015-04-03 23:46:31 +02003214 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003215 cur_ptr = cur_next;
3216 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
3217
3218 /* Now we have one full header at cur_ptr of len cur_hdr->len,
3219 * and the next header starts at cur_next. We'll check
3220 * this header in the list as well as against the default
3221 * rule.
3222 */
3223
3224 /* look for ': *'. */
3225 hn = cur_ptr;
3226 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
3227 if (p >= cur_ptr+cur_hdr->len)
3228 continue;
3229 hnl = p - hn;
3230 p++;
3231 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
3232 p++;
3233 if (p >= cur_ptr+cur_hdr->len)
3234 continue;
3235 hv = p;
3236 hvl = cur_ptr+cur_hdr->len-p;
3237
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003238 /* Lowercase the key. Don't check the size of trash, it have
3239 * the size of one buffer and the input data contains in one
3240 * buffer.
3241 */
3242 out = trash.str;
3243 for (in=hn; in<hn+hnl; in++, out++)
3244 *out = tolower(*in);
3245 *out = '\0';
3246
3247 /* Check for existing entry:
3248 * assume that the table is on the top of the stack, and
3249 * push the key in the stack, the function lua_gettable()
3250 * perform the lookup.
3251 */
3252 lua_pushlstring(L, trash.str, hnl);
3253 lua_gettable(L, -2);
3254 type = lua_type(L, -1);
3255
3256 switch (type) {
3257 case LUA_TNIL:
3258 /* Table not found, create it. */
3259 lua_pop(L, 1); /* remove the nil value. */
3260 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
3261 lua_newtable(L); /* create and push empty table. */
3262 lua_pushlstring(L, hv, hvl); /* push header value. */
3263 lua_rawseti(L, -2, 0); /* index header value (pop it). */
3264 lua_rawset(L, -3); /* index new table with header name (pop the values). */
3265 break;
3266
3267 case LUA_TTABLE:
3268 /* Entry found: push the value in the table. */
3269 len = lua_rawlen(L, -1);
3270 lua_pushlstring(L, hv, hvl); /* push header value. */
3271 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
3272 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
3273 break;
3274
3275 default:
3276 /* Other cases are errors. */
3277 hlua_pusherror(L, "internal error during the parsing of headers.");
3278 WILL_LJMP(lua_error(L));
3279 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003280 }
3281
3282 return 1;
3283}
3284
3285__LJMP static int hlua_http_req_get_headers(lua_State *L)
3286{
3287 struct hlua_txn *htxn;
3288
3289 MAY_LJMP(check_args(L, 1, "req_get_headers"));
3290 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3291
Willy Tarreaueee5b512015-04-03 23:46:31 +02003292 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003293}
3294
3295__LJMP static int hlua_http_res_get_headers(lua_State *L)
3296{
3297 struct hlua_txn *htxn;
3298
3299 MAY_LJMP(check_args(L, 1, "res_get_headers"));
3300 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3301
Willy Tarreaueee5b512015-04-03 23:46:31 +02003302 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003303}
3304
3305/* This function replace full header, or just a value in
3306 * the request or in the response. It is a wrapper fir the
3307 * 4 following functions.
3308 */
3309__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
3310 struct http_msg *msg, int action)
3311{
3312 size_t name_len;
3313 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3314 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
3315 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
3316 struct my_regex re;
3317
3318 if (!regex_comp(reg, &re, 1, 1, NULL))
3319 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
3320
3321 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
3322 regex_free(&re);
3323 return 0;
3324}
3325
3326__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
3327{
3328 struct hlua_txn *htxn;
3329
3330 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3331 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3332
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003333 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003334}
3335
3336__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
3337{
3338 struct hlua_txn *htxn;
3339
3340 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
3341 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3342
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003343 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003344}
3345
3346__LJMP static int hlua_http_req_rep_val(lua_State *L)
3347{
3348 struct hlua_txn *htxn;
3349
3350 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3351 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3352
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003353 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003354}
3355
3356__LJMP static int hlua_http_res_rep_val(lua_State *L)
3357{
3358 struct hlua_txn *htxn;
3359
3360 MAY_LJMP(check_args(L, 4, "res_rep_val"));
3361 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3362
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003363 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003364}
3365
3366/* This function deletes all the occurences of an header.
3367 * It is a wrapper for the 2 following functions.
3368 */
3369__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3370{
3371 size_t len;
3372 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3373 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003374 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003375
3376 ctx.idx = 0;
3377 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
3378 http_remove_header2(msg, &txn->hdr_idx, &ctx);
3379 return 0;
3380}
3381
3382__LJMP static int hlua_http_req_del_hdr(lua_State *L)
3383{
3384 struct hlua_txn *htxn;
3385
3386 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3387 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3388
Willy Tarreaueee5b512015-04-03 23:46:31 +02003389 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003390}
3391
3392__LJMP static int hlua_http_res_del_hdr(lua_State *L)
3393{
3394 struct hlua_txn *htxn;
3395
3396 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3397 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3398
Willy Tarreaueee5b512015-04-03 23:46:31 +02003399 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003400}
3401
3402/* This function adds an header. It is a wrapper used by
3403 * the 2 following functions.
3404 */
3405__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3406{
3407 size_t name_len;
3408 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3409 size_t value_len;
3410 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
3411 char *p;
3412
3413 /* Check length. */
3414 trash.len = value_len + name_len + 2;
3415 if (trash.len > trash.size)
3416 return 0;
3417
3418 /* Creates the header string. */
3419 p = trash.str;
3420 memcpy(p, name, name_len);
3421 p += name_len;
3422 *p = ':';
3423 p++;
3424 *p = ' ';
3425 p++;
3426 memcpy(p, value, value_len);
3427
Willy Tarreaueee5b512015-04-03 23:46:31 +02003428 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003429 trash.str, trash.len) != 0);
3430
3431 return 0;
3432}
3433
3434__LJMP static int hlua_http_req_add_hdr(lua_State *L)
3435{
3436 struct hlua_txn *htxn;
3437
3438 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
3439 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3440
Willy Tarreaueee5b512015-04-03 23:46:31 +02003441 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003442}
3443
3444__LJMP static int hlua_http_res_add_hdr(lua_State *L)
3445{
3446 struct hlua_txn *htxn;
3447
3448 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
3449 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3450
Willy Tarreaueee5b512015-04-03 23:46:31 +02003451 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003452}
3453
3454static int hlua_http_req_set_hdr(lua_State *L)
3455{
3456 struct hlua_txn *htxn;
3457
3458 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
3459 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3460
Willy Tarreaueee5b512015-04-03 23:46:31 +02003461 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
3462 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003463}
3464
3465static int hlua_http_res_set_hdr(lua_State *L)
3466{
3467 struct hlua_txn *htxn;
3468
3469 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
3470 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3471
Willy Tarreaueee5b512015-04-03 23:46:31 +02003472 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
3473 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003474}
3475
3476/* This function set the method. */
3477static int hlua_http_req_set_meth(lua_State *L)
3478{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003479 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003480 size_t name_len;
3481 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003482
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003483 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003484 return 1;
3485}
3486
3487/* This function set the method. */
3488static int hlua_http_req_set_path(lua_State *L)
3489{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003490 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003491 size_t name_len;
3492 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003493 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003494 return 1;
3495}
3496
3497/* This function set the query-string. */
3498static int hlua_http_req_set_query(lua_State *L)
3499{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003500 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003501 size_t name_len;
3502 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003503
3504 /* Check length. */
3505 if (name_len > trash.size - 1) {
3506 lua_pushboolean(L, 0);
3507 return 1;
3508 }
3509
3510 /* Add the mark question as prefix. */
3511 chunk_reset(&trash);
3512 trash.str[trash.len++] = '?';
3513 memcpy(trash.str + trash.len, name, name_len);
3514 trash.len += name_len;
3515
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003516 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003517 return 1;
3518}
3519
3520/* This function set the uri. */
3521static int hlua_http_req_set_uri(lua_State *L)
3522{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003523 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003524 size_t name_len;
3525 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003526
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003527 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003528 return 1;
3529}
3530
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02003531/* This function set the response code. */
3532static int hlua_http_res_set_status(lua_State *L)
3533{
3534 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3535 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
3536
3537 http_set_status(code, htxn->s);
3538 return 0;
3539}
3540
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003541/*
3542 *
3543 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003544 * Class TXN
3545 *
3546 *
3547 */
3548
3549/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003550 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003551 */
3552__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
3553{
3554 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
3555}
3556
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02003557__LJMP static int hlua_set_var(lua_State *L)
3558{
3559 struct hlua_txn *htxn;
3560 const char *name;
3561 size_t len;
3562 struct sample smp;
3563
3564 MAY_LJMP(check_args(L, 3, "set_var"));
3565
3566 /* It is useles to retrieve the stream, but this function
3567 * runs only in a stream context.
3568 */
3569 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3570 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3571
3572 /* Converts the third argument in a sample. */
3573 hlua_lua2smp(L, 3, &smp);
3574
3575 /* Store the sample in a variable. */
3576 vars_set_by_name(name, len, htxn->s, &smp);
3577 return 0;
3578}
3579
3580__LJMP static int hlua_get_var(lua_State *L)
3581{
3582 struct hlua_txn *htxn;
3583 const char *name;
3584 size_t len;
3585 struct sample smp;
3586
3587 MAY_LJMP(check_args(L, 2, "get_var"));
3588
3589 /* It is useles to retrieve the stream, but this function
3590 * runs only in a stream context.
3591 */
3592 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3593 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3594
3595 if (!vars_get_by_name(name, len, htxn->s, &smp)) {
3596 lua_pushnil(L);
3597 return 1;
3598 }
3599
3600 return hlua_smp2lua(L, &smp);
3601}
3602
Willy Tarreau59551662015-03-10 14:23:13 +01003603__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003604{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003605 struct hlua *hlua;
3606
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003607 MAY_LJMP(check_args(L, 2, "set_priv"));
3608
Willy Tarreau87b09662015-04-03 00:22:06 +02003609 /* It is useles to retrieve the stream, but this function
3610 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003611 */
3612 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003613 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003614
3615 /* Remove previous value. */
3616 if (hlua->Mref != -1)
3617 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3618
3619 /* Get and store new value. */
3620 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3621 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3622
3623 return 0;
3624}
3625
Willy Tarreau59551662015-03-10 14:23:13 +01003626__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003627{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003628 struct hlua *hlua;
3629
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003630 MAY_LJMP(check_args(L, 1, "get_priv"));
3631
Willy Tarreau87b09662015-04-03 00:22:06 +02003632 /* It is useles to retrieve the stream, but this function
3633 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003634 */
3635 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003636 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003637
3638 /* Push configuration index in the stack. */
3639 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3640
3641 return 1;
3642}
3643
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003644/* Create stack entry containing a class TXN. This function
3645 * return 0 if the stack does not contains free slots,
3646 * otherwise it returns 1.
3647 */
Willy Tarreau15e91e12015-04-04 00:52:09 +02003648static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003649{
Willy Tarreaude491382015-04-06 11:04:28 +02003650 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003651
3652 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003653 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003654 return 0;
3655
3656 /* NOTE: The allocation never fails. The failure
3657 * throw an error, and the function never returns.
3658 * if the throw is not avalaible, the process is aborted.
3659 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003660 /* Create the object: obj[0] = userdata. */
3661 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02003662 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003663 lua_rawseti(L, -2, 0);
3664
Willy Tarreaude491382015-04-06 11:04:28 +02003665 htxn->s = s;
3666 htxn->p = p;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003667
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003668 /* Create the "f" field that contains a list of fetches. */
3669 lua_pushstring(L, "f");
Willy Tarreaude491382015-04-06 11:04:28 +02003670 if (!hlua_fetches_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003671 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02003672 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003673
3674 /* Create the "sf" field that contains a list of stringsafe fetches. */
3675 lua_pushstring(L, "sf");
Willy Tarreaude491382015-04-06 11:04:28 +02003676 if (!hlua_fetches_new(L, htxn, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003677 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02003678 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003679
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003680 /* Create the "c" field that contains a list of converters. */
3681 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02003682 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003683 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02003684 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003685
3686 /* Create the "sc" field that contains a list of stringsafe converters. */
3687 lua_pushstring(L, "sc");
Willy Tarreaude491382015-04-06 11:04:28 +02003688 if (!hlua_converters_new(L, htxn, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003689 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02003690 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003691
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003692 /* Create the "req" field that contains the request channel object. */
3693 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003694 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003695 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02003696 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003697
3698 /* Create the "res" field that contains the response channel object. */
3699 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003700 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003701 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02003702 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003703
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003704 /* Creates the HTTP object is the current proxy allows http. */
3705 lua_pushstring(L, "http");
3706 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02003707 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003708 return 0;
3709 }
3710 else
3711 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02003712 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003713
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003714 /* Pop a class sesison metatable and affect it to the userdata. */
3715 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
3716 lua_setmetatable(L, -2);
3717
3718 return 1;
3719}
3720
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003721__LJMP static int hlua_txn_deflog(lua_State *L)
3722{
3723 const char *msg;
3724 struct hlua_txn *htxn;
3725
3726 MAY_LJMP(check_args(L, 2, "deflog"));
3727 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3728 msg = MAY_LJMP(luaL_checkstring(L, 2));
3729
3730 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
3731 return 0;
3732}
3733
3734__LJMP static int hlua_txn_log(lua_State *L)
3735{
3736 int level;
3737 const char *msg;
3738 struct hlua_txn *htxn;
3739
3740 MAY_LJMP(check_args(L, 3, "log"));
3741 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3742 level = MAY_LJMP(luaL_checkinteger(L, 2));
3743 msg = MAY_LJMP(luaL_checkstring(L, 3));
3744
3745 if (level < 0 || level >= NB_LOG_LEVELS)
3746 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3747
3748 hlua_sendlog(htxn->s->be, level, msg);
3749 return 0;
3750}
3751
3752__LJMP static int hlua_txn_log_debug(lua_State *L)
3753{
3754 const char *msg;
3755 struct hlua_txn *htxn;
3756
3757 MAY_LJMP(check_args(L, 2, "Debug"));
3758 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3759 msg = MAY_LJMP(luaL_checkstring(L, 2));
3760 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
3761 return 0;
3762}
3763
3764__LJMP static int hlua_txn_log_info(lua_State *L)
3765{
3766 const char *msg;
3767 struct hlua_txn *htxn;
3768
3769 MAY_LJMP(check_args(L, 2, "Info"));
3770 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3771 msg = MAY_LJMP(luaL_checkstring(L, 2));
3772 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
3773 return 0;
3774}
3775
3776__LJMP static int hlua_txn_log_warning(lua_State *L)
3777{
3778 const char *msg;
3779 struct hlua_txn *htxn;
3780
3781 MAY_LJMP(check_args(L, 2, "Warning"));
3782 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3783 msg = MAY_LJMP(luaL_checkstring(L, 2));
3784 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
3785 return 0;
3786}
3787
3788__LJMP static int hlua_txn_log_alert(lua_State *L)
3789{
3790 const char *msg;
3791 struct hlua_txn *htxn;
3792
3793 MAY_LJMP(check_args(L, 2, "Alert"));
3794 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3795 msg = MAY_LJMP(luaL_checkstring(L, 2));
3796 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
3797 return 0;
3798}
3799
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003800__LJMP static int hlua_txn_set_loglevel(lua_State *L)
3801{
3802 struct hlua_txn *htxn;
3803 int ll;
3804
3805 MAY_LJMP(check_args(L, 2, "set_loglevel"));
3806 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3807 ll = MAY_LJMP(luaL_checkinteger(L, 2));
3808
3809 if (ll < 0 || ll > 7)
3810 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
3811
3812 htxn->s->logs.level = ll;
3813 return 0;
3814}
3815
3816__LJMP static int hlua_txn_set_tos(lua_State *L)
3817{
3818 struct hlua_txn *htxn;
3819 struct connection *cli_conn;
3820 int tos;
3821
3822 MAY_LJMP(check_args(L, 2, "set_tos"));
3823 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3824 tos = MAY_LJMP(luaL_checkinteger(L, 2));
3825
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003826 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003827 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
3828
3829 return 0;
3830}
3831
3832__LJMP static int hlua_txn_set_mark(lua_State *L)
3833{
3834#ifdef SO_MARK
3835 struct hlua_txn *htxn;
3836 struct connection *cli_conn;
3837 int mark;
3838
3839 MAY_LJMP(check_args(L, 2, "set_mark"));
3840 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3841 mark = MAY_LJMP(luaL_checkinteger(L, 2));
3842
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003843 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02003844 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003845#endif
3846 return 0;
3847}
3848
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003849/* This function is an Lua binding that send pending data
3850 * to the client, and close the stream interface.
3851 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02003852__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003853{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003854 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01003855 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003856
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003857 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003858 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003859
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003860 ic = &htxn->s->req;
3861 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01003862
Willy Tarreau630ef452015-08-28 10:06:15 +02003863 if (htxn->s->txn) {
3864 /* HTTP mode, let's stay in sync with the stream */
3865 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
3866 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
3867 htxn->s->txn->req.sov = 0;
3868 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
3869 oc->analysers = AN_RES_HTTP_XFER_BODY;
3870 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
3871 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
3872
3873 /* Trim any possible response */
3874 oc->buf->i = 0;
3875 htxn->s->txn->rsp.next = htxn->s->txn->rsp.sov = 0;
3876
3877 /* Note that if we want to support keep-alive, we need
3878 * to bypass the close/shutr_now calls below, but that
3879 * may only be done if the HTTP request was already
3880 * processed and the connection header is known (ie
3881 * not during TCP rules).
3882 */
3883 }
3884
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02003885 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01003886 channel_abort(ic);
3887 channel_auto_close(ic);
3888 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02003889
3890 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01003891 channel_auto_read(oc);
3892 channel_auto_close(oc);
3893 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003894
Willy Tarreau0458b082015-08-28 09:40:04 +02003895 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02003896
3897 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003898 return 0;
3899}
3900
3901__LJMP static int hlua_log(lua_State *L)
3902{
3903 int level;
3904 const char *msg;
3905
3906 MAY_LJMP(check_args(L, 2, "log"));
3907 level = MAY_LJMP(luaL_checkinteger(L, 1));
3908 msg = MAY_LJMP(luaL_checkstring(L, 2));
3909
3910 if (level < 0 || level >= NB_LOG_LEVELS)
3911 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3912
3913 hlua_sendlog(NULL, level, msg);
3914 return 0;
3915}
3916
3917__LJMP static int hlua_log_debug(lua_State *L)
3918{
3919 const char *msg;
3920
3921 MAY_LJMP(check_args(L, 1, "debug"));
3922 msg = MAY_LJMP(luaL_checkstring(L, 1));
3923 hlua_sendlog(NULL, LOG_DEBUG, msg);
3924 return 0;
3925}
3926
3927__LJMP static int hlua_log_info(lua_State *L)
3928{
3929 const char *msg;
3930
3931 MAY_LJMP(check_args(L, 1, "info"));
3932 msg = MAY_LJMP(luaL_checkstring(L, 1));
3933 hlua_sendlog(NULL, LOG_INFO, msg);
3934 return 0;
3935}
3936
3937__LJMP static int hlua_log_warning(lua_State *L)
3938{
3939 const char *msg;
3940
3941 MAY_LJMP(check_args(L, 1, "warning"));
3942 msg = MAY_LJMP(luaL_checkstring(L, 1));
3943 hlua_sendlog(NULL, LOG_WARNING, msg);
3944 return 0;
3945}
3946
3947__LJMP static int hlua_log_alert(lua_State *L)
3948{
3949 const char *msg;
3950
3951 MAY_LJMP(check_args(L, 1, "alert"));
3952 msg = MAY_LJMP(luaL_checkstring(L, 1));
3953 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003954 return 0;
3955}
3956
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003957__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003958{
3959 int wakeup_ms = lua_tointeger(L, -1);
3960 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003961 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003962 return 0;
3963}
3964
3965__LJMP static int hlua_sleep(lua_State *L)
3966{
3967 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003968 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003969
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003970 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003971
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003972 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003973 wakeup_ms = tick_add(now_ms, delay);
3974 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003975
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003976 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3977 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003978}
3979
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003980__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003981{
3982 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003983 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003984
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003985 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003986
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003987 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003988 wakeup_ms = tick_add(now_ms, delay);
3989 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003990
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003991 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3992 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003993}
3994
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003995/* This functionis an LUA binding. it permits to give back
3996 * the hand at the HAProxy scheduler. It is used when the
3997 * LUA processing consumes a lot of time.
3998 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003999__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004000{
4001 return 0;
4002}
4003
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004004__LJMP static int hlua_yield(lua_State *L)
4005{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004006 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
4007 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004008}
4009
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004010/* This function change the nice of the currently executed
4011 * task. It is used set low or high priority at the current
4012 * task.
4013 */
Willy Tarreau59551662015-03-10 14:23:13 +01004014__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004015{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004016 struct hlua *hlua;
4017 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004018
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004019 MAY_LJMP(check_args(L, 1, "set_nice"));
4020 hlua = hlua_gethlua(L);
4021 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004022
4023 /* If he task is not set, I'm in a start mode. */
4024 if (!hlua || !hlua->task)
4025 return 0;
4026
4027 if (nice < -1024)
4028 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004029 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004030 nice = 1024;
4031
4032 hlua->task->nice = nice;
4033 return 0;
4034}
4035
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004036/* This function is used as a calback of a task. It is called by the
4037 * HAProxy task subsystem when the task is awaked. The LUA runtime can
4038 * return an E_AGAIN signal, the emmiter of this signal must set a
4039 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004040 *
4041 * Task wrapper are longjmp safe because the only one Lua code
4042 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004043 */
4044static struct task *hlua_process_task(struct task *task)
4045{
4046 struct hlua *hlua = task->context;
4047 enum hlua_exec status;
4048
4049 /* We need to remove the task from the wait queue before executing
4050 * the Lua code because we don't know if it needs to wait for
4051 * another timer or not in the case of E_AGAIN.
4052 */
4053 task_delete(task);
4054
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004055 /* If it is the first call to the task, we must initialize the
4056 * execution timeouts.
4057 */
4058 if (!HLUA_IS_RUNNING(hlua))
Camilo Lopez685c0142015-08-02 19:07:28 -04004059 hlua->expire = tick_add_ifset(now_ms, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004060
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004061 /* Execute the Lua code. */
4062 status = hlua_ctx_resume(hlua, 1);
4063
4064 switch (status) {
4065 /* finished or yield */
4066 case HLUA_E_OK:
4067 hlua_ctx_destroy(hlua);
4068 task_delete(task);
4069 task_free(task);
4070 break;
4071
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004072 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
4073 if (hlua->wake_time != TICK_ETERNITY)
4074 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004075 break;
4076
4077 /* finished with error. */
4078 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004079 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004080 hlua_ctx_destroy(hlua);
4081 task_delete(task);
4082 task_free(task);
4083 break;
4084
4085 case HLUA_E_ERR:
4086 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004087 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004088 hlua_ctx_destroy(hlua);
4089 task_delete(task);
4090 task_free(task);
4091 break;
4092 }
4093 return NULL;
4094}
4095
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004096/* This function is an LUA binding that register LUA function to be
4097 * executed after the HAProxy configuration parsing and before the
4098 * HAProxy scheduler starts. This function expect only one LUA
4099 * argument that is a function. This function returns nothing, but
4100 * throws if an error is encountered.
4101 */
4102__LJMP static int hlua_register_init(lua_State *L)
4103{
4104 struct hlua_init_function *init;
4105 int ref;
4106
4107 MAY_LJMP(check_args(L, 1, "register_init"));
4108
4109 ref = MAY_LJMP(hlua_checkfunction(L, 1));
4110
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02004111 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004112 if (!init)
4113 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4114
4115 init->function_ref = ref;
4116 LIST_ADDQ(&hlua_init_functions, &init->l);
4117 return 0;
4118}
4119
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004120/* This functio is an LUA binding. It permits to register a task
4121 * executed in parallel of the main HAroxy activity. The task is
4122 * created and it is set in the HAProxy scheduler. It can be called
4123 * from the "init" section, "post init" or during the runtime.
4124 *
4125 * Lua prototype:
4126 *
4127 * <none> core.register_task(<function>)
4128 */
4129static int hlua_register_task(lua_State *L)
4130{
4131 struct hlua *hlua;
4132 struct task *task;
4133 int ref;
4134
4135 MAY_LJMP(check_args(L, 1, "register_task"));
4136
4137 ref = MAY_LJMP(hlua_checkfunction(L, 1));
4138
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02004139 hlua = calloc(1, sizeof(*hlua));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004140 if (!hlua)
4141 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4142
4143 task = task_new();
4144 task->context = hlua;
4145 task->process = hlua_process_task;
4146
4147 if (!hlua_ctx_init(hlua, task))
4148 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4149
4150 /* Restore the function in the stack. */
4151 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
4152 hlua->nargs = 0;
4153
4154 /* Schedule task. */
4155 task_schedule(task, now_ms);
4156
4157 return 0;
4158}
4159
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004160/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
4161 * doesn't allow "yield" functions because the HAProxy engine cannot
4162 * resume converters.
4163 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004164static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004165{
4166 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004167 struct stream *stream = smp->strm;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004168
Willy Tarreau87b09662015-04-03 00:22:06 +02004169 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004170 * Lua context can be not initialized. This behavior
4171 * permits to save performances because a systematic
4172 * Lua initialization cause 5% performances loss.
4173 */
Willy Tarreau87b09662015-04-03 00:22:06 +02004174 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004175 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004176 return 0;
4177 }
4178
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004179 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004180 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004181
4182 /* The following Lua calls can fail. */
4183 if (!SET_SAFE_LJMP(stream->hlua.T)) {
4184 SEND_ERR(stream->be, "Lua converter '%s': critical error.\n", fcn->name);
4185 return 0;
4186 }
4187
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004188 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004189 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004190 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02004191 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004192 return 0;
4193 }
4194
4195 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004196 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004197
4198 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004199 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004200 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02004201 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004202 return 0;
4203 }
Willy Tarreau87b09662015-04-03 00:22:06 +02004204 hlua_smp2lua(stream->hlua.T, smp);
4205 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004206
4207 /* push keywords in the stack. */
4208 if (arg_p) {
4209 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02004210 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004211 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02004212 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004213 return 0;
4214 }
Willy Tarreau87b09662015-04-03 00:22:06 +02004215 hlua_arg2lua(stream->hlua.T, arg_p);
4216 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004217 }
4218 }
4219
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004220 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004221 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004222
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004223 /* At this point the execution is safe. */
4224 RESET_SAFE_LJMP(stream->hlua.T);
4225
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004226 /* Set the currently running flag. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004227 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004228 }
4229
4230 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004231 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004232 /* finished. */
4233 case HLUA_E_OK:
4234 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004235 hlua_lua2smp(stream->hlua.T, -1, smp);
4236 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004237 return 1;
4238
4239 /* yield. */
4240 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004241 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004242 return 0;
4243
4244 /* finished with error. */
4245 case HLUA_E_ERRMSG:
4246 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004247 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
4248 fcn->name, lua_tostring(stream->hlua.T, -1));
Willy Tarreau87b09662015-04-03 00:22:06 +02004249 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004250 return 0;
4251
4252 case HLUA_E_ERR:
4253 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004254 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004255
4256 default:
4257 return 0;
4258 }
4259}
4260
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004261/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
4262 * doesn't allow "yield" functions because the HAProxy engine cannot
4263 * resume sample-fetches.
4264 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004265static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
4266 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004267{
4268 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004269 struct stream *stream = smp->strm;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004270
Willy Tarreau87b09662015-04-03 00:22:06 +02004271 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004272 * Lua context can be not initialized. This behavior
4273 * permits to save performances because a systematic
4274 * Lua initialization cause 5% performances loss.
4275 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004276 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004277 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004278 return 0;
4279 }
4280
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004281 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004282 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004283
4284 /* The following Lua calls can fail. */
4285 if (!SET_SAFE_LJMP(stream->hlua.T)) {
4286 SEND_ERR(smp->px, "Lua sample-fetch '%s': critical error.\n", fcn->name);
4287 return 0;
4288 }
4289
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004290 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004291 if (!lua_checkstack(stream->hlua.T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004292 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02004293 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004294 return 0;
4295 }
4296
4297 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004298 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004299
4300 /* push arguments in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004301 if (!hlua_txn_new(stream->hlua.T, stream, smp->px)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004302 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02004303 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004304 return 0;
4305 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004306 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004307
4308 /* push keywords in the stack. */
4309 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
4310 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004311 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004312 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02004313 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004314 return 0;
4315 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004316 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004317 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02004318 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004319 return 0;
4320 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004321 hlua_arg2lua(stream->hlua.T, arg_p);
4322 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004323 }
4324
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004325 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004326 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004327
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004328 /* At this point the execution is safe. */
4329 RESET_SAFE_LJMP(stream->hlua.T);
4330
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004331 /* Set the currently running flag. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004332 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004333 }
4334
4335 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004336 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004337 /* finished. */
4338 case HLUA_E_OK:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02004339 if (!hlua_check_proto(stream, !(smp->opt & SMP_OPT_DIR_REQ)))
4340 return 0;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004341 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004342 hlua_lua2smp(stream->hlua.T, -1, smp);
4343 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004344
4345 /* Set the end of execution flag. */
4346 smp->flags &= ~SMP_F_MAY_CHANGE;
4347 return 1;
4348
4349 /* yield. */
4350 case HLUA_E_AGAIN:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02004351 hlua_check_proto(stream, !(smp->opt & SMP_OPT_DIR_REQ));
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004352 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004353 return 0;
4354
4355 /* finished with error. */
4356 case HLUA_E_ERRMSG:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02004357 hlua_check_proto(stream, !(smp->opt & SMP_OPT_DIR_REQ));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004358 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004359 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
4360 fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004361 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004362 return 0;
4363
4364 case HLUA_E_ERR:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02004365 hlua_check_proto(stream, !(smp->opt & SMP_OPT_DIR_REQ));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004366 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004367 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004368
4369 default:
4370 return 0;
4371 }
4372}
4373
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004374/* This function is an LUA binding used for registering
4375 * "sample-conv" functions. It expects a converter name used
4376 * in the haproxy configuration file, and an LUA function.
4377 */
4378__LJMP static int hlua_register_converters(lua_State *L)
4379{
4380 struct sample_conv_kw_list *sck;
4381 const char *name;
4382 int ref;
4383 int len;
4384 struct hlua_function *fcn;
4385
4386 MAY_LJMP(check_args(L, 2, "register_converters"));
4387
4388 /* First argument : converter name. */
4389 name = MAY_LJMP(luaL_checkstring(L, 1));
4390
4391 /* Second argument : lua function. */
4392 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4393
4394 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02004395 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004396 if (!sck)
4397 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02004398 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004399 if (!fcn)
4400 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4401
4402 /* Fill fcn. */
4403 fcn->name = strdup(name);
4404 if (!fcn->name)
4405 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4406 fcn->function_ref = ref;
4407
4408 /* List head */
4409 sck->list.n = sck->list.p = NULL;
4410
4411 /* converter keyword. */
4412 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02004413 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004414 if (!sck->kw[0].kw)
4415 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4416
4417 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
4418 sck->kw[0].process = hlua_sample_conv_wrapper;
4419 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4420 sck->kw[0].val_args = NULL;
4421 sck->kw[0].in_type = SMP_T_STR;
4422 sck->kw[0].out_type = SMP_T_STR;
4423 sck->kw[0].private = fcn;
4424
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004425 /* Register this new converter */
4426 sample_register_convs(sck);
4427
4428 return 0;
4429}
4430
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004431/* This fucntion is an LUA binding used for registering
4432 * "sample-fetch" functions. It expects a converter name used
4433 * in the haproxy configuration file, and an LUA function.
4434 */
4435__LJMP static int hlua_register_fetches(lua_State *L)
4436{
4437 const char *name;
4438 int ref;
4439 int len;
4440 struct sample_fetch_kw_list *sfk;
4441 struct hlua_function *fcn;
4442
4443 MAY_LJMP(check_args(L, 2, "register_fetches"));
4444
4445 /* First argument : sample-fetch name. */
4446 name = MAY_LJMP(luaL_checkstring(L, 1));
4447
4448 /* Second argument : lua function. */
4449 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4450
4451 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02004452 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004453 if (!sfk)
4454 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02004455 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004456 if (!fcn)
4457 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4458
4459 /* Fill fcn. */
4460 fcn->name = strdup(name);
4461 if (!fcn->name)
4462 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4463 fcn->function_ref = ref;
4464
4465 /* List head */
4466 sfk->list.n = sfk->list.p = NULL;
4467
4468 /* sample-fetch keyword. */
4469 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02004470 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004471 if (!sfk->kw[0].kw)
4472 return luaL_error(L, "lua out of memory error.");
4473
4474 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
4475 sfk->kw[0].process = hlua_sample_fetch_wrapper;
4476 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4477 sfk->kw[0].val_args = NULL;
4478 sfk->kw[0].out_type = SMP_T_STR;
4479 sfk->kw[0].use = SMP_USE_HTTP_ANY;
4480 sfk->kw[0].val = 0;
4481 sfk->kw[0].private = fcn;
4482
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004483 /* Register this new fetch. */
4484 sample_register_fetches(sfk);
4485
4486 return 0;
4487}
4488
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004489/* This function is a wrapper to execute each LUA function declared
4490 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004491 * return ACT_RET_CONT if the processing is finished (with or without
4492 * error) and return ACT_RET_YIELD if the function must be called again
4493 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004494 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004495static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02004496 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004497{
4498 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004499 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02004500 int dir;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004501
4502 switch (rule->from) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02004503 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = 0; break;
4504 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = 1; break;
4505 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = 0; break;
4506 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = 1; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004507 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004508 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004509 return ACT_RET_CONT;
4510 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004511
Willy Tarreau87b09662015-04-03 00:22:06 +02004512 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004513 * Lua context can be not initialized. This behavior
4514 * permits to save performances because a systematic
4515 * Lua initialization cause 5% performances loss.
4516 */
4517 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004518 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004519 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004520 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004521 }
4522
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004523 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004524 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004525
4526 /* The following Lua calls can fail. */
4527 if (!SET_SAFE_LJMP(s->hlua.T)) {
4528 SEND_ERR(px, "Lua function '%s': critical error.\n",
4529 rule->arg.hlua_rule->fcn.name);
4530 return ACT_RET_CONT;
4531 }
4532
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004533 /* Check stack available size. */
4534 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004535 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004536 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02004537 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004538 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004539 }
4540
4541 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004542 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004543
Willy Tarreau87b09662015-04-03 00:22:06 +02004544 /* Create and and push object stream in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02004545 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004546 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004547 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02004548 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004549 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004550 }
4551 s->hlua.nargs = 1;
4552
4553 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004554 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004555 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004556 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004557 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02004558 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004559 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004560 }
4561 lua_pushstring(s->hlua.T, *arg);
4562 s->hlua.nargs++;
4563 }
4564
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004565 /* Now the execution is safe. */
4566 RESET_SAFE_LJMP(s->hlua.T);
4567
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004568 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004569 s->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004570
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004571 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004572 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004573 }
4574
4575 /* Execute the function. */
Willy Tarreau528192d2015-09-27 10:48:01 +02004576 switch (hlua_ctx_resume(&s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004577 /* finished. */
4578 case HLUA_E_OK:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02004579 if (!hlua_check_proto(s, dir))
4580 return ACT_RET_ERR;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004581 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004582
4583 /* yield. */
4584 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004585 /* Set timeout in the required channel. */
4586 if (s->hlua.wake_time != TICK_ETERNITY) {
4587 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004588 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004589 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004590 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004591 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004592 /* Some actions can be wake up when a "write" event
4593 * is detected on a response channel. This is useful
4594 * only for actions targetted on the requests.
4595 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004596 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004597 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01004598 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004599 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004600 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004601 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004602 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004603 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004604
4605 /* finished with error. */
4606 case HLUA_E_ERRMSG:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02004607 if (!hlua_check_proto(s, dir))
4608 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004609 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004610 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004611 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004612 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004613 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004614
4615 case HLUA_E_ERR:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02004616 if (!hlua_check_proto(s, dir))
4617 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004618 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004619 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004620 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004621
4622 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004623 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004624 }
4625}
4626
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004627/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
4628 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004629 *
4630 * This function can fail with an abort() due to an Lua critical error.
4631 * We are in the configuration parsing process of HAProxy, this abort() is
4632 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004633 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004634static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4635 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004636{
Thierry FOURNIER8255a752015-09-23 21:03:35 +02004637 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
4638
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004639 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02004640 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004641 if (!rule->arg.hlua_rule) {
4642 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004643 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004644 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004645
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004646 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02004647 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004648
4649 /* TODO: later accept arguments. */
4650 rule->arg.hlua_rule->args = NULL;
4651
Thierry FOURNIER42148732015-09-02 17:17:33 +02004652 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004653 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004654 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004655}
4656
Thierry FOURNIER8255a752015-09-23 21:03:35 +02004657/* This function is an LUA binding used for registering
4658 * "sample-conv" functions. It expects a converter name used
4659 * in the haproxy configuration file, and an LUA function.
4660 */
4661__LJMP static int hlua_register_action(lua_State *L)
4662{
4663 struct action_kw_list *akl;
4664 const char *name;
4665 int ref;
4666 int len;
4667 struct hlua_function *fcn;
4668
4669 MAY_LJMP(check_args(L, 3, "register_service"));
4670
4671 /* First argument : converter name. */
4672 name = MAY_LJMP(luaL_checkstring(L, 1));
4673
4674 /* Second argument : environment. */
4675 if (lua_type(L, 2) != LUA_TTABLE)
4676 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
4677
4678 /* Third argument : lua function. */
4679 ref = MAY_LJMP(hlua_checkfunction(L, 3));
4680
4681 /* browse the second argulent as an array. */
4682 lua_pushnil(L);
4683 while (lua_next(L, 2) != 0) {
4684 if (lua_type(L, -1) != LUA_TSTRING)
4685 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
4686
4687 /* Check required environment. Only accepted "http" or "tcp". */
4688 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02004689 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02004690 if (!akl)
4691 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02004692 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02004693 if (!fcn)
4694 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4695
4696 /* Fill fcn. */
4697 fcn->name = strdup(name);
4698 if (!fcn->name)
4699 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4700 fcn->function_ref = ref;
4701
4702 /* List head */
4703 akl->list.n = akl->list.p = NULL;
4704
Thierry FOURNIER8255a752015-09-23 21:03:35 +02004705 /* action keyword. */
4706 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02004707 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02004708 if (!akl->kw[0].kw)
4709 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4710
4711 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
4712
4713 akl->kw[0].match_pfx = 0;
4714 akl->kw[0].private = fcn;
4715 akl->kw[0].parse = action_register_lua;
4716
4717 /* select the action registering point. */
4718 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
4719 tcp_req_cont_keywords_register(akl);
4720 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
4721 tcp_res_cont_keywords_register(akl);
4722 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
4723 http_req_keywords_register(akl);
4724 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
4725 http_res_keywords_register(akl);
4726 else
4727 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
4728 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
4729 "are expected.", lua_tostring(L, -1)));
4730
4731 /* pop the environment string. */
4732 lua_pop(L, 1);
4733 }
4734
4735 return 0;
4736}
4737
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004738static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
4739 struct proxy *defpx, const char *file, int line,
4740 char **err, unsigned int *timeout)
4741{
4742 const char *error;
4743
4744 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
4745 if (error && *error != '\0') {
4746 memprintf(err, "%s: invalid timeout", args[0]);
4747 return -1;
4748 }
4749 return 0;
4750}
4751
4752static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
4753 struct proxy *defpx, const char *file, int line,
4754 char **err)
4755{
4756 return hlua_read_timeout(args, section_type, curpx, defpx,
4757 file, line, err, &hlua_timeout_session);
4758}
4759
4760static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
4761 struct proxy *defpx, const char *file, int line,
4762 char **err)
4763{
4764 return hlua_read_timeout(args, section_type, curpx, defpx,
4765 file, line, err, &hlua_timeout_task);
4766}
4767
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004768static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
4769 struct proxy *defpx, const char *file, int line,
4770 char **err)
4771{
4772 char *error;
4773
4774 hlua_nb_instruction = strtoll(args[1], &error, 10);
4775 if (*error != '\0') {
4776 memprintf(err, "%s: invalid number", args[0]);
4777 return -1;
4778 }
4779 return 0;
4780}
4781
Willy Tarreau32f61e22015-03-18 17:54:59 +01004782static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
4783 struct proxy *defpx, const char *file, int line,
4784 char **err)
4785{
4786 char *error;
4787
4788 if (*(args[1]) == 0) {
4789 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
4790 return -1;
4791 }
4792 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
4793 if (*error != '\0') {
4794 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
4795 return -1;
4796 }
4797 return 0;
4798}
4799
4800
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004801/* This function is called by the main configuration key "lua-load". It loads and
4802 * execute an lua file during the parsing of the HAProxy configuration file. It is
4803 * the main lua entry point.
4804 *
4805 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
4806 * occured, otherwise it returns 0.
4807 *
4808 * In some error case, LUA set an error message in top of the stack. This function
4809 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004810 *
4811 * This function can fail with an abort() due to an Lua critical error.
4812 * We are in the configuration parsing process of HAProxy, this abort() is
4813 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004814 */
4815static int hlua_load(char **args, int section_type, struct proxy *curpx,
4816 struct proxy *defpx, const char *file, int line,
4817 char **err)
4818{
4819 int error;
4820
4821 /* Just load and compile the file. */
4822 error = luaL_loadfile(gL.T, args[1]);
4823 if (error) {
4824 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
4825 lua_pop(gL.T, 1);
4826 return -1;
4827 }
4828
4829 /* If no syntax error where detected, execute the code. */
4830 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
4831 switch (error) {
4832 case LUA_OK:
4833 break;
4834 case LUA_ERRRUN:
4835 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
4836 lua_pop(gL.T, 1);
4837 return -1;
4838 case LUA_ERRMEM:
4839 memprintf(err, "lua out of memory error\n");
4840 return -1;
4841 case LUA_ERRERR:
4842 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
4843 lua_pop(gL.T, 1);
4844 return -1;
4845 case LUA_ERRGCMM:
4846 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
4847 lua_pop(gL.T, 1);
4848 return -1;
4849 default:
4850 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
4851 lua_pop(gL.T, 1);
4852 return -1;
4853 }
4854
4855 return 0;
4856}
4857
4858/* configuration keywords declaration */
4859static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004860 { CFG_GLOBAL, "lua-load", hlua_load },
4861 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
4862 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004863 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01004864 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004865 { 0, NULL, NULL },
4866}};
4867
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004868/* This function can fail with an abort() due to an Lua critical error.
4869 * We are in the initialisation process of HAProxy, this abort() is
4870 * tolerated.
4871 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004872int hlua_post_init()
4873{
4874 struct hlua_init_function *init;
4875 const char *msg;
4876 enum hlua_exec ret;
4877
4878 list_for_each_entry(init, &hlua_init_functions, l) {
4879 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
4880 ret = hlua_ctx_resume(&gL, 0);
4881 switch (ret) {
4882 case HLUA_E_OK:
4883 lua_pop(gL.T, -1);
4884 return 1;
4885 case HLUA_E_AGAIN:
4886 Alert("lua init: yield not allowed.\n");
4887 return 0;
4888 case HLUA_E_ERRMSG:
4889 msg = lua_tostring(gL.T, -1);
4890 Alert("lua init: %s.\n", msg);
4891 return 0;
4892 case HLUA_E_ERR:
4893 default:
4894 Alert("lua init: unknown runtime error.\n");
4895 return 0;
4896 }
4897 }
4898 return 1;
4899}
4900
Willy Tarreau32f61e22015-03-18 17:54:59 +01004901/* The memory allocator used by the Lua stack. <ud> is a pointer to the
4902 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
4903 * is the previously allocated size or the kind of object in case of a new
4904 * allocation. <nsize> is the requested new size.
4905 */
4906static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
4907{
4908 struct hlua_mem_allocator *zone = ud;
4909
4910 if (nsize == 0) {
4911 /* it's a free */
4912 if (ptr)
4913 zone->allocated -= osize;
4914 free(ptr);
4915 return NULL;
4916 }
4917
4918 if (!ptr) {
4919 /* it's a new allocation */
4920 if (zone->limit && zone->allocated + nsize > zone->limit)
4921 return NULL;
4922
4923 ptr = malloc(nsize);
4924 if (ptr)
4925 zone->allocated += nsize;
4926 return ptr;
4927 }
4928
4929 /* it's a realloc */
4930 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
4931 return NULL;
4932
4933 ptr = realloc(ptr, nsize);
4934 if (ptr)
4935 zone->allocated += nsize - osize;
4936 return ptr;
4937}
4938
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004939/* Ithis function can fail with an abort() due to an Lua critical error.
4940 * We are in the initialisation process of HAProxy, this abort() is
4941 * tolerated.
4942 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004943void hlua_init(void)
4944{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004945 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004946 int idx;
4947 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004948 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004949 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004950#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004951 struct srv_kw *kw;
4952 int tmp_error;
4953 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01004954 char *args[] = { /* SSL client configuration. */
4955 "ssl",
4956 "verify",
4957 "none",
4958 "force-sslv3",
4959 NULL
4960 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004961#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004962
Willy Tarreau87b09662015-04-03 00:22:06 +02004963 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004964 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
4965
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004966 /* Register configuration keywords. */
4967 cfg_register_keywords(&cfg_kws);
4968
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004969 /* Init main lua stack. */
4970 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004971 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004972 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004973 gL.T = luaL_newstate();
4974 hlua_sethlua(&gL);
4975 gL.Tref = LUA_REFNIL;
4976 gL.task = NULL;
4977
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004978 /* From this point, until the end of the initialisation fucntion,
4979 * the Lua function can fail with an abort. We are in the initialisation
4980 * process of HAProxy, this abort() is tolerated.
4981 */
4982
Willy Tarreau32f61e22015-03-18 17:54:59 +01004983 /* change the memory allocators to track memory usage */
4984 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
4985
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004986 /* Initialise lua. */
4987 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004988
4989 /*
4990 *
4991 * Create "core" object.
4992 *
4993 */
4994
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01004995 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004996 lua_newtable(gL.T);
4997
4998 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004999 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01005000 hlua_class_const_int(gL.T, log_levels[i], i);
5001
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005002 /* Register special functions. */
5003 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005004 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005005 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005006 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02005007 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005008 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01005009 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005010 hlua_class_function(gL.T, "sleep", hlua_sleep);
5011 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01005012 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
5013 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
5014 hlua_class_function(gL.T, "set_map", hlua_set_map);
5015 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005016 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005017 hlua_class_function(gL.T, "log", hlua_log);
5018 hlua_class_function(gL.T, "Debug", hlua_log_debug);
5019 hlua_class_function(gL.T, "Info", hlua_log_info);
5020 hlua_class_function(gL.T, "Warning", hlua_log_warning);
5021 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02005022 hlua_class_function(gL.T, "done", hlua_done);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005023
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01005024 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005025
5026 /*
5027 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02005028 * Register class Map
5029 *
5030 */
5031
5032 /* This table entry is the object "Map" base. */
5033 lua_newtable(gL.T);
5034
5035 /* register pattern types. */
5036 for (i=0; i<PAT_MATCH_NUM; i++)
5037 hlua_class_const_int(gL.T, pat_match_names[i], i);
5038
5039 /* register constructor. */
5040 hlua_class_function(gL.T, "new", hlua_map_new);
5041
5042 /* Create and fill the metatable. */
5043 lua_newtable(gL.T);
5044
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02005045 /* Create the __tostring identifier */
5046 lua_pushstring(gL.T, "__tostring");
5047 lua_pushstring(gL.T, CLASS_MAP);
5048 lua_pushcclosure(gL.T, hlua_dump_object, 1);
5049 lua_rawset(gL.T, -3);
5050
Thierry FOURNIER3def3932015-04-07 11:27:54 +02005051 /* Create and fille the __index entry. */
5052 lua_pushstring(gL.T, "__index");
5053 lua_newtable(gL.T);
5054
5055 /* Register . */
5056 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
5057 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
5058
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005059 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02005060
5061 /* Register previous table in the registry with reference and named entry. */
5062 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5063 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5064 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
5065 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
5066
5067 /* Assign the metatable to the mai Map object. */
5068 lua_setmetatable(gL.T, -2);
5069
5070 /* Set a name to the table. */
5071 lua_setglobal(gL.T, "Map");
5072
5073 /*
5074 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01005075 * Register class Channel
5076 *
5077 */
5078
5079 /* Create and fill the metatable. */
5080 lua_newtable(gL.T);
5081
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02005082 /* Create the __tostring identifier */
5083 lua_pushstring(gL.T, "__tostring");
5084 lua_pushstring(gL.T, CLASS_CHANNEL);
5085 lua_pushcclosure(gL.T, hlua_dump_object, 1);
5086 lua_rawset(gL.T, -3);
5087
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01005088 /* Create and fille the __index entry. */
5089 lua_pushstring(gL.T, "__index");
5090 lua_newtable(gL.T);
5091
5092 /* Register . */
5093 hlua_class_function(gL.T, "get", hlua_channel_get);
5094 hlua_class_function(gL.T, "dup", hlua_channel_dup);
5095 hlua_class_function(gL.T, "getline", hlua_channel_getline);
5096 hlua_class_function(gL.T, "set", hlua_channel_set);
5097 hlua_class_function(gL.T, "append", hlua_channel_append);
5098 hlua_class_function(gL.T, "send", hlua_channel_send);
5099 hlua_class_function(gL.T, "forward", hlua_channel_forward);
5100 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
5101 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
5102
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005103 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01005104
5105 /* Register previous table in the registry with reference and named entry. */
5106 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5107 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
5108 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
5109
5110 /*
5111 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005112 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005113 *
5114 */
5115
5116 /* Create and fill the metatable. */
5117 lua_newtable(gL.T);
5118
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02005119 /* Create the __tostring identifier */
5120 lua_pushstring(gL.T, "__tostring");
5121 lua_pushstring(gL.T, CLASS_FETCHES);
5122 lua_pushcclosure(gL.T, hlua_dump_object, 1);
5123 lua_rawset(gL.T, -3);
5124
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005125 /* Create and fille the __index entry. */
5126 lua_pushstring(gL.T, "__index");
5127 lua_newtable(gL.T);
5128
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01005129 /* Browse existing fetches and create the associated
5130 * object method.
5131 */
5132 sf = NULL;
5133 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
5134
5135 /* Dont register the keywork if the arguments check function are
5136 * not safe during the runtime.
5137 */
5138 if ((sf->val_args != NULL) &&
5139 (sf->val_args != val_payload_lv) &&
5140 (sf->val_args != val_hdr))
5141 continue;
5142
5143 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
5144 * by an underscore.
5145 */
5146 strncpy(trash.str, sf->kw, trash.size);
5147 trash.str[trash.size - 1] = '\0';
5148 for (p = trash.str; *p; p++)
5149 if (*p == '.' || *p == '-' || *p == '+')
5150 *p = '_';
5151
5152 /* Register the function. */
5153 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01005154 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01005155 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005156 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01005157 }
5158
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005159 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005160
5161 /* Register previous table in the registry with reference and named entry. */
5162 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5163 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
5164 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
5165
5166 /*
5167 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005168 * Register class Converters
5169 *
5170 */
5171
5172 /* Create and fill the metatable. */
5173 lua_newtable(gL.T);
5174
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02005175 /* Create the __tostring identifier */
5176 lua_pushstring(gL.T, "__tostring");
5177 lua_pushstring(gL.T, CLASS_CONVERTERS);
5178 lua_pushcclosure(gL.T, hlua_dump_object, 1);
5179 lua_rawset(gL.T, -3);
5180
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005181 /* Create and fill the __index entry. */
5182 lua_pushstring(gL.T, "__index");
5183 lua_newtable(gL.T);
5184
5185 /* Browse existing converters and create the associated
5186 * object method.
5187 */
5188 sc = NULL;
5189 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
5190 /* Dont register the keywork if the arguments check function are
5191 * not safe during the runtime.
5192 */
5193 if (sc->val_args != NULL)
5194 continue;
5195
5196 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
5197 * by an underscore.
5198 */
5199 strncpy(trash.str, sc->kw, trash.size);
5200 trash.str[trash.size - 1] = '\0';
5201 for (p = trash.str; *p; p++)
5202 if (*p == '.' || *p == '-' || *p == '+')
5203 *p = '_';
5204
5205 /* Register the function. */
5206 lua_pushstring(gL.T, trash.str);
5207 lua_pushlightuserdata(gL.T, sc);
5208 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005209 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005210 }
5211
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005212 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005213
5214 /* Register previous table in the registry with reference and named entry. */
5215 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5216 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
5217 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
5218
5219 /*
5220 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005221 * Register class HTTP
5222 *
5223 */
5224
5225 /* Create and fill the metatable. */
5226 lua_newtable(gL.T);
5227
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02005228 /* Create the __tostring identifier */
5229 lua_pushstring(gL.T, "__tostring");
5230 lua_pushstring(gL.T, CLASS_HTTP);
5231 lua_pushcclosure(gL.T, hlua_dump_object, 1);
5232 lua_rawset(gL.T, -3);
5233
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005234 /* Create and fille the __index entry. */
5235 lua_pushstring(gL.T, "__index");
5236 lua_newtable(gL.T);
5237
5238 /* Register Lua functions. */
5239 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
5240 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
5241 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
5242 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
5243 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
5244 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
5245 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
5246 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
5247 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
5248 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
5249
5250 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
5251 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
5252 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
5253 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
5254 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
5255 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005256 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005257
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005258 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005259
5260 /* Register previous table in the registry with reference and named entry. */
5261 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5262 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
5263 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
5264
5265 /*
5266 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005267 * Register class TXN
5268 *
5269 */
5270
5271 /* Create and fill the metatable. */
5272 lua_newtable(gL.T);
5273
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02005274 /* Create the __tostring identifier */
5275 lua_pushstring(gL.T, "__tostring");
5276 lua_pushstring(gL.T, CLASS_TXN);
5277 lua_pushcclosure(gL.T, hlua_dump_object, 1);
5278 lua_rawset(gL.T, -3);
5279
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005280 /* Create and fille the __index entry. */
5281 lua_pushstring(gL.T, "__index");
5282 lua_newtable(gL.T);
5283
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005284 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01005285 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
5286 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005287 hlua_class_function(gL.T, "set_var", hlua_set_var);
5288 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005289 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005290 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
5291 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
5292 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005293 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
5294 hlua_class_function(gL.T, "log", hlua_txn_log);
5295 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
5296 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
5297 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
5298 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005299
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005300 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005301
5302 /* Register previous table in the registry with reference and named entry. */
5303 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5304 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
5305 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005306
5307 /*
5308 *
5309 * Register class Socket
5310 *
5311 */
5312
5313 /* Create and fill the metatable. */
5314 lua_newtable(gL.T);
5315
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02005316 /* Create the __tostring identifier */
5317 lua_pushstring(gL.T, "__tostring");
5318 lua_pushstring(gL.T, CLASS_SOCKET);
5319 lua_pushcclosure(gL.T, hlua_dump_object, 1);
5320 lua_rawset(gL.T, -3);
5321
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005322 /* Create and fille the __index entry. */
5323 lua_pushstring(gL.T, "__index");
5324 lua_newtable(gL.T);
5325
Baptiste Assmann84bb4932015-03-02 21:40:06 +01005326#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005327 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01005328#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005329 hlua_class_function(gL.T, "connect", hlua_socket_connect);
5330 hlua_class_function(gL.T, "send", hlua_socket_send);
5331 hlua_class_function(gL.T, "receive", hlua_socket_receive);
5332 hlua_class_function(gL.T, "close", hlua_socket_close);
5333 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
5334 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
5335 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
5336 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
5337
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005338 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005339
5340 /* Register the garbage collector entry. */
5341 lua_pushstring(gL.T, "__gc");
5342 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005343 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005344
5345 /* Register previous table in the registry with reference and named entry. */
5346 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5347 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5348 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
5349 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
5350
5351 /* Proxy and server configuration initialisation. */
5352 memset(&socket_proxy, 0, sizeof(socket_proxy));
5353 init_new_proxy(&socket_proxy);
5354 socket_proxy.parent = NULL;
5355 socket_proxy.last_change = now.tv_sec;
5356 socket_proxy.id = "LUA-SOCKET";
5357 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
5358 socket_proxy.maxconn = 0;
5359 socket_proxy.accept = NULL;
5360 socket_proxy.options2 |= PR_O2_INDEPSTR;
5361 socket_proxy.srv = NULL;
5362 socket_proxy.conn_retries = 0;
5363 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
5364
5365 /* Init TCP server: unchanged parameters */
5366 memset(&socket_tcp, 0, sizeof(socket_tcp));
5367 socket_tcp.next = NULL;
5368 socket_tcp.proxy = &socket_proxy;
5369 socket_tcp.obj_type = OBJ_TYPE_SERVER;
5370 LIST_INIT(&socket_tcp.actconns);
5371 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02005372 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02005373 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02005374 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005375 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
5376 socket_tcp.last_change = 0;
5377 socket_tcp.id = "LUA-TCP-CONN";
5378 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5379 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5380 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
5381
5382 /* XXX: Copy default parameter from default server,
5383 * but the default server is not initialized.
5384 */
5385 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
5386 socket_tcp.minconn = socket_proxy.defsrv.minconn;
5387 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
5388 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
5389 socket_tcp.onerror = socket_proxy.defsrv.onerror;
5390 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5391 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
5392 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5393 socket_tcp.uweight = socket_proxy.defsrv.iweight;
5394 socket_tcp.iweight = socket_proxy.defsrv.iweight;
5395
5396 socket_tcp.check.status = HCHK_STATUS_INI;
5397 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
5398 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
5399 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
5400 socket_tcp.check.server = &socket_tcp;
5401
5402 socket_tcp.agent.status = HCHK_STATUS_INI;
5403 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
5404 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
5405 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
5406 socket_tcp.agent.server = &socket_tcp;
5407
5408 socket_tcp.xprt = &raw_sock;
5409
5410#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005411 /* Init TCP server: unchanged parameters */
5412 memset(&socket_ssl, 0, sizeof(socket_ssl));
5413 socket_ssl.next = NULL;
5414 socket_ssl.proxy = &socket_proxy;
5415 socket_ssl.obj_type = OBJ_TYPE_SERVER;
5416 LIST_INIT(&socket_ssl.actconns);
5417 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02005418 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02005419 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02005420 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005421 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
5422 socket_ssl.last_change = 0;
5423 socket_ssl.id = "LUA-SSL-CONN";
5424 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5425 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5426 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
5427
5428 /* XXX: Copy default parameter from default server,
5429 * but the default server is not initialized.
5430 */
5431 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
5432 socket_ssl.minconn = socket_proxy.defsrv.minconn;
5433 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
5434 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
5435 socket_ssl.onerror = socket_proxy.defsrv.onerror;
5436 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5437 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
5438 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5439 socket_ssl.uweight = socket_proxy.defsrv.iweight;
5440 socket_ssl.iweight = socket_proxy.defsrv.iweight;
5441
5442 socket_ssl.check.status = HCHK_STATUS_INI;
5443 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
5444 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
5445 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
5446 socket_ssl.check.server = &socket_ssl;
5447
5448 socket_ssl.agent.status = HCHK_STATUS_INI;
5449 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
5450 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
5451 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
5452 socket_ssl.agent.server = &socket_ssl;
5453
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005454 socket_ssl.use_ssl = 1;
5455 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005456
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005457 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005458 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
5459 /*
5460 *
5461 * If the keyword is not known, we can search in the registered
5462 * server keywords. This is usefull to configure special SSL
5463 * features like client certificates and ssl_verify.
5464 *
5465 */
5466 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
5467 if (tmp_error != 0) {
5468 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
5469 abort(); /* This must be never arrives because the command line
5470 not editable by the user. */
5471 }
5472 idx += kw->skip;
5473 }
5474 }
5475
5476 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005477 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005478#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01005479}