blob: 121c283f1c25bfdbaefee614a6a4d8c0aae4b9e7 [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010013#include <sys/socket.h>
14
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020016#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010017
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010018#include <lauxlib.h>
19#include <lua.h>
20#include <lualib.h>
21
Thierry FOURNIER463119c2015-03-10 00:35:36 +010022#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
23#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010024#endif
25
Thierry FOURNIER380d0932015-01-23 14:27:52 +010026#include <ebpttree.h>
27
28#include <common/cfgparse.h>
29
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010030#include <types/connection.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010031#include <types/hlua.h>
32#include <types/proxy.h>
33
Thierry FOURNIER55da1652015-01-23 11:36:30 +010034#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020035#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010036#include <proto/channel.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010037#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010038#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010039#include <proto/hlua_fcn.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020040#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010041#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010042#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010043#include <proto/payload.h>
44#include <proto/proto_http.h>
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010045#include <proto/proto_tcp.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010046#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010047#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010048#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020049#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020050#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010051#include <proto/ssl_sock.h>
52#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010053#include <proto/task.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020054#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010055
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010056/* Lua uses longjmp to perform yield or throwing errors. This
57 * macro is used only for identifying the function that can
58 * not return because a longjmp is executed.
59 * __LJMP marks a prototype of hlua file that can use longjmp.
60 * WILL_LJMP() marks an lua function that will use longjmp.
61 * MAY_LJMP() marks an lua function that may use longjmp.
62 */
63#define __LJMP
64#define WILL_LJMP(func) func
65#define MAY_LJMP(func) func
66
Thierry FOURNIERbabae282015-09-17 11:36:37 +020067/* This couple of function executes securely some Lua calls outside of
68 * the lua runtime environment. Each Lua call can return a longjmp
69 * if it encounter a memory error.
70 *
71 * Lua documentation extract:
72 *
73 * If an error happens outside any protected environment, Lua calls
74 * a panic function (see lua_atpanic) and then calls abort, thus
75 * exiting the host application. Your panic function can avoid this
76 * exit by never returning (e.g., doing a long jump to your own
77 * recovery point outside Lua).
78 *
79 * The panic function runs as if it were a message handler (see
80 * §2.3); in particular, the error message is at the top of the
81 * stack. However, there is no guarantee about stack space. To push
82 * anything on the stack, the panic function must first check the
83 * available space (see §4.2).
84 *
85 * We must check all the Lua entry point. This includes:
86 * - The include/proto/hlua.h exported functions
87 * - the task wrapper function
88 * - The action wrapper function
89 * - The converters wrapper function
90 * - The sample-fetch wrapper functions
91 *
92 * It is tolerated that the initilisation function returns an abort.
93 * Before each Lua abort, an error message is writed on stderr.
94 *
95 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
96 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
97 * because they must be exists in the program stack when the longjmp
98 * is called.
99 */
100jmp_buf safe_ljmp_env;
101static int hlua_panic_safe(lua_State *L) { return 0; }
102static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
103
104#define SET_SAFE_LJMP(__L) \
105 ({ \
106 int ret; \
107 if (setjmp(safe_ljmp_env) != 0) { \
108 lua_atpanic(__L, hlua_panic_safe); \
109 ret = 0; \
110 } else { \
111 lua_atpanic(__L, hlua_panic_ljmp); \
112 ret = 1; \
113 } \
114 ret; \
115 })
116
117/* If we are the last function catching Lua errors, we
118 * must reset the panic function.
119 */
120#define RESET_SAFE_LJMP(__L) \
121 do { \
122 lua_atpanic(__L, hlua_panic_safe); \
123 } while(0)
124
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200125/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200126#define APPLET_DONE 0x01 /* applet processing is done. */
127#define APPLET_100C 0x02 /* 100 continue expected. */
128#define APPLET_HDR_SENT 0x04 /* Response header sent. */
129#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
130#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100131#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200132
133#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200134
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100135/* The main Lua execution context. */
136struct hlua gL;
137
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100138/* This is the memory pool containing all the signal structs. These
139 * struct are used to store each requiered signal between two tasks.
140 */
141struct pool_head *pool2_hlua_com;
142
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100143/* Used for Socket connection. */
144static struct proxy socket_proxy;
145static struct server socket_tcp;
146#ifdef USE_OPENSSL
147static struct server socket_ssl;
148#endif
149
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100150/* List head of the function called at the initialisation time. */
151struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
152
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100153/* The following variables contains the reference of the different
154 * Lua classes. These references are useful for identify metadata
155 * associated with an object.
156 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100157static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100158static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100159static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100160static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100161static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100162static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200163static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200164static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200165static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100166
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100167/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200168 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100169 * short timeout. Lua linked with tasks doesn't have a timeout
170 * because a task may remain alive during all the haproxy execution.
171 */
172static unsigned int hlua_timeout_session = 4000; /* session timeout. */
173static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200174static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100175
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100176/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
177 * it is used for preventing infinite loops.
178 *
179 * I test the scheer with an infinite loop containing one incrementation
180 * and one test. I run this loop between 10 seconds, I raise a ceil of
181 * 710M loops from one interrupt each 9000 instructions, so I fix the value
182 * to one interrupt each 10 000 instructions.
183 *
184 * configured | Number of
185 * instructions | loops executed
186 * between two | in milions
187 * forced yields |
188 * ---------------+---------------
189 * 10 | 160
190 * 500 | 670
191 * 1000 | 680
192 * 5000 | 700
193 * 7000 | 700
194 * 8000 | 700
195 * 9000 | 710 <- ceil
196 * 10000 | 710
197 * 100000 | 710
198 * 1000000 | 710
199 *
200 */
201static unsigned int hlua_nb_instruction = 10000;
202
Willy Tarreau32f61e22015-03-18 17:54:59 +0100203/* Descriptor for the memory allocation state. If limit is not null, it will
204 * be enforced on any memory allocation.
205 */
206struct hlua_mem_allocator {
207 size_t allocated;
208 size_t limit;
209};
210
211static struct hlua_mem_allocator hlua_global_allocator;
212
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200213static const char error_500[] =
214 "HTTP/1.0 500 Server Error\r\n"
215 "Cache-Control: no-cache\r\n"
216 "Connection: close\r\n"
217 "Content-Type: text/html\r\n"
218 "\r\n"
219 "<html><body><h1>500 Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
220
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100221/* These functions converts types between HAProxy internal args or
222 * sample and LUA types. Another function permits to check if the
223 * LUA stack contains arguments according with an required ARG_T
224 * format.
225 */
226static int hlua_arg2lua(lua_State *L, const struct arg *arg);
227static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100228__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100229 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100230static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100231static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100232static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
233
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200234__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
235
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200236#define SEND_ERR(__be, __fmt, __args...) \
237 do { \
238 send_log(__be, LOG_ERR, __fmt, ## __args); \
239 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
240 Alert(__fmt, ## __args); \
241 } while (0)
242
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100243/* Used to check an Lua function type in the stack. It creates and
244 * returns a reference of the function. This function throws an
245 * error if the rgument is not a "function".
246 */
247__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
248{
249 if (!lua_isfunction(L, argno)) {
250 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
251 WILL_LJMP(luaL_argerror(L, argno, msg));
252 }
253 lua_pushvalue(L, argno);
254 return luaL_ref(L, LUA_REGISTRYINDEX);
255}
256
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200257/* Return the string that is of the top of the stack. */
258const char *hlua_get_top_error_string(lua_State *L)
259{
260 if (lua_gettop(L) < 1)
261 return "unknown error";
262 if (lua_type(L, -1) != LUA_TSTRING)
263 return "unknown error";
264 return lua_tostring(L, -1);
265}
266
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100267/* This function check the number of arguments available in the
268 * stack. If the number of arguments available is not the same
269 * then <nb> an error is throwed.
270 */
271__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
272{
273 if (lua_gettop(L) == nb)
274 return;
275 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
276}
277
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100278/* This fucntion push an error string prefixed by the file name
279 * and the line number where the error is encountered.
280 */
281static int hlua_pusherror(lua_State *L, const char *fmt, ...)
282{
283 va_list argp;
284 va_start(argp, fmt);
285 luaL_where(L, 1);
286 lua_pushvfstring(L, fmt, argp);
287 va_end(argp);
288 lua_concat(L, 2);
289 return 1;
290}
291
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100292/* This function register a new signal. "lua" is the current lua
293 * execution context. It contains a pointer to the associated task.
294 * "link" is a list head attached to an other task that must be wake
295 * the lua task if an event occurs. This is useful with external
296 * events like TCP I/O or sleep functions. This funcion allocate
297 * memory for the signal.
298 */
299static int hlua_com_new(struct hlua *lua, struct list *link)
300{
301 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
302 if (!com)
303 return 0;
304 LIST_ADDQ(&lua->com, &com->purge_me);
305 LIST_ADDQ(link, &com->wake_me);
306 com->task = lua->task;
307 return 1;
308}
309
310/* This function purge all the pending signals when the LUA execution
311 * is finished. This prevent than a coprocess try to wake a deleted
312 * task. This function remove the memory associated to the signal.
313 */
314static void hlua_com_purge(struct hlua *lua)
315{
316 struct hlua_com *com, *back;
317
318 /* Delete all pending communication signals. */
319 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
320 LIST_DEL(&com->purge_me);
321 LIST_DEL(&com->wake_me);
322 pool_free2(pool2_hlua_com, com);
323 }
324}
325
326/* This function sends signals. It wakes all the tasks attached
327 * to a list head, and remove the signal, and free the used
328 * memory.
329 */
330static void hlua_com_wake(struct list *wake)
331{
332 struct hlua_com *com, *back;
333
334 /* Wake task and delete all pending communication signals. */
335 list_for_each_entry_safe(com, back, wake, wake_me) {
336 LIST_DEL(&com->purge_me);
337 LIST_DEL(&com->wake_me);
338 task_wakeup(com->task, TASK_WOKEN_MSG);
339 pool_free2(pool2_hlua_com, com);
340 }
341}
342
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100343/* This functions is used with sample fetch and converters. It
344 * converts the HAProxy configuration argument in a lua stack
345 * values.
346 *
347 * It takes an array of "arg", and each entry of the array is
348 * converted and pushed in the LUA stack.
349 */
350static int hlua_arg2lua(lua_State *L, const struct arg *arg)
351{
352 switch (arg->type) {
353 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100354 case ARGT_TIME:
355 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100356 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100357 break;
358
359 case ARGT_STR:
360 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
361 break;
362
363 case ARGT_IPV4:
364 case ARGT_IPV6:
365 case ARGT_MSK4:
366 case ARGT_MSK6:
367 case ARGT_FE:
368 case ARGT_BE:
369 case ARGT_TAB:
370 case ARGT_SRV:
371 case ARGT_USR:
372 case ARGT_MAP:
373 default:
374 lua_pushnil(L);
375 break;
376 }
377 return 1;
378}
379
380/* This function take one entrie in an LUA stack at the index "ud",
381 * and try to convert it in an HAProxy argument entry. This is useful
382 * with sample fetch wrappers. The input arguments are gived to the
383 * lua wrapper and converted as arg list by thi function.
384 */
385static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
386{
387 switch (lua_type(L, ud)) {
388
389 case LUA_TNUMBER:
390 case LUA_TBOOLEAN:
391 arg->type = ARGT_SINT;
392 arg->data.sint = lua_tointeger(L, ud);
393 break;
394
395 case LUA_TSTRING:
396 arg->type = ARGT_STR;
397 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
398 break;
399
400 case LUA_TUSERDATA:
401 case LUA_TNIL:
402 case LUA_TTABLE:
403 case LUA_TFUNCTION:
404 case LUA_TTHREAD:
405 case LUA_TLIGHTUSERDATA:
406 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200407 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100408 break;
409 }
410 return 1;
411}
412
413/* the following functions are used to convert a struct sample
414 * in Lua type. This useful to convert the return of the
415 * fetchs or converters.
416 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100417static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100418{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200419 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100420 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100421 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200422 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100423 break;
424
425 case SMP_T_BIN:
426 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200427 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100428 break;
429
430 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200431 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100432 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
433 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
434 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
435 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
436 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
437 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
438 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
439 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
440 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200441 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100442 break;
443 default:
444 lua_pushnil(L);
445 break;
446 }
447 break;
448
449 case SMP_T_IPV4:
450 case SMP_T_IPV6:
451 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200452 if (sample_casts[smp->data.type][SMP_T_STR] &&
453 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200454 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100455 else
456 lua_pushnil(L);
457 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100458 default:
459 lua_pushnil(L);
460 break;
461 }
462 return 1;
463}
464
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100465/* the following functions are used to convert a struct sample
466 * in Lua strings. This is useful to convert the return of the
467 * fetchs or converters.
468 */
469static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
470{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200471 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100472
473 case SMP_T_BIN:
474 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200475 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100476 break;
477
478 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200479 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100480 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
481 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
482 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
483 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
484 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
485 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
486 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
487 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
488 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200489 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100490 break;
491 default:
492 lua_pushstring(L, "");
493 break;
494 }
495 break;
496
497 case SMP_T_SINT:
498 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100499 case SMP_T_IPV4:
500 case SMP_T_IPV6:
501 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200502 if (sample_casts[smp->data.type][SMP_T_STR] &&
503 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200504 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100505 else
506 lua_pushstring(L, "");
507 break;
508 default:
509 lua_pushstring(L, "");
510 break;
511 }
512 return 1;
513}
514
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100515/* the following functions are used to convert an Lua type in a
516 * struct sample. This is useful to provide data from a converter
517 * to the LUA code.
518 */
519static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
520{
521 switch (lua_type(L, ud)) {
522
523 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200524 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200525 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100526 break;
527
528
529 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200530 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200531 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100532 break;
533
534 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200535 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100536 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200537 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100538 break;
539
540 case LUA_TUSERDATA:
541 case LUA_TNIL:
542 case LUA_TTABLE:
543 case LUA_TFUNCTION:
544 case LUA_TTHREAD:
545 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200546 case LUA_TNONE:
547 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200548 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200549 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100550 break;
551 }
552 return 1;
553}
554
555/* This function check the "argp" builded by another conversion function
556 * is in accord with the expected argp defined by the "mask". The fucntion
557 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100558 *
559 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
560 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100561 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100562__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100563 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100564{
565 int min_arg;
566 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100567 struct proxy *px;
568 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100569
570 idx = 0;
571 min_arg = ARGM(mask);
572 mask >>= ARGM_BITS;
573
574 while (1) {
575
576 /* Check oversize. */
577 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100578 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100579 }
580
581 /* Check for mandatory arguments. */
582 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100583 if (idx < min_arg) {
584
585 /* If miss other argument than the first one, we return an error. */
586 if (idx > 0)
587 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
588
589 /* If first argument have a certain type, some default values
590 * may be used. See the function smp_resolve_args().
591 */
592 switch (mask & ARGT_MASK) {
593
594 case ARGT_FE:
595 if (!(p->cap & PR_CAP_FE))
596 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
597 argp[idx].data.prx = p;
598 argp[idx].type = ARGT_FE;
599 argp[idx+1].type = ARGT_STOP;
600 break;
601
602 case ARGT_BE:
603 if (!(p->cap & PR_CAP_BE))
604 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
605 argp[idx].data.prx = p;
606 argp[idx].type = ARGT_BE;
607 argp[idx+1].type = ARGT_STOP;
608 break;
609
610 case ARGT_TAB:
611 argp[idx].data.prx = p;
612 argp[idx].type = ARGT_TAB;
613 argp[idx+1].type = ARGT_STOP;
614 break;
615
616 default:
617 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
618 break;
619 }
620 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100621 return 0;
622 }
623
624 /* Check for exceed the number of requiered argument. */
625 if ((mask & ARGT_MASK) == ARGT_STOP &&
626 argp[idx].type != ARGT_STOP) {
627 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
628 }
629
630 if ((mask & ARGT_MASK) == ARGT_STOP &&
631 argp[idx].type == ARGT_STOP) {
632 return 0;
633 }
634
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100635 /* Convert some argument types. */
636 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100637 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100638 if (argp[idx].type != ARGT_SINT)
639 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
640 argp[idx].type = ARGT_SINT;
641 break;
642
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100643 case ARGT_TIME:
644 if (argp[idx].type != ARGT_SINT)
645 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200646 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100647 break;
648
649 case ARGT_SIZE:
650 if (argp[idx].type != ARGT_SINT)
651 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200652 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100653 break;
654
655 case ARGT_FE:
656 if (argp[idx].type != ARGT_STR)
657 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
658 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
659 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200660 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100661 if (!argp[idx].data.prx)
662 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
663 argp[idx].type = ARGT_FE;
664 break;
665
666 case ARGT_BE:
667 if (argp[idx].type != ARGT_STR)
668 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
669 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
670 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200671 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100672 if (!argp[idx].data.prx)
673 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
674 argp[idx].type = ARGT_BE;
675 break;
676
677 case ARGT_TAB:
678 if (argp[idx].type != ARGT_STR)
679 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
680 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
681 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200682 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100683 if (!argp[idx].data.prx)
684 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
685 argp[idx].type = ARGT_TAB;
686 break;
687
688 case ARGT_SRV:
689 if (argp[idx].type != ARGT_STR)
690 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
691 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
692 trash.str[argp[idx].data.str.len] = 0;
693 sname = strrchr(trash.str, '/');
694 if (sname) {
695 *sname++ = '\0';
696 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200697 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100698 if (!px)
699 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
700 }
701 else {
702 sname = trash.str;
703 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100704 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100705 argp[idx].data.srv = findserver(px, sname);
706 if (!argp[idx].data.srv)
707 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
708 argp[idx].type = ARGT_SRV;
709 break;
710
711 case ARGT_IPV4:
712 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
713 trash.str[argp[idx].data.str.len] = 0;
714 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
715 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
716 argp[idx].type = ARGT_IPV4;
717 break;
718
719 case ARGT_MSK4:
720 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
721 trash.str[argp[idx].data.str.len] = 0;
722 if (!str2mask(trash.str, &argp[idx].data.ipv4))
723 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
724 argp[idx].type = ARGT_MSK4;
725 break;
726
727 case ARGT_IPV6:
728 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
729 trash.str[argp[idx].data.str.len] = 0;
730 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
731 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
732 argp[idx].type = ARGT_IPV6;
733 break;
734
735 case ARGT_MSK6:
736 case ARGT_MAP:
737 case ARGT_REG:
738 case ARGT_USR:
739 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100740 break;
741 }
742
743 /* Check for type of argument. */
744 if ((mask & ARGT_MASK) != argp[idx].type) {
745 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
746 arg_type_names[(mask & ARGT_MASK)],
747 arg_type_names[argp[idx].type & ARGT_MASK]);
748 WILL_LJMP(luaL_argerror(L, first + idx, msg));
749 }
750
751 /* Next argument. */
752 mask >>= ARGT_BITS;
753 idx++;
754 }
755}
756
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100757/*
758 * The following functions are used to make correspondance between the the
759 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100760 *
761 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100762 * - hlua_sethlua : create the association between hlua context and lua_state.
763 */
764static inline struct hlua *hlua_gethlua(lua_State *L)
765{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100766 struct hlua **hlua = lua_getextraspace(L);
767 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100768}
769static inline void hlua_sethlua(struct hlua *hlua)
770{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100771 struct hlua **hlua_store = lua_getextraspace(hlua->T);
772 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100773}
774
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100775/* This function is used to send logs. It try to send on screen (stderr)
776 * and on the default syslog server.
777 */
778static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
779{
780 struct tm tm;
781 char *p;
782
783 /* Cleanup the log message. */
784 p = trash.str;
785 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200786 if (p >= trash.str + trash.size - 1) {
787 /* Break the message if exceed the buffer size. */
788 *(p-4) = ' ';
789 *(p-3) = '.';
790 *(p-2) = '.';
791 *(p-1) = '.';
792 break;
793 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100794 if (isprint(*msg))
795 *p = *msg;
796 else
797 *p = '.';
798 }
799 *p = '\0';
800
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200801 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100802 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200803 get_localtime(date.tv_sec, &tm);
804 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100805 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
806 (int)getpid(), trash.str);
807 fflush(stderr);
808 }
809}
810
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100811/* This function just ensure that the yield will be always
812 * returned with a timeout and permit to set some flags
813 */
814__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100815 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100816{
817 struct hlua *hlua = hlua_gethlua(L);
818
819 /* Set the wake timeout. If timeout is required, we set
820 * the expiration time.
821 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200822 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100823
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100824 hlua->flags |= flags;
825
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100826 /* Process the yield. */
827 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
828}
829
Willy Tarreau87b09662015-04-03 00:22:06 +0200830/* This function initialises the Lua environment stored in the stream.
831 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100832 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200833 *
834 * This function is particular. it initialises a new Lua thread. If the
835 * initialisation fails (example: out of memory error), the lua function
836 * throws an error (longjmp).
837 *
838 * This function manipulates two Lua stack: the main and the thread. Only
839 * the main stack can fail. The thread is not manipulated. This function
840 * MUST NOT manipulate the created thread stack state, because is not
841 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100842 */
843int hlua_ctx_init(struct hlua *lua, struct task *task)
844{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200845 if (!SET_SAFE_LJMP(gL.T)) {
846 lua->Tref = LUA_REFNIL;
847 return 0;
848 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100849 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100850 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100851 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100852 lua->T = lua_newthread(gL.T);
853 if (!lua->T) {
854 lua->Tref = LUA_REFNIL;
855 return 0;
856 }
857 hlua_sethlua(lua);
858 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
859 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200860 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100861 return 1;
862}
863
Willy Tarreau87b09662015-04-03 00:22:06 +0200864/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100865 * is destroyed. The destroy also the memory context. The struct "lua"
866 * is not freed.
867 */
868void hlua_ctx_destroy(struct hlua *lua)
869{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100870 if (!lua->T)
871 return;
872
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100873 /* Purge all the pending signals. */
874 hlua_com_purge(lua);
875
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100876 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
877 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200878
879 /* Forces a garbage collecting process. If the Lua program is finished
880 * without error, we run the GC on the thread pointer. Its freed all
881 * the unused memory.
882 * If the thread is finnish with an error or is currently yielded,
883 * it seems that the GC applied on the thread doesn't clean anything,
884 * so e run the GC on the main thread.
885 * NOTE: maybe this action locks all the Lua threads untiml the en of
886 * the garbage collection.
887 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200888 if (lua->flags & HLUA_MUST_GC) {
889 lua_gc(lua->T, LUA_GCCOLLECT, 0);
890 if (lua_status(lua->T) != LUA_OK)
891 lua_gc(gL.T, LUA_GCCOLLECT, 0);
892 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200893
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200894 lua->T = NULL;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100895}
896
897/* This function is used to restore the Lua context when a coroutine
898 * fails. This function copy the common memory between old coroutine
899 * and the new coroutine. The old coroutine is destroyed, and its
900 * replaced by the new coroutine.
901 * If the flag "keep_msg" is set, the last entry of the old is assumed
902 * as string error message and it is copied in the new stack.
903 */
904static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
905{
906 lua_State *T;
907 int new_ref;
908
909 /* Renew the main LUA stack doesn't have sense. */
910 if (lua == &gL)
911 return 0;
912
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100913 /* New Lua coroutine. */
914 T = lua_newthread(gL.T);
915 if (!T)
916 return 0;
917
918 /* Copy last error message. */
919 if (keep_msg)
920 lua_xmove(lua->T, T, 1);
921
922 /* Copy data between the coroutines. */
923 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
924 lua_xmove(lua->T, T, 1);
925 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
926
927 /* Destroy old data. */
928 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
929
930 /* The thread is garbage collected by Lua. */
931 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
932
933 /* Fill the struct with the new coroutine values. */
934 lua->Mref = new_ref;
935 lua->T = T;
936 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
937
938 /* Set context. */
939 hlua_sethlua(lua);
940
941 return 1;
942}
943
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100944void hlua_hook(lua_State *L, lua_Debug *ar)
945{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100946 struct hlua *hlua = hlua_gethlua(L);
947
948 /* Lua cannot yield when its returning from a function,
949 * so, we can fix the interrupt hook to 1 instruction,
950 * expecting that the function is finnished.
951 */
952 if (lua_gethookmask(L) & LUA_MASKRET) {
953 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
954 return;
955 }
956
957 /* restore the interrupt condition. */
958 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
959
960 /* If we interrupt the Lua processing in yieldable state, we yield.
961 * If the state is not yieldable, trying yield causes an error.
962 */
963 if (lua_isyieldable(L))
964 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
965
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100966 /* If we cannot yield, update the clock and check the timeout. */
967 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200968 hlua->run_time += now_ms - hlua->start_time;
969 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100970 lua_pushfstring(L, "execution timeout");
971 WILL_LJMP(lua_error(L));
972 }
973
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200974 /* Update the start time. */
975 hlua->start_time = now_ms;
976
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100977 /* Try to interrupt the process at the end of the current
978 * unyieldable function.
979 */
980 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100981}
982
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100983/* This function start or resumes the Lua stack execution. If the flag
984 * "yield_allowed" if no set and the LUA stack execution returns a yield
985 * The function return an error.
986 *
987 * The function can returns 4 values:
988 * - HLUA_E_OK : The execution is terminated without any errors.
989 * - HLUA_E_AGAIN : The execution must continue at the next associated
990 * task wakeup.
991 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
992 * the top of the stack.
993 * - HLUA_E_ERR : An error has occured without error message.
994 *
995 * If an error occured, the stack is renewed and it is ready to run new
996 * LUA code.
997 */
998static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
999{
1000 int ret;
1001 const char *msg;
1002
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001003 /* Initialise run time counter. */
1004 if (!HLUA_IS_RUNNING(lua))
1005 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001006
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001007resume_execution:
1008
1009 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1010 * instructions. it is used for preventing infinite loops.
1011 */
1012 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1013
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001014 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001015 HLUA_SET_RUN(lua);
1016 HLUA_CLR_CTRLYIELD(lua);
1017 HLUA_CLR_WAKERESWR(lua);
1018 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001019
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001020 /* Update the start time. */
1021 lua->start_time = now_ms;
1022
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001023 /* Call the function. */
1024 ret = lua_resume(lua->T, gL.T, lua->nargs);
1025 switch (ret) {
1026
1027 case LUA_OK:
1028 ret = HLUA_E_OK;
1029 break;
1030
1031 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001032 /* Check if the execution timeout is expired. It it is the case, we
1033 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001034 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001035 tv_update_date(0, 1);
1036 lua->run_time += now_ms - lua->start_time;
1037 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001038 lua_settop(lua->T, 0); /* Empty the stack. */
1039 if (!lua_checkstack(lua->T, 1)) {
1040 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001041 break;
1042 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001043 lua_pushfstring(lua->T, "execution timeout");
1044 ret = HLUA_E_ERRMSG;
1045 break;
1046 }
1047 /* Process the forced yield. if the general yield is not allowed or
1048 * if no task were associated this the current Lua execution
1049 * coroutine, we resume the execution. Else we want to return in the
1050 * scheduler and we want to be waked up again, to continue the
1051 * current Lua execution. So we schedule our own task.
1052 */
1053 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001054 if (!yield_allowed || !lua->task)
1055 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001056 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001057 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001058 if (!yield_allowed) {
1059 lua_settop(lua->T, 0); /* Empty the stack. */
1060 if (!lua_checkstack(lua->T, 1)) {
1061 ret = HLUA_E_ERR;
1062 break;
1063 }
1064 lua_pushfstring(lua->T, "yield not allowed");
1065 ret = HLUA_E_ERRMSG;
1066 break;
1067 }
1068 ret = HLUA_E_AGAIN;
1069 break;
1070
1071 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001072
1073 /* Special exit case. The traditionnal exit is returned as an error
1074 * because the errors ares the only one mean to return immediately
1075 * from and lua execution.
1076 */
1077 if (lua->flags & HLUA_EXIT) {
1078 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001079 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001080 break;
1081 }
1082
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001083 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001084 if (!lua_checkstack(lua->T, 1)) {
1085 ret = HLUA_E_ERR;
1086 break;
1087 }
1088 msg = lua_tostring(lua->T, -1);
1089 lua_settop(lua->T, 0); /* Empty the stack. */
1090 lua_pop(lua->T, 1);
1091 if (msg)
1092 lua_pushfstring(lua->T, "runtime error: %s", msg);
1093 else
1094 lua_pushfstring(lua->T, "unknown runtime error");
1095 ret = HLUA_E_ERRMSG;
1096 break;
1097
1098 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001099 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001100 lua_settop(lua->T, 0); /* Empty the stack. */
1101 if (!lua_checkstack(lua->T, 1)) {
1102 ret = HLUA_E_ERR;
1103 break;
1104 }
1105 lua_pushfstring(lua->T, "out of memory error");
1106 ret = HLUA_E_ERRMSG;
1107 break;
1108
1109 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001110 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001111 if (!lua_checkstack(lua->T, 1)) {
1112 ret = HLUA_E_ERR;
1113 break;
1114 }
1115 msg = lua_tostring(lua->T, -1);
1116 lua_settop(lua->T, 0); /* Empty the stack. */
1117 lua_pop(lua->T, 1);
1118 if (msg)
1119 lua_pushfstring(lua->T, "message handler error: %s", msg);
1120 else
1121 lua_pushfstring(lua->T, "message handler error");
1122 ret = HLUA_E_ERRMSG;
1123 break;
1124
1125 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001126 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001127 lua_settop(lua->T, 0); /* Empty the stack. */
1128 if (!lua_checkstack(lua->T, 1)) {
1129 ret = HLUA_E_ERR;
1130 break;
1131 }
1132 lua_pushfstring(lua->T, "unknonwn error");
1133 ret = HLUA_E_ERRMSG;
1134 break;
1135 }
1136
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001137 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001138 if (lua->flags & HLUA_MUST_GC &&
1139 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001140 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1141
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001142 switch (ret) {
1143 case HLUA_E_AGAIN:
1144 break;
1145
1146 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001147 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001148 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001149 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001150 break;
1151
1152 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001153 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001154 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001155 hlua_ctx_renew(lua, 0);
1156 break;
1157
1158 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001159 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001160 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001161 break;
1162 }
1163
1164 return ret;
1165}
1166
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001167/* This function exit the current code. */
1168__LJMP static int hlua_done(lua_State *L)
1169{
1170 struct hlua *hlua = hlua_gethlua(L);
1171
1172 hlua->flags |= HLUA_EXIT;
1173 WILL_LJMP(lua_error(L));
1174
1175 return 0;
1176}
1177
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001178/* This function is an LUA binding. It provides a function
1179 * for deleting ACL from a referenced ACL file.
1180 */
1181__LJMP static int hlua_del_acl(lua_State *L)
1182{
1183 const char *name;
1184 const char *key;
1185 struct pat_ref *ref;
1186
1187 MAY_LJMP(check_args(L, 2, "del_acl"));
1188
1189 name = MAY_LJMP(luaL_checkstring(L, 1));
1190 key = MAY_LJMP(luaL_checkstring(L, 2));
1191
1192 ref = pat_ref_lookup(name);
1193 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001194 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001195
1196 pat_ref_delete(ref, key);
1197 return 0;
1198}
1199
1200/* This function is an LUA binding. It provides a function
1201 * for deleting map entry from a referenced map file.
1202 */
1203static int hlua_del_map(lua_State *L)
1204{
1205 const char *name;
1206 const char *key;
1207 struct pat_ref *ref;
1208
1209 MAY_LJMP(check_args(L, 2, "del_map"));
1210
1211 name = MAY_LJMP(luaL_checkstring(L, 1));
1212 key = MAY_LJMP(luaL_checkstring(L, 2));
1213
1214 ref = pat_ref_lookup(name);
1215 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001216 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001217
1218 pat_ref_delete(ref, key);
1219 return 0;
1220}
1221
1222/* This function is an LUA binding. It provides a function
1223 * for adding ACL pattern from a referenced ACL file.
1224 */
1225static int hlua_add_acl(lua_State *L)
1226{
1227 const char *name;
1228 const char *key;
1229 struct pat_ref *ref;
1230
1231 MAY_LJMP(check_args(L, 2, "add_acl"));
1232
1233 name = MAY_LJMP(luaL_checkstring(L, 1));
1234 key = MAY_LJMP(luaL_checkstring(L, 2));
1235
1236 ref = pat_ref_lookup(name);
1237 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001238 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001239
1240 if (pat_ref_find_elt(ref, key) == NULL)
1241 pat_ref_add(ref, key, NULL, NULL);
1242 return 0;
1243}
1244
1245/* This function is an LUA binding. It provides a function
1246 * for setting map pattern and sample from a referenced map
1247 * file.
1248 */
1249static int hlua_set_map(lua_State *L)
1250{
1251 const char *name;
1252 const char *key;
1253 const char *value;
1254 struct pat_ref *ref;
1255
1256 MAY_LJMP(check_args(L, 3, "set_map"));
1257
1258 name = MAY_LJMP(luaL_checkstring(L, 1));
1259 key = MAY_LJMP(luaL_checkstring(L, 2));
1260 value = MAY_LJMP(luaL_checkstring(L, 3));
1261
1262 ref = pat_ref_lookup(name);
1263 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001264 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001265
1266 if (pat_ref_find_elt(ref, key) != NULL)
1267 pat_ref_set(ref, key, value, NULL);
1268 else
1269 pat_ref_add(ref, key, value, NULL);
1270 return 0;
1271}
1272
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001273/* A class is a lot of memory that contain data. This data can be a table,
1274 * an integer or user data. This data is associated with a metatable. This
1275 * metatable have an original version registred in the global context with
1276 * the name of the object (_G[<name>] = <metable> ).
1277 *
1278 * A metable is a table that modify the standard behavior of a standard
1279 * access to the associated data. The entries of this new metatable are
1280 * defined as is:
1281 *
1282 * http://lua-users.org/wiki/MetatableEvents
1283 *
1284 * __index
1285 *
1286 * we access an absent field in a table, the result is nil. This is
1287 * true, but it is not the whole truth. Actually, such access triggers
1288 * the interpreter to look for an __index metamethod: If there is no
1289 * such method, as usually happens, then the access results in nil;
1290 * otherwise, the metamethod will provide the result.
1291 *
1292 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1293 * the key does not appear in the table, but the metatable has an __index
1294 * property:
1295 *
1296 * - if the value is a function, the function is called, passing in the
1297 * table and the key; the return value of that function is returned as
1298 * the result.
1299 *
1300 * - if the value is another table, the value of the key in that table is
1301 * asked for and returned (and if it doesn't exist in that table, but that
1302 * table's metatable has an __index property, then it continues on up)
1303 *
1304 * - Use "rawget(myTable,key)" to skip this metamethod.
1305 *
1306 * http://www.lua.org/pil/13.4.1.html
1307 *
1308 * __newindex
1309 *
1310 * Like __index, but control property assignment.
1311 *
1312 * __mode - Control weak references. A string value with one or both
1313 * of the characters 'k' and 'v' which specifies that the the
1314 * keys and/or values in the table are weak references.
1315 *
1316 * __call - Treat a table like a function. When a table is followed by
1317 * parenthesis such as "myTable( 'foo' )" and the metatable has
1318 * a __call key pointing to a function, that function is invoked
1319 * (passing any specified arguments) and the return value is
1320 * returned.
1321 *
1322 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1323 * called, if the metatable for myTable has a __metatable
1324 * key, the value of that key is returned instead of the
1325 * actual metatable.
1326 *
1327 * __tostring - Control string representation. When the builtin
1328 * "tostring( myTable )" function is called, if the metatable
1329 * for myTable has a __tostring property set to a function,
1330 * that function is invoked (passing myTable to it) and the
1331 * return value is used as the string representation.
1332 *
1333 * __len - Control table length. When the table length is requested using
1334 * the length operator ( '#' ), if the metatable for myTable has
1335 * a __len key pointing to a function, that function is invoked
1336 * (passing myTable to it) and the return value used as the value
1337 * of "#myTable".
1338 *
1339 * __gc - Userdata finalizer code. When userdata is set to be garbage
1340 * collected, if the metatable has a __gc field pointing to a
1341 * function, that function is first invoked, passing the userdata
1342 * to it. The __gc metamethod is not called for tables.
1343 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1344 *
1345 * Special metamethods for redefining standard operators:
1346 * http://www.lua.org/pil/13.1.html
1347 *
1348 * __add "+"
1349 * __sub "-"
1350 * __mul "*"
1351 * __div "/"
1352 * __unm "!"
1353 * __pow "^"
1354 * __concat ".."
1355 *
1356 * Special methods for redfining standar relations
1357 * http://www.lua.org/pil/13.2.html
1358 *
1359 * __eq "=="
1360 * __lt "<"
1361 * __le "<="
1362 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001363
1364/*
1365 *
1366 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001367 * Class Map
1368 *
1369 *
1370 */
1371
1372/* Returns a struct hlua_map if the stack entry "ud" is
1373 * a class session, otherwise it throws an error.
1374 */
1375__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1376{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001377 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001378}
1379
1380/* This function is the map constructor. It don't need
1381 * the class Map object. It creates and return a new Map
1382 * object. It must be called only during "body" or "init"
1383 * context because it process some filesystem accesses.
1384 */
1385__LJMP static int hlua_map_new(struct lua_State *L)
1386{
1387 const char *fn;
1388 int match = PAT_MATCH_STR;
1389 struct sample_conv conv;
1390 const char *file = "";
1391 int line = 0;
1392 lua_Debug ar;
1393 char *err = NULL;
1394 struct arg args[2];
1395
1396 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1397 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1398
1399 fn = MAY_LJMP(luaL_checkstring(L, 1));
1400
1401 if (lua_gettop(L) >= 2) {
1402 match = MAY_LJMP(luaL_checkinteger(L, 2));
1403 if (match < 0 || match >= PAT_MATCH_NUM)
1404 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1405 }
1406
1407 /* Get Lua filename and line number. */
1408 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1409 lua_getinfo(L, "Sl", &ar); /* get info about it */
1410 if (ar.currentline > 0) { /* is there info? */
1411 file = ar.short_src;
1412 line = ar.currentline;
1413 }
1414 }
1415
1416 /* fill fake sample_conv struct. */
1417 conv.kw = ""; /* unused. */
1418 conv.process = NULL; /* unused. */
1419 conv.arg_mask = 0; /* unused. */
1420 conv.val_args = NULL; /* unused. */
1421 conv.out_type = SMP_T_STR;
1422 conv.private = (void *)(long)match;
1423 switch (match) {
1424 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1425 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1426 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1427 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1428 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1429 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1430 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001431 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001432 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1433 default:
1434 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1435 }
1436
1437 /* fill fake args. */
1438 args[0].type = ARGT_STR;
1439 args[0].data.str.str = (char *)fn;
1440 args[1].type = ARGT_STOP;
1441
1442 /* load the map. */
1443 if (!sample_load_map(args, &conv, file, line, &err)) {
1444 /* error case: we cant use luaL_error because we must
1445 * free the err variable.
1446 */
1447 luaL_where(L, 1);
1448 lua_pushfstring(L, "'new': %s.", err);
1449 lua_concat(L, 2);
1450 free(err);
1451 WILL_LJMP(lua_error(L));
1452 }
1453
1454 /* create the lua object. */
1455 lua_newtable(L);
1456 lua_pushlightuserdata(L, args[0].data.map);
1457 lua_rawseti(L, -2, 0);
1458
1459 /* Pop a class Map metatable and affect it to the userdata. */
1460 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1461 lua_setmetatable(L, -2);
1462
1463
1464 return 1;
1465}
1466
1467__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1468{
1469 struct map_descriptor *desc;
1470 struct pattern *pat;
1471 struct sample smp;
1472
1473 MAY_LJMP(check_args(L, 2, "lookup"));
1474 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001475 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001476 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001477 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001478 }
1479 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001480 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001481 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001482 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 +02001483 }
1484
1485 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001486 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001487 if (str)
1488 lua_pushstring(L, "");
1489 else
1490 lua_pushnil(L);
1491 return 1;
1492 }
1493
1494 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001495 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001496 return 1;
1497}
1498
1499__LJMP static int hlua_map_lookup(struct lua_State *L)
1500{
1501 return _hlua_map_lookup(L, 0);
1502}
1503
1504__LJMP static int hlua_map_slookup(struct lua_State *L)
1505{
1506 return _hlua_map_lookup(L, 1);
1507}
1508
1509/*
1510 *
1511 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001512 * Class Socket
1513 *
1514 *
1515 */
1516
1517__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1518{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001519 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001520}
1521
1522/* This function is the handler called for each I/O on the established
1523 * connection. It is used for notify space avalaible to send or data
1524 * received.
1525 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001526static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001527{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001528 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001529 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001530
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001531 /* If the connection object is not avalaible, close all the
1532 * streams and wakeup everithing waiting for.
1533 */
1534 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001535 si_shutw(si);
1536 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001537 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001538 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1539 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001540 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001541 }
1542
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001543 /* If we cant write, wakeup the pending write signals. */
1544 if (channel_output_closed(si_ic(si)))
1545 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1546
1547 /* If we cant read, wakeup the pending read signals. */
1548 if (channel_input_closed(si_oc(si)))
1549 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1550
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001551 /* if the connection is not estabkished, inform the stream that we want
1552 * to be notified whenever the connection completes.
1553 */
1554 if (!(c->flags & CO_FL_CONNECTED)) {
1555 si_applet_cant_get(si);
1556 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001557 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001558 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001559
1560 /* This function is called after the connect. */
1561 appctx->ctx.hlua.connected = 1;
1562
1563 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001564 if (channel_may_recv(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001565 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1566
1567 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001568 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001569 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1570}
1571
Willy Tarreau87b09662015-04-03 00:22:06 +02001572/* This function is called when the "struct stream" is destroyed.
1573 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001574 * Wake all the pending signals.
1575 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001576static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001577{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001578 /* Remove my link in the original object. */
1579 if (appctx->ctx.hlua.socket)
1580 appctx->ctx.hlua.socket->s = NULL;
1581
1582 /* Wake all the task waiting for me. */
1583 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1584 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1585}
1586
1587/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001588 * uses this object. If the stream does not exists, just quit.
1589 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001590 * pending signal can rest in the read and write lists. destroy
1591 * it.
1592 */
1593__LJMP static int hlua_socket_gc(lua_State *L)
1594{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001595 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001596 struct appctx *appctx;
1597
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001598 MAY_LJMP(check_args(L, 1, "__gc"));
1599
1600 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001601 if (!socket->s)
1602 return 0;
1603
Willy Tarreau87b09662015-04-03 00:22:06 +02001604 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001605 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001606 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001607 socket->s = NULL;
1608 appctx->ctx.hlua.socket = NULL;
1609
1610 return 0;
1611}
1612
1613/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001614 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001615 */
1616__LJMP static int hlua_socket_close(lua_State *L)
1617{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001618 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001619 struct appctx *appctx;
1620
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001621 MAY_LJMP(check_args(L, 1, "close"));
1622
1623 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001624 if (!socket->s)
1625 return 0;
1626
Willy Tarreau87b09662015-04-03 00:22:06 +02001627 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001628 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001629 appctx = objt_appctx(socket->s->si[0].end);
1630 appctx->ctx.hlua.socket = NULL;
1631 socket->s = NULL;
1632
1633 return 0;
1634}
1635
1636/* This Lua function assumes that the stack contain three parameters.
1637 * 1 - USERDATA containing a struct socket
1638 * 2 - INTEGER with values of the macro defined below
1639 * If the integer is -1, we must read at most one line.
1640 * If the integer is -2, we ust read all the data until the
1641 * end of the stream.
1642 * If the integer is positive value, we must read a number of
1643 * bytes corresponding to this value.
1644 */
1645#define HLSR_READ_LINE (-1)
1646#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001647__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001648{
1649 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1650 int wanted = lua_tointeger(L, 2);
1651 struct hlua *hlua = hlua_gethlua(L);
1652 struct appctx *appctx;
1653 int len;
1654 int nblk;
1655 char *blk1;
1656 int len1;
1657 char *blk2;
1658 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001659 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001660 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001661
1662 /* Check if this lua stack is schedulable. */
1663 if (!hlua || !hlua->task)
1664 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1665 "'frontend', 'backend' or 'task'"));
1666
1667 /* check for connection closed. If some data where read, return it. */
1668 if (!socket->s)
1669 goto connection_closed;
1670
Willy Tarreau94aa6172015-03-13 14:19:06 +01001671 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001672 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001673 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001674 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001675 if (nblk < 0) /* Connection close. */
1676 goto connection_closed;
1677 if (nblk == 0) /* No data avalaible. */
1678 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001679
1680 /* remove final \r\n. */
1681 if (nblk == 1) {
1682 if (blk1[len1-1] == '\n') {
1683 len1--;
1684 skip_at_end++;
1685 if (blk1[len1-1] == '\r') {
1686 len1--;
1687 skip_at_end++;
1688 }
1689 }
1690 }
1691 else {
1692 if (blk2[len2-1] == '\n') {
1693 len2--;
1694 skip_at_end++;
1695 if (blk2[len2-1] == '\r') {
1696 len2--;
1697 skip_at_end++;
1698 }
1699 }
1700 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001701 }
1702
1703 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001704 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001705 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001706 if (nblk < 0) /* Connection close. */
1707 goto connection_closed;
1708 if (nblk == 0) /* No data avalaible. */
1709 goto connection_empty;
1710 }
1711
1712 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001713 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001714 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001715 if (nblk < 0) /* Connection close. */
1716 goto connection_closed;
1717 if (nblk == 0) /* No data avalaible. */
1718 goto connection_empty;
1719
1720 if (len1 > wanted) {
1721 nblk = 1;
1722 len1 = wanted;
1723 } if (nblk == 2 && len1 + len2 > wanted)
1724 len2 = wanted - len1;
1725 }
1726
1727 len = len1;
1728
1729 luaL_addlstring(&socket->b, blk1, len1);
1730 if (nblk == 2) {
1731 len += len2;
1732 luaL_addlstring(&socket->b, blk2, len2);
1733 }
1734
1735 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001736 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001737
1738 /* Don't wait anything. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001739 stream_int_notify(&socket->s->si[0]);
1740 stream_int_update_applet(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001741
1742 /* If the pattern reclaim to read all the data
1743 * in the connection, got out.
1744 */
1745 if (wanted == HLSR_READ_ALL)
1746 goto connection_empty;
1747 else if (wanted >= 0 && len < wanted)
1748 goto connection_empty;
1749
1750 /* Return result. */
1751 luaL_pushresult(&socket->b);
1752 return 1;
1753
1754connection_closed:
1755
1756 /* If the buffer containds data. */
1757 if (socket->b.n > 0) {
1758 luaL_pushresult(&socket->b);
1759 return 1;
1760 }
1761 lua_pushnil(L);
1762 lua_pushstring(L, "connection closed.");
1763 return 2;
1764
1765connection_empty:
1766
1767 appctx = objt_appctx(socket->s->si[0].end);
1768 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1769 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001770 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001771 return 0;
1772}
1773
1774/* This Lus function gets two parameters. The first one can be string
1775 * or a number. If the string is "*l", the user require one line. If
1776 * the string is "*a", the user require all the content of the stream.
1777 * If the value is a number, the user require a number of bytes equal
1778 * to the value. The default value is "*l" (a line).
1779 *
1780 * This paraeter with a variable type is converted in integer. This
1781 * integer takes this values:
1782 * -1 : read a line
1783 * -2 : read all the stream
1784 * >0 : amount if bytes.
1785 *
1786 * The second parameter is optinal. It contains a string that must be
1787 * concatenated with the read data.
1788 */
1789__LJMP static int hlua_socket_receive(struct lua_State *L)
1790{
1791 int wanted = HLSR_READ_LINE;
1792 const char *pattern;
1793 int type;
1794 char *error;
1795 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001796 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001797
1798 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1799 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1800
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001801 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001802
1803 /* check for pattern. */
1804 if (lua_gettop(L) >= 2) {
1805 type = lua_type(L, 2);
1806 if (type == LUA_TSTRING) {
1807 pattern = lua_tostring(L, 2);
1808 if (strcmp(pattern, "*a") == 0)
1809 wanted = HLSR_READ_ALL;
1810 else if (strcmp(pattern, "*l") == 0)
1811 wanted = HLSR_READ_LINE;
1812 else {
1813 wanted = strtoll(pattern, &error, 10);
1814 if (*error != '\0')
1815 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1816 }
1817 }
1818 else if (type == LUA_TNUMBER) {
1819 wanted = lua_tointeger(L, 2);
1820 if (wanted < 0)
1821 WILL_LJMP(luaL_error(L, "Unsupported size."));
1822 }
1823 }
1824
1825 /* Set pattern. */
1826 lua_pushinteger(L, wanted);
1827 lua_replace(L, 2);
1828
1829 /* init bufffer, and fiil it wih prefix. */
1830 luaL_buffinit(L, &socket->b);
1831
1832 /* Check prefix. */
1833 if (lua_gettop(L) >= 3) {
1834 if (lua_type(L, 3) != LUA_TSTRING)
1835 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1836 pattern = lua_tolstring(L, 3, &len);
1837 luaL_addlstring(&socket->b, pattern, len);
1838 }
1839
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001840 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001841}
1842
1843/* Write the Lua input string in the output buffer.
1844 * This fucntion returns a yield if no space are available.
1845 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001846static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001847{
1848 struct hlua_socket *socket;
1849 struct hlua *hlua = hlua_gethlua(L);
1850 struct appctx *appctx;
1851 size_t buf_len;
1852 const char *buf;
1853 int len;
1854 int send_len;
1855 int sent;
1856
1857 /* Check if this lua stack is schedulable. */
1858 if (!hlua || !hlua->task)
1859 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1860 "'frontend', 'backend' or 'task'"));
1861
1862 /* Get object */
1863 socket = MAY_LJMP(hlua_checksocket(L, 1));
1864 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001865 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001866
1867 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001868 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001869 lua_pushinteger(L, -1);
1870 return 1;
1871 }
1872
1873 /* Update the input buffer data. */
1874 buf += sent;
1875 send_len = buf_len - sent;
1876
1877 /* All the data are sent. */
1878 if (sent >= buf_len)
1879 return 1; /* Implicitly return the length sent. */
1880
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001881 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1882 * the request buffer if its not required.
1883 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001884 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001885 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001886 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001887 goto hlua_socket_write_yield_return;
1888 }
1889 }
1890
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001891 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001892 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001893 if (len <= 0)
1894 goto hlua_socket_write_yield_return;
1895
1896 /* send data */
1897 if (len < send_len)
1898 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001899 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001900
1901 /* "Not enough space" (-1), "Buffer too little to contain
1902 * the data" (-2) are not expected because the available length
1903 * is tested.
1904 * Other unknown error are also not expected.
1905 */
1906 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001907 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001908 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001909
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001910 MAY_LJMP(hlua_socket_close(L));
1911 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001912 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001913 return 1;
1914 }
1915
1916 /* update buffers. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001917 stream_int_notify(&socket->s->si[0]);
1918 stream_int_update_applet(&socket->s->si[0]);
1919
Willy Tarreau94aa6172015-03-13 14:19:06 +01001920 socket->s->req.rex = TICK_ETERNITY;
1921 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001922
1923 /* Update length sent. */
1924 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001925 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001926
1927 /* All the data buffer is sent ? */
1928 if (sent + len >= buf_len)
1929 return 1;
1930
1931hlua_socket_write_yield_return:
1932 appctx = objt_appctx(socket->s->si[0].end);
1933 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1934 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001935 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001936 return 0;
1937}
1938
1939/* This function initiate the send of data. It just check the input
1940 * parameters and push an integer in the Lua stack that contain the
1941 * amount of data writed in the buffer. This is used by the function
1942 * "hlua_socket_write_yield" that can yield.
1943 *
1944 * The Lua function gets between 3 and 4 parameters. The first one is
1945 * the associated object. The second is a string buffer. The third is
1946 * a facultative integer that represents where is the buffer position
1947 * of the start of the data that can send. The first byte is the
1948 * position "1". The default value is "1". The fourth argument is a
1949 * facultative integer that represents where is the buffer position
1950 * of the end of the data that can send. The default is the last byte.
1951 */
1952static int hlua_socket_send(struct lua_State *L)
1953{
1954 int i;
1955 int j;
1956 const char *buf;
1957 size_t buf_len;
1958
1959 /* Check number of arguments. */
1960 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1961 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1962
1963 /* Get the string. */
1964 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1965
1966 /* Get and check j. */
1967 if (lua_gettop(L) == 4) {
1968 j = MAY_LJMP(luaL_checkinteger(L, 4));
1969 if (j < 0)
1970 j = buf_len + j + 1;
1971 if (j > buf_len)
1972 j = buf_len + 1;
1973 lua_pop(L, 1);
1974 }
1975 else
1976 j = buf_len;
1977
1978 /* Get and check i. */
1979 if (lua_gettop(L) == 3) {
1980 i = MAY_LJMP(luaL_checkinteger(L, 3));
1981 if (i < 0)
1982 i = buf_len + i + 1;
1983 if (i > buf_len)
1984 i = buf_len + 1;
1985 lua_pop(L, 1);
1986 } else
1987 i = 1;
1988
1989 /* Check bth i and j. */
1990 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001991 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001992 return 1;
1993 }
1994 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001995 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001996 return 1;
1997 }
1998 if (i == 0)
1999 i = 1;
2000 if (j == 0)
2001 j = 1;
2002
2003 /* Pop the string. */
2004 lua_pop(L, 1);
2005
2006 /* Update the buffer length. */
2007 buf += i - 1;
2008 buf_len = j - i + 1;
2009 lua_pushlstring(L, buf, buf_len);
2010
2011 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002012 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002013
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002014 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002015}
2016
Willy Tarreau22b0a682015-06-17 19:43:49 +02002017#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002018__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2019{
2020 static char buffer[SOCKET_INFO_MAX_LEN];
2021 int ret;
2022 int len;
2023 char *p;
2024
2025 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2026 if (ret <= 0) {
2027 lua_pushnil(L);
2028 return 1;
2029 }
2030
2031 if (ret == AF_UNIX) {
2032 lua_pushstring(L, buffer+1);
2033 return 1;
2034 }
2035 else if (ret == AF_INET6) {
2036 buffer[0] = '[';
2037 len = strlen(buffer);
2038 buffer[len] = ']';
2039 len++;
2040 buffer[len] = ':';
2041 len++;
2042 p = buffer;
2043 }
2044 else if (ret == AF_INET) {
2045 p = buffer + 1;
2046 len = strlen(p);
2047 p[len] = ':';
2048 len++;
2049 }
2050 else {
2051 lua_pushnil(L);
2052 return 1;
2053 }
2054
2055 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2056 lua_pushnil(L);
2057 return 1;
2058 }
2059
2060 lua_pushstring(L, p);
2061 return 1;
2062}
2063
2064/* Returns information about the peer of the connection. */
2065__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2066{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002067 struct hlua_socket *socket;
2068 struct connection *conn;
2069
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002070 MAY_LJMP(check_args(L, 1, "getpeername"));
2071
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002072 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002073
2074 /* Check if the tcp object is avalaible. */
2075 if (!socket->s) {
2076 lua_pushnil(L);
2077 return 1;
2078 }
2079
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002080 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002081 if (!conn) {
2082 lua_pushnil(L);
2083 return 1;
2084 }
2085
2086 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
2087 unsigned int salen = sizeof(conn->addr.to);
2088 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
2089 lua_pushnil(L);
2090 return 1;
2091 }
2092 conn->flags |= CO_FL_ADDR_TO_SET;
2093 }
2094
2095 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2096}
2097
2098/* Returns information about my connection side. */
2099static int hlua_socket_getsockname(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, "getsockname"));
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_FROM_SET)) {
2121 unsigned int salen = sizeof(conn->addr.from);
2122 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2123 lua_pushnil(L);
2124 return 1;
2125 }
2126 conn->flags |= CO_FL_ADDR_FROM_SET;
2127 }
2128
2129 return hlua_socket_info(L, &conn->addr.from);
2130}
2131
2132/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002133static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002134 .obj_type = OBJ_TYPE_APPLET,
2135 .name = "<LUA_TCP>",
2136 .fct = hlua_socket_handler,
2137 .release = hlua_socket_release,
2138};
2139
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002140__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002141{
2142 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2143 struct hlua *hlua = hlua_gethlua(L);
2144 struct appctx *appctx;
2145
2146 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002147 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002148 lua_pushnil(L);
2149 lua_pushstring(L, "Can't connect");
2150 return 2;
2151 }
2152
2153 appctx = objt_appctx(socket->s->si[0].end);
2154
2155 /* Check for connection established. */
2156 if (appctx->ctx.hlua.connected) {
2157 lua_pushinteger(L, 1);
2158 return 1;
2159 }
2160
2161 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2162 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002163 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002164 return 0;
2165}
2166
2167/* This function fail or initite the connection. */
2168__LJMP static int hlua_socket_connect(struct lua_State *L)
2169{
2170 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002171 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002172 const char *ip;
2173 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002174 struct hlua *hlua;
2175 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002176 int low, high;
2177 struct sockaddr_storage *addr;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002178
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002179 if (lua_gettop(L) < 2)
2180 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002181
2182 /* Get args. */
2183 socket = MAY_LJMP(hlua_checksocket(L, 1));
2184 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002185 if (lua_gettop(L) >= 3)
2186 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002187
Willy Tarreau973a5422015-08-05 21:47:23 +02002188 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002189 if (!conn)
2190 WILL_LJMP(luaL_error(L, "connect: internal error"));
2191
Willy Tarreau3adac082015-09-26 17:51:09 +02002192 /* needed for the connection not to be closed */
2193 conn->target = socket->s->target;
2194
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002195 /* Parse ip address. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002196 addr = str2sa_range(ip, &low, &high, NULL, NULL, NULL, 0);
2197 if (!addr)
2198 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
2199 if (low != high)
2200 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
2201 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002202
2203 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002204 if (low == 0) {
2205 if (conn->addr.to.ss_family == AF_INET) {
2206 if (port == -1)
2207 WILL_LJMP(luaL_error(L, "connect: port missing"));
2208 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2209 } else if (conn->addr.to.ss_family == AF_INET6) {
2210 if (port == -1)
2211 WILL_LJMP(luaL_error(L, "connect: port missing"));
2212 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2213 }
2214 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002215
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002216 hlua = hlua_gethlua(L);
2217 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002218
2219 /* inform the stream that we want to be notified whenever the
2220 * connection completes.
2221 */
2222 si_applet_cant_get(&socket->s->si[0]);
2223 si_applet_cant_put(&socket->s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002224 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002225
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002226 hlua->flags |= HLUA_MUST_GC;
2227
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002228 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2229 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002230 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002231
2232 return 0;
2233}
2234
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002235#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002236__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2237{
2238 struct hlua_socket *socket;
2239
2240 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2241 socket = MAY_LJMP(hlua_checksocket(L, 1));
2242 socket->s->target = &socket_ssl.obj_type;
2243 return MAY_LJMP(hlua_socket_connect(L));
2244}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002245#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002246
2247__LJMP static int hlua_socket_setoption(struct lua_State *L)
2248{
2249 return 0;
2250}
2251
2252__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2253{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002254 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002255 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002256
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002257 MAY_LJMP(check_args(L, 2, "settimeout"));
2258
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002259 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002260 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002261
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002262 socket->s->req.rto = tmout;
2263 socket->s->req.wto = tmout;
2264 socket->s->res.rto = tmout;
2265 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002266
2267 return 0;
2268}
2269
2270__LJMP static int hlua_socket_new(lua_State *L)
2271{
2272 struct hlua_socket *socket;
2273 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002274 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002275 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002276 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002277
2278 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002279 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002280 hlua_pusherror(L, "socket: full stack");
2281 goto out_fail_conf;
2282 }
2283
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002284 /* Create the object: obj[0] = userdata. */
2285 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002286 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002287 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002288 memset(socket, 0, sizeof(*socket));
2289
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002290 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002291 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002292 hlua_pusherror(L, "socket: uninitialized pools.");
2293 goto out_fail_conf;
2294 }
2295
Willy Tarreau87b09662015-04-03 00:22:06 +02002296 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002297 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2298 lua_setmetatable(L, -2);
2299
Willy Tarreaud420a972015-04-06 00:39:18 +02002300 /* Create the applet context */
2301 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002302 if (!appctx) {
2303 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002304 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002305 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002306
Willy Tarreaud420a972015-04-06 00:39:18 +02002307 appctx->ctx.hlua.socket = socket;
2308 appctx->ctx.hlua.connected = 0;
2309 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2310 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002311
Willy Tarreaud420a972015-04-06 00:39:18 +02002312 /* Now create a session, task and stream for this applet */
2313 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2314 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002315 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002316 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002317 }
2318
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002319 task = task_new();
2320 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002322 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002324 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002325
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002326 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002327 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002328 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002329 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002330 }
2331
Willy Tarreaud420a972015-04-06 00:39:18 +02002332 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002333 socket->s = strm;
2334 strm->hlua.T = NULL;
2335 strm->hlua.Tref = LUA_REFNIL;
2336 strm->hlua.Mref = LUA_REFNIL;
2337 strm->hlua.nargs = 0;
2338 strm->hlua.flags = 0;
2339 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002340
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002341 /* Configure "right" stream interface. this "si" is used to connect
2342 * and retrieve data from the server. The connection is initialized
2343 * with the "struct server".
2344 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002345 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002346
2347 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002348 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2349 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002350
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002351 /* Update statistics counters. */
2352 socket_proxy.feconn++; /* beconn will be increased later */
2353 jobs++;
2354 totalconn++;
2355
2356 /* Return yield waiting for connection. */
2357 return 1;
2358
Willy Tarreaud420a972015-04-06 00:39:18 +02002359 out_fail_stream:
2360 task_free(task);
2361 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002362 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002363 out_fail_sess:
2364 appctx_free(appctx);
2365 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002366 WILL_LJMP(lua_error(L));
2367 return 0;
2368}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002369
2370/*
2371 *
2372 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002373 * Class Channel
2374 *
2375 *
2376 */
2377
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002378/* The state between the channel data and the HTTP parser state can be
2379 * unconsistent, so reset the parser and call it again. Warning, this
2380 * action not revalidate the request and not send a 400 if the modified
2381 * resuest is not valid.
2382 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002383 * This function never fails. The direction is set using dir, which equals
2384 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002385 */
2386static void hlua_resynchonize_proto(struct stream *stream, int dir)
2387{
2388 /* Protocol HTTP. */
2389 if (stream->be->mode == PR_MODE_HTTP) {
2390
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002391 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002392 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002393 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002394 http_txn_reset_res(stream->txn);
2395
2396 if (stream->txn->hdr_idx.v)
2397 hdr_idx_init(&stream->txn->hdr_idx);
2398
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002399 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002400 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002401 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002402 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2403 }
2404}
2405
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002406/* Check the protocole integrity after the Lua manipulations. Close the stream
2407 * and returns 0 if fails, otherwise returns 1. The direction is set using dir,
2408 * which equals either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002409 */
2410static int hlua_check_proto(struct stream *stream, int dir)
2411{
2412 const struct chunk msg = { .len = 0 };
2413
Willy Tarreau9af89f72015-09-26 11:50:08 +02002414 /* Protocol HTTP. The message parsing state must match the request or
2415 * response state. The problem that may happen is that Lua modifies
2416 * the request or response message *after* it was parsed, and corrupted
2417 * it so that it could not be processed anymore. We just need to verify
2418 * if the parser is still expected to run or not.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002419 */
2420 if (stream->be->mode == PR_MODE_HTTP) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002421 if (dir == SMP_OPT_DIR_REQ &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002422 !(stream->req.analysers & AN_REQ_WAIT_HTTP) &&
2423 stream->txn->req.msg_state < HTTP_MSG_BODY) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002424 stream_int_retnclose(&stream->si[0], &msg);
2425 return 0;
2426 }
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002427 else if (dir == SMP_OPT_DIR_RES &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002428 !(stream->res.analysers & AN_RES_WAIT_HTTP) &&
2429 stream->txn->rsp.msg_state < HTTP_MSG_BODY) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002430 stream_int_retnclose(&stream->si[0], &msg);
2431 return 0;
2432 }
2433 }
2434 return 1;
2435}
2436
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002437/* Returns the struct hlua_channel join to the class channel in the
2438 * stack entry "ud" or throws an argument error.
2439 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002440__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002441{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002442 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002443}
2444
Willy Tarreau47860ed2015-03-10 14:07:50 +01002445/* Pushes the channel onto the top of the stack. If the stask does not have a
2446 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002447 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002448static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002449{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002450 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002451 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002452 return 0;
2453
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002454 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002455 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002456 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002457
2458 /* Pop a class sesison metatable and affect it to the userdata. */
2459 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2460 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002461 return 1;
2462}
2463
2464/* Duplicate all the data present in the input channel and put it
2465 * in a string LUA variables. Returns -1 and push a nil value in
2466 * the stack if the channel is closed and all the data are consumed,
2467 * returns 0 if no data are available, otherwise it returns the length
2468 * of the builded string.
2469 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002470static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002471{
2472 char *blk1;
2473 char *blk2;
2474 int len1;
2475 int len2;
2476 int ret;
2477 luaL_Buffer b;
2478
Willy Tarreau47860ed2015-03-10 14:07:50 +01002479 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002480 if (unlikely(ret == 0))
2481 return 0;
2482
2483 if (unlikely(ret < 0)) {
2484 lua_pushnil(L);
2485 return -1;
2486 }
2487
2488 luaL_buffinit(L, &b);
2489 luaL_addlstring(&b, blk1, len1);
2490 if (unlikely(ret == 2))
2491 luaL_addlstring(&b, blk2, len2);
2492 luaL_pushresult(&b);
2493
2494 if (unlikely(ret == 2))
2495 return len1 + len2;
2496 return len1;
2497}
2498
2499/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2500 * a yield. This function keep the data in the buffer.
2501 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002502__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002503{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002504 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002505
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002506 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2507
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002508 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002509 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002510 return 1;
2511}
2512
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002513/* Check arguments for the function "hlua_channel_dup_yield". */
2514__LJMP static int hlua_channel_dup(lua_State *L)
2515{
2516 MAY_LJMP(check_args(L, 1, "dup"));
2517 MAY_LJMP(hlua_checkchannel(L, 1));
2518 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2519}
2520
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002521/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2522 * a yield. This function consumes the data in the buffer. It returns
2523 * a string containing the data or a nil pointer if no data are available
2524 * and the channel is closed.
2525 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002526__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002527{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002528 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002529 int ret;
2530
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002531 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002532
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002533 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002534 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002535 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002536
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002537 if (unlikely(ret == -1))
2538 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002539
Willy Tarreau47860ed2015-03-10 14:07:50 +01002540 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002541 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002542 return 1;
2543}
2544
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002545/* Check arguments for the fucntion "hlua_channel_get_yield". */
2546__LJMP static int hlua_channel_get(lua_State *L)
2547{
2548 MAY_LJMP(check_args(L, 1, "get"));
2549 MAY_LJMP(hlua_checkchannel(L, 1));
2550 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2551}
2552
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002553/* This functions consumes and returns one line. If the channel is closed,
2554 * and the last data does not contains a final '\n', the data are returned
2555 * without the final '\n'. When no more data are avalaible, it returns nil
2556 * value.
2557 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002558__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002559{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002560 char *blk1;
2561 char *blk2;
2562 int len1;
2563 int len2;
2564 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002565 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002566 int ret;
2567 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002568
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002569 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2570
Willy Tarreau47860ed2015-03-10 14:07:50 +01002571 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002572 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002573 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002574
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002575 if (ret == -1) {
2576 lua_pushnil(L);
2577 return 1;
2578 }
2579
2580 luaL_buffinit(L, &b);
2581 luaL_addlstring(&b, blk1, len1);
2582 len = len1;
2583 if (unlikely(ret == 2)) {
2584 luaL_addlstring(&b, blk2, len2);
2585 len += len2;
2586 }
2587 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002588 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002589 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002590 return 1;
2591}
2592
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002593/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2594__LJMP static int hlua_channel_getline(lua_State *L)
2595{
2596 MAY_LJMP(check_args(L, 1, "getline"));
2597 MAY_LJMP(hlua_checkchannel(L, 1));
2598 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2599}
2600
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002601/* This function takes a string as input, and append it at the
2602 * input side of channel. If the data is too big, but a space
2603 * is probably available after sending some data, the function
2604 * yield. If the data is bigger than the buffer, or if the
2605 * channel is closed, it returns -1. otherwise, it returns the
2606 * amount of data writed.
2607 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002608__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002609{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002610 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002611 size_t len;
2612 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2613 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2614 int ret;
2615 int max;
2616
Willy Tarreau47860ed2015-03-10 14:07:50 +01002617 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002618 if (max > len - l)
2619 max = len - l;
2620
Willy Tarreau47860ed2015-03-10 14:07:50 +01002621 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002622 if (ret == -2 || ret == -3) {
2623 lua_pushinteger(L, -1);
2624 return 1;
2625 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002626 if (ret == -1) {
2627 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002628 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002629 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002630 l += ret;
2631 lua_pop(L, 1);
2632 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002633 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002634
Willy Tarreau47860ed2015-03-10 14:07:50 +01002635 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2636 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002637 /* There are no space avalaible, and the output buffer is empty.
2638 * in this case, we cannot add more data, so we cannot yield,
2639 * we return the amount of copyied data.
2640 */
2641 return 1;
2642 }
2643 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002644 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002645 return 1;
2646}
2647
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002648/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002649 * of the writed string, or -1 if the channel is closed or if the
2650 * buffer size is too little for the data.
2651 */
2652__LJMP static int hlua_channel_append(lua_State *L)
2653{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002654 size_t len;
2655
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002656 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002657 MAY_LJMP(hlua_checkchannel(L, 1));
2658 MAY_LJMP(luaL_checklstring(L, 2, &len));
2659 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002660 lua_pushinteger(L, 0);
2661
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002662 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002663}
2664
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002665/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002666 * his process by cleaning the buffer. The result is a replacement
2667 * of the current data. It returns the length of the writed string,
2668 * or -1 if the channel is closed or if the buffer size is too
2669 * little for the data.
2670 */
2671__LJMP static int hlua_channel_set(lua_State *L)
2672{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002673 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002674
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002675 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002676 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002677 lua_pushinteger(L, 0);
2678
Willy Tarreau47860ed2015-03-10 14:07:50 +01002679 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002680
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002681 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002682}
2683
2684/* Append data in the output side of the buffer. This data is immediatly
2685 * sent. The fcuntion returns the ammount of data writed. If the buffer
2686 * cannot contains the data, the function yield. The function returns -1
2687 * if the channel is closed.
2688 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002689__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002690{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002691 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002692 size_t len;
2693 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2694 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2695 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002696 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002697
Willy Tarreau47860ed2015-03-10 14:07:50 +01002698 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002699 lua_pushinteger(L, -1);
2700 return 1;
2701 }
2702
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002703 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2704 * the request buffer if its not required.
2705 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002706 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002707 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002708 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002709 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002710 }
2711 }
2712
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002713 /* the writed data will be immediatly sent, so we can check
2714 * the avalaible space without taking in account the reserve.
2715 * The reserve is guaranted for the processing of incoming
2716 * data, because the buffer will be flushed.
2717 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002718 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002719
2720 /* If there are no space avalaible, and the output buffer is empty.
2721 * in this case, we cannot add more data, so we cannot yield,
2722 * we return the amount of copyied data.
2723 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002724 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002725 return 1;
2726
2727 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002728 if (max > len - l)
2729 max = len - l;
2730
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002731 /* The buffer avalaible size may be not contiguous. This test
2732 * detects a non contiguous buffer and realign it.
2733 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002734 if (bi_space_for_replace(chn->buf) < max)
2735 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002736
2737 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002738 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002739
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002740 /* buffer replace considers that the input part is filled.
2741 * so, I must forward these new data in the output part.
2742 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002743 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002744
2745 l += max;
2746 lua_pop(L, 1);
2747 lua_pushinteger(L, l);
2748
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002749 /* If there are no space avalaible, and the output buffer is empty.
2750 * in this case, we cannot add more data, so we cannot yield,
2751 * we return the amount of copyied data.
2752 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002753 max = chn->buf->size - buffer_len(chn->buf);
2754 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002755 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002756
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002757 if (l < len) {
2758 /* If we are waiting for space in the response buffer, we
2759 * must set the flag WAKERESWR. This flag required the task
2760 * wake up if any activity is detected on the response buffer.
2761 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002762 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002763 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002764 else
2765 HLUA_SET_WAKEREQWR(hlua);
2766 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002767 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002768
2769 return 1;
2770}
2771
2772/* Just a wraper of "_hlua_channel_send". This wrapper permits
2773 * yield the LUA process, and resume it without checking the
2774 * input arguments.
2775 */
2776__LJMP static int hlua_channel_send(lua_State *L)
2777{
2778 MAY_LJMP(check_args(L, 2, "send"));
2779 lua_pushinteger(L, 0);
2780
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002781 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002782}
2783
2784/* This function forward and amount of butes. The data pass from
2785 * the input side of the buffer to the output side, and can be
2786 * forwarded. This function never fails.
2787 *
2788 * The Lua function takes an amount of bytes to be forwarded in
2789 * imput. It returns the number of bytes forwarded.
2790 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002791__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002792{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002793 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002794 int len;
2795 int l;
2796 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002797 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002798
2799 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2800 len = MAY_LJMP(luaL_checkinteger(L, 2));
2801 l = MAY_LJMP(luaL_checkinteger(L, -1));
2802
2803 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002804 if (max > chn->buf->i)
2805 max = chn->buf->i;
2806 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002807 l += max;
2808
2809 lua_pop(L, 1);
2810 lua_pushinteger(L, l);
2811
2812 /* Check if it miss bytes to forward. */
2813 if (l < len) {
2814 /* The the input channel or the output channel are closed, we
2815 * must return the amount of data forwarded.
2816 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002817 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002818 return 1;
2819
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002820 /* If we are waiting for space data in the response buffer, we
2821 * must set the flag WAKERESWR. This flag required the task
2822 * wake up if any activity is detected on the response buffer.
2823 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002824 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002825 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002826 else
2827 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002828
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002829 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002830 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002831 }
2832
2833 return 1;
2834}
2835
2836/* Just check the input and prepare the stack for the previous
2837 * function "hlua_channel_forward_yield"
2838 */
2839__LJMP static int hlua_channel_forward(lua_State *L)
2840{
2841 MAY_LJMP(check_args(L, 2, "forward"));
2842 MAY_LJMP(hlua_checkchannel(L, 1));
2843 MAY_LJMP(luaL_checkinteger(L, 2));
2844
2845 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002846 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002847}
2848
2849/* Just returns the number of bytes available in the input
2850 * side of the buffer. This function never fails.
2851 */
2852__LJMP static int hlua_channel_get_in_len(lua_State *L)
2853{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002854 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002855
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002856 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002857 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002858 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002859 return 1;
2860}
2861
2862/* Just returns the number of bytes available in the output
2863 * side of the buffer. This function never fails.
2864 */
2865__LJMP static int hlua_channel_get_out_len(lua_State *L)
2866{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002867 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002868
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002869 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002870 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002871 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002872 return 1;
2873}
2874
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002875/*
2876 *
2877 *
2878 * Class Fetches
2879 *
2880 *
2881 */
2882
2883/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002884 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002885 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002886__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002887{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002888 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002889}
2890
2891/* This function creates and push in the stack a fetch object according
2892 * with a current TXN.
2893 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002894static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002895{
Willy Tarreau7073c472015-04-06 11:15:40 +02002896 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002897
2898 /* Check stack size. */
2899 if (!lua_checkstack(L, 3))
2900 return 0;
2901
2902 /* Create the object: obj[0] = userdata.
2903 * Note that the base of the Fetches object is the
2904 * transaction object.
2905 */
2906 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002907 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002908 lua_rawseti(L, -2, 0);
2909
Willy Tarreau7073c472015-04-06 11:15:40 +02002910 hsmp->s = txn->s;
2911 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01002912 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002913 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002914
2915 /* Pop a class sesison metatable and affect it to the userdata. */
2916 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2917 lua_setmetatable(L, -2);
2918
2919 return 1;
2920}
2921
2922/* This function is an LUA binding. It is called with each sample-fetch.
2923 * It uses closure argument to store the associated sample-fetch. It
2924 * returns only one argument or throws an error. An error is thrown
2925 * only if an error is encountered during the argument parsing. If
2926 * the "sample-fetch" function fails, nil is returned.
2927 */
2928__LJMP static int hlua_run_sample_fetch(lua_State *L)
2929{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002930 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002931 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002932 struct arg args[ARGM_NBARGS + 1];
2933 int i;
2934 struct sample smp;
2935
2936 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002937 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002938
2939 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002940 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002941
Thierry FOURNIERca988662015-12-20 18:43:03 +01002942 /* Check execution authorization. */
2943 if (f->use & SMP_USE_HTTP_ANY &&
2944 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
2945 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
2946 "is not available in Lua services", f->kw);
2947 WILL_LJMP(lua_error(L));
2948 }
2949
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002950 /* Get extra arguments. */
2951 for (i = 0; i < lua_gettop(L) - 1; i++) {
2952 if (i >= ARGM_NBARGS)
2953 break;
2954 hlua_lua2arg(L, i + 2, &args[i]);
2955 }
2956 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01002957 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002958
2959 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002960 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002961
2962 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002963 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002964 lua_pushfstring(L, "error in arguments");
2965 WILL_LJMP(lua_error(L));
2966 }
2967
2968 /* Initialise the sample. */
2969 memset(&smp, 0, sizeof(smp));
2970
2971 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01002972 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02002973 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002974 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002975 lua_pushstring(L, "");
2976 else
2977 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002978 return 1;
2979 }
2980
2981 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002982 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002983 hlua_smp2lua_str(L, &smp);
2984 else
2985 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002986 return 1;
2987}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002988
2989/*
2990 *
2991 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002992 * Class Converters
2993 *
2994 *
2995 */
2996
2997/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002998 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002999 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003000__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003001{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003002 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003003}
3004
3005/* This function creates and push in the stack a Converters object
3006 * according with a current TXN.
3007 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003008static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003009{
Willy Tarreau7073c472015-04-06 11:15:40 +02003010 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003011
3012 /* Check stack size. */
3013 if (!lua_checkstack(L, 3))
3014 return 0;
3015
3016 /* Create the object: obj[0] = userdata.
3017 * Note that the base of the Converters object is the
3018 * same than the TXN object.
3019 */
3020 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003021 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003022 lua_rawseti(L, -2, 0);
3023
Willy Tarreau7073c472015-04-06 11:15:40 +02003024 hsmp->s = txn->s;
3025 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003026 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003027 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003028
Willy Tarreau87b09662015-04-03 00:22:06 +02003029 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003030 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3031 lua_setmetatable(L, -2);
3032
3033 return 1;
3034}
3035
3036/* This function is an LUA binding. It is called with each converter.
3037 * It uses closure argument to store the associated converter. It
3038 * returns only one argument or throws an error. An error is thrown
3039 * only if an error is encountered during the argument parsing. If
3040 * the converter function function fails, nil is returned.
3041 */
3042__LJMP static int hlua_run_sample_conv(lua_State *L)
3043{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003044 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003045 struct sample_conv *conv;
3046 struct arg args[ARGM_NBARGS + 1];
3047 int i;
3048 struct sample smp;
3049
3050 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003051 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003052
3053 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003054 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003055
3056 /* Get extra arguments. */
3057 for (i = 0; i < lua_gettop(L) - 2; i++) {
3058 if (i >= ARGM_NBARGS)
3059 break;
3060 hlua_lua2arg(L, i + 3, &args[i]);
3061 }
3062 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003063 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003064
3065 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003066 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003067
3068 /* Run the special args checker. */
3069 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3070 hlua_pusherror(L, "error in arguments");
3071 WILL_LJMP(lua_error(L));
3072 }
3073
3074 /* Initialise the sample. */
3075 if (!hlua_lua2smp(L, 2, &smp)) {
3076 hlua_pusherror(L, "error in the input argument");
3077 WILL_LJMP(lua_error(L));
3078 }
3079
Willy Tarreau1777ea62016-03-10 16:15:46 +01003080 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3081
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003082 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003083 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003084 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003085 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003086 WILL_LJMP(lua_error(L));
3087 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003088 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3089 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003090 hlua_pusherror(L, "error during the input argument casting");
3091 WILL_LJMP(lua_error(L));
3092 }
3093
3094 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003095 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003096 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003097 lua_pushstring(L, "");
3098 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003099 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003100 return 1;
3101 }
3102
3103 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003104 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003105 hlua_smp2lua_str(L, &smp);
3106 else
3107 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003108 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003109}
3110
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003111/*
3112 *
3113 *
3114 * Class AppletTCP
3115 *
3116 *
3117 */
3118
3119/* Returns a struct hlua_txn if the stack entry "ud" is
3120 * a class stream, otherwise it throws an error.
3121 */
3122__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3123{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003124 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003125}
3126
3127/* This function creates and push in the stack an Applet object
3128 * according with a current TXN.
3129 */
3130static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3131{
3132 struct hlua_appctx *appctx;
3133 struct stream_interface *si = ctx->owner;
3134 struct stream *s = si_strm(si);
3135 struct proxy *p = s->be;
3136
3137 /* Check stack size. */
3138 if (!lua_checkstack(L, 3))
3139 return 0;
3140
3141 /* Create the object: obj[0] = userdata.
3142 * Note that the base of the Converters object is the
3143 * same than the TXN object.
3144 */
3145 lua_newtable(L);
3146 appctx = lua_newuserdata(L, sizeof(*appctx));
3147 lua_rawseti(L, -2, 0);
3148 appctx->appctx = ctx;
3149 appctx->htxn.s = s;
3150 appctx->htxn.p = p;
3151
3152 /* Create the "f" field that contains a list of fetches. */
3153 lua_pushstring(L, "f");
3154 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3155 return 0;
3156 lua_settable(L, -3);
3157
3158 /* Create the "sf" field that contains a list of stringsafe fetches. */
3159 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003160 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003161 return 0;
3162 lua_settable(L, -3);
3163
3164 /* Create the "c" field that contains a list of converters. */
3165 lua_pushstring(L, "c");
3166 if (!hlua_converters_new(L, &appctx->htxn, 0))
3167 return 0;
3168 lua_settable(L, -3);
3169
3170 /* Create the "sc" field that contains a list of stringsafe converters. */
3171 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003172 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003173 return 0;
3174 lua_settable(L, -3);
3175
3176 /* Pop a class stream metatable and affect it to the table. */
3177 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3178 lua_setmetatable(L, -2);
3179
3180 return 1;
3181}
3182
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003183__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3184{
3185 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3186 struct stream *s = appctx->htxn.s;
3187 struct hlua *hlua = &s->hlua;
3188
3189 MAY_LJMP(check_args(L, 2, "set_priv"));
3190
3191 /* Remove previous value. */
3192 if (hlua->Mref != -1)
3193 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3194
3195 /* Get and store new value. */
3196 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3197 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3198
3199 return 0;
3200}
3201
3202__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3203{
3204 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3205 struct stream *s = appctx->htxn.s;
3206 struct hlua *hlua = &s->hlua;
3207
3208 /* Push configuration index in the stack. */
3209 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3210
3211 return 1;
3212}
3213
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003214/* If expected data not yet available, it returns a yield. This function
3215 * consumes the data in the buffer. It returns a string containing the
3216 * data. This string can be empty.
3217 */
3218__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3219{
3220 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3221 struct stream_interface *si = appctx->appctx->owner;
3222 int ret;
3223 char *blk1;
3224 int len1;
3225 char *blk2;
3226 int len2;
3227
3228 /* Read the maximum amount of data avalaible. */
3229 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3230
3231 /* Data not yet avalaible. return yield. */
3232 if (ret == 0) {
3233 si_applet_cant_get(si);
3234 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3235 }
3236
3237 /* End of data: commit the total strings and return. */
3238 if (ret < 0) {
3239 luaL_pushresult(&appctx->b);
3240 return 1;
3241 }
3242
3243 /* Ensure that the block 2 length is usable. */
3244 if (ret == 1)
3245 len2 = 0;
3246
3247 /* dont check the max length read and dont check. */
3248 luaL_addlstring(&appctx->b, blk1, len1);
3249 luaL_addlstring(&appctx->b, blk2, len2);
3250
3251 /* Consume input channel output buffer data. */
3252 bo_skip(si_oc(si), len1 + len2);
3253 luaL_pushresult(&appctx->b);
3254 return 1;
3255}
3256
3257/* Check arguments for the fucntion "hlua_channel_get_yield". */
3258__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3259{
3260 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3261
3262 /* Initialise the string catenation. */
3263 luaL_buffinit(L, &appctx->b);
3264
3265 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3266}
3267
3268/* If expected data not yet available, it returns a yield. This function
3269 * consumes the data in the buffer. It returns a string containing the
3270 * data. This string can be empty.
3271 */
3272__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3273{
3274 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3275 struct stream_interface *si = appctx->appctx->owner;
3276 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3277 int ret;
3278 char *blk1;
3279 int len1;
3280 char *blk2;
3281 int len2;
3282
3283 /* Read the maximum amount of data avalaible. */
3284 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3285
3286 /* Data not yet avalaible. return yield. */
3287 if (ret == 0) {
3288 si_applet_cant_get(si);
3289 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3290 }
3291
3292 /* End of data: commit the total strings and return. */
3293 if (ret < 0) {
3294 luaL_pushresult(&appctx->b);
3295 return 1;
3296 }
3297
3298 /* Ensure that the block 2 length is usable. */
3299 if (ret == 1)
3300 len2 = 0;
3301
3302 if (len == -1) {
3303
3304 /* If len == -1, catenate all the data avalaile and
3305 * yield because we want to get all the data until
3306 * the end of data stream.
3307 */
3308 luaL_addlstring(&appctx->b, blk1, len1);
3309 luaL_addlstring(&appctx->b, blk2, len2);
3310 bo_skip(si_oc(si), len1 + len2);
3311 si_applet_cant_get(si);
3312 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3313
3314 } else {
3315
3316 /* Copy the fisrt block caping to the length required. */
3317 if (len1 > len)
3318 len1 = len;
3319 luaL_addlstring(&appctx->b, blk1, len1);
3320 len -= len1;
3321
3322 /* Copy the second block. */
3323 if (len2 > len)
3324 len2 = len;
3325 luaL_addlstring(&appctx->b, blk2, len2);
3326 len -= len2;
3327
3328 /* Consume input channel output buffer data. */
3329 bo_skip(si_oc(si), len1 + len2);
3330
3331 /* If we are no other data avalaible, yield waiting for new data. */
3332 if (len > 0) {
3333 lua_pushinteger(L, len);
3334 lua_replace(L, 2);
3335 si_applet_cant_get(si);
3336 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3337 }
3338
3339 /* return the result. */
3340 luaL_pushresult(&appctx->b);
3341 return 1;
3342 }
3343
3344 /* we never executes this */
3345 hlua_pusherror(L, "Lua: internal error");
3346 WILL_LJMP(lua_error(L));
3347 return 0;
3348}
3349
3350/* Check arguments for the fucntion "hlua_channel_get_yield". */
3351__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3352{
3353 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3354 int len = -1;
3355
3356 if (lua_gettop(L) > 2)
3357 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3358 if (lua_gettop(L) >= 2) {
3359 len = MAY_LJMP(luaL_checkinteger(L, 2));
3360 lua_pop(L, 1);
3361 }
3362
3363 /* Confirm or set the required length */
3364 lua_pushinteger(L, len);
3365
3366 /* Initialise the string catenation. */
3367 luaL_buffinit(L, &appctx->b);
3368
3369 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3370}
3371
3372/* Append data in the output side of the buffer. This data is immediatly
3373 * sent. The fcuntion returns the ammount of data writed. If the buffer
3374 * cannot contains the data, the function yield. The function returns -1
3375 * if the channel is closed.
3376 */
3377__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3378{
3379 size_t len;
3380 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3381 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3382 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3383 struct stream_interface *si = appctx->appctx->owner;
3384 struct channel *chn = si_ic(si);
3385 int max;
3386
3387 /* Get the max amount of data which can write as input in the channel. */
3388 max = channel_recv_max(chn);
3389 if (max > (len - l))
3390 max = len - l;
3391
3392 /* Copy data. */
3393 bi_putblk(chn, str + l, max);
3394
3395 /* update counters. */
3396 l += max;
3397 lua_pop(L, 1);
3398 lua_pushinteger(L, l);
3399
3400 /* If some data is not send, declares the situation to the
3401 * applet, and returns a yield.
3402 */
3403 if (l < len) {
3404 si_applet_cant_put(si);
3405 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3406 }
3407
3408 return 1;
3409}
3410
3411/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3412 * yield the LUA process, and resume it without checking the
3413 * input arguments.
3414 */
3415__LJMP static int hlua_applet_tcp_send(lua_State *L)
3416{
3417 MAY_LJMP(check_args(L, 2, "send"));
3418 lua_pushinteger(L, 0);
3419
3420 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3421}
3422
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003423/*
3424 *
3425 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003426 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003427 *
3428 *
3429 */
3430
3431/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003432 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003433 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003434__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003435{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003436 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003437}
3438
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003439/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003440 * according with a current TXN.
3441 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003442static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003443{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003444 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003445 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003446 struct stream_interface *si = ctx->owner;
3447 struct stream *s = si_strm(si);
3448 struct proxy *px = s->be;
3449 struct http_txn *txn = s->txn;
3450 const char *path;
3451 const char *end;
3452 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003453
3454 /* Check stack size. */
3455 if (!lua_checkstack(L, 3))
3456 return 0;
3457
3458 /* Create the object: obj[0] = userdata.
3459 * Note that the base of the Converters object is the
3460 * same than the TXN object.
3461 */
3462 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003463 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003464 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003465 appctx->appctx = ctx;
3466 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
3467 appctx->htxn.s = s;
3468 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003469
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003470 /* Create the "f" field that contains a list of fetches. */
3471 lua_pushstring(L, "f");
3472 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3473 return 0;
3474 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003475
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003476 /* Create the "sf" field that contains a list of stringsafe fetches. */
3477 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003478 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003479 return 0;
3480 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003481
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003482 /* Create the "c" field that contains a list of converters. */
3483 lua_pushstring(L, "c");
3484 if (!hlua_converters_new(L, &appctx->htxn, 0))
3485 return 0;
3486 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003487
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003488 /* Create the "sc" field that contains a list of stringsafe converters. */
3489 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003490 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003491 return 0;
3492 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003493
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003494 /* Stores the request method. */
3495 lua_pushstring(L, "method");
3496 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3497 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003498
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003499 /* Stores the http version. */
3500 lua_pushstring(L, "version");
3501 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3502 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003503
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003504 /* creates an array of headers. hlua_http_get_headers() crates and push
3505 * the array on the top of the stack.
3506 */
3507 lua_pushstring(L, "headers");
3508 htxn.s = s;
3509 htxn.p = px;
3510 htxn.dir = SMP_OPT_DIR_REQ;
3511 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3512 return 0;
3513 lua_settable(L, -3);
3514
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003515 /* Get path and qs */
3516 path = http_get_path(txn);
3517 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3518 p = path;
3519 while (p < end && *p != '?')
3520 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003521
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003522 /* Stores the request path. */
3523 lua_pushstring(L, "path");
3524 lua_pushlstring(L, path, p - path);
3525 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003526
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003527 /* Stores the query string. */
3528 lua_pushstring(L, "qs");
3529 if (*p == '?')
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003530 p++;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003531 lua_pushlstring(L, p, end - p);
3532 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003533
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003534 /* Stores the request path. */
3535 lua_pushstring(L, "length");
3536 lua_pushinteger(L, txn->req.body_len);
3537 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003538
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003539 /* Create an array of HTTP request headers. */
3540 lua_pushstring(L, "headers");
3541 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3542 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003543
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003544 /* Create an empty array of HTTP request headers. */
3545 lua_pushstring(L, "response");
3546 lua_newtable(L);
3547 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003548
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003549 /* Pop a class stream metatable and affect it to the table. */
3550 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3551 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003552
3553 return 1;
3554}
3555
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003556__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3557{
3558 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3559 struct stream *s = appctx->htxn.s;
3560 struct hlua *hlua = &s->hlua;
3561
3562 MAY_LJMP(check_args(L, 2, "set_priv"));
3563
3564 /* Remove previous value. */
3565 if (hlua->Mref != -1)
3566 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3567
3568 /* Get and store new value. */
3569 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3570 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3571
3572 return 0;
3573}
3574
3575__LJMP static int hlua_applet_http_get_priv(lua_State *L)
3576{
3577 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3578 struct stream *s = appctx->htxn.s;
3579 struct hlua *hlua = &s->hlua;
3580
3581 /* Push configuration index in the stack. */
3582 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3583
3584 return 1;
3585}
3586
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003587/* If expected data not yet available, it returns a yield. This function
3588 * consumes the data in the buffer. It returns a string containing the
3589 * data. This string can be empty.
3590 */
3591__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003592{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003593 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3594 struct stream_interface *si = appctx->appctx->owner;
3595 struct channel *chn = si_ic(si);
3596 int ret;
3597 char *blk1;
3598 int len1;
3599 char *blk2;
3600 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003601
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003602 /* Maybe we cant send a 100-continue ? */
3603 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3604 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3605 /* if ret == -2 or -3 the channel closed or the message si too
3606 * big for the buffers. We cant send anything. So, we ignoring
3607 * the error, considers that the 100-continue is sent, and try
3608 * to receive.
3609 * If ret is -1, we dont have room in the buffer, so we yield.
3610 */
3611 if (ret == -1) {
3612 si_applet_cant_put(si);
3613 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3614 }
3615 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3616 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003617
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003618 /* Check for the end of the data. */
3619 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3620 luaL_pushresult(&appctx->b);
3621 return 1;
3622 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003623
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003624 /* Read the maximum amount of data avalaible. */
3625 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003626
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003627 /* Data not yet avalaible. return yield. */
3628 if (ret == 0) {
3629 si_applet_cant_get(si);
3630 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3631 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003632
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003633 /* End of data: commit the total strings and return. */
3634 if (ret < 0) {
3635 luaL_pushresult(&appctx->b);
3636 return 1;
3637 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003638
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003639 /* Ensure that the block 2 length is usable. */
3640 if (ret == 1)
3641 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003642
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003643 /* Copy the fisrt block caping to the length required. */
3644 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3645 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3646 luaL_addlstring(&appctx->b, blk1, len1);
3647 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003648
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003649 /* Copy the second block. */
3650 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3651 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3652 luaL_addlstring(&appctx->b, blk2, len2);
3653 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003654
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003655 /* Consume input channel output buffer data. */
3656 bo_skip(si_oc(si), len1 + len2);
3657 luaL_pushresult(&appctx->b);
3658 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003659}
3660
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003661/* Check arguments for the fucntion "hlua_channel_get_yield". */
3662__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003663{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003664 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003665
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003666 /* Initialise the string catenation. */
3667 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003668
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003669 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003670}
3671
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003672/* If expected data not yet available, it returns a yield. This function
3673 * consumes the data in the buffer. It returns a string containing the
3674 * data. This string can be empty.
3675 */
3676__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003677{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003678 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3679 struct stream_interface *si = appctx->appctx->owner;
3680 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3681 struct channel *chn = si_ic(si);
3682 int ret;
3683 char *blk1;
3684 int len1;
3685 char *blk2;
3686 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003687
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003688 /* Maybe we cant send a 100-continue ? */
3689 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3690 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3691 /* if ret == -2 or -3 the channel closed or the message si too
3692 * big for the buffers. We cant send anything. So, we ignoring
3693 * the error, considers that the 100-continue is sent, and try
3694 * to receive.
3695 * If ret is -1, we dont have room in the buffer, so we yield.
3696 */
3697 if (ret == -1) {
3698 si_applet_cant_put(si);
3699 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3700 }
3701 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3702 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003703
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003704 /* Read the maximum amount of data avalaible. */
3705 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003706
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003707 /* Data not yet avalaible. return yield. */
3708 if (ret == 0) {
3709 si_applet_cant_get(si);
3710 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3711 }
3712
3713 /* End of data: commit the total strings and return. */
3714 if (ret < 0) {
3715 luaL_pushresult(&appctx->b);
3716 return 1;
3717 }
3718
3719 /* Ensure that the block 2 length is usable. */
3720 if (ret == 1)
3721 len2 = 0;
3722
3723 /* Copy the fisrt block caping to the length required. */
3724 if (len1 > len)
3725 len1 = len;
3726 luaL_addlstring(&appctx->b, blk1, len1);
3727 len -= len1;
3728
3729 /* Copy the second block. */
3730 if (len2 > len)
3731 len2 = len;
3732 luaL_addlstring(&appctx->b, blk2, len2);
3733 len -= len2;
3734
3735 /* Consume input channel output buffer data. */
3736 bo_skip(si_oc(si), len1 + len2);
3737 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
3738 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
3739
3740 /* If we are no other data avalaible, yield waiting for new data. */
3741 if (len > 0) {
3742 lua_pushinteger(L, len);
3743 lua_replace(L, 2);
3744 si_applet_cant_get(si);
3745 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3746 }
3747
3748 /* return the result. */
3749 luaL_pushresult(&appctx->b);
3750 return 1;
3751}
3752
3753/* Check arguments for the fucntion "hlua_channel_get_yield". */
3754__LJMP static int hlua_applet_http_recv(lua_State *L)
3755{
3756 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3757 int len = -1;
3758
3759 /* Check arguments. */
3760 if (lua_gettop(L) > 2)
3761 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3762 if (lua_gettop(L) >= 2) {
3763 len = MAY_LJMP(luaL_checkinteger(L, 2));
3764 lua_pop(L, 1);
3765 }
3766
3767 /* Check the required length */
3768 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3769 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3770 lua_pushinteger(L, len);
3771
3772 /* Initialise the string catenation. */
3773 luaL_buffinit(L, &appctx->b);
3774
3775 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
3776}
3777
3778/* Append data in the output side of the buffer. This data is immediatly
3779 * sent. The fcuntion returns the ammount of data writed. If the buffer
3780 * cannot contains the data, the function yield. The function returns -1
3781 * if the channel is closed.
3782 */
3783__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
3784{
3785 size_t len;
3786 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3787 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3788 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3789 struct stream_interface *si = appctx->appctx->owner;
3790 struct channel *chn = si_ic(si);
3791 int max;
3792
3793 /* Get the max amount of data which can write as input in the channel. */
3794 max = channel_recv_max(chn);
3795 if (max > (len - l))
3796 max = len - l;
3797
3798 /* Copy data. */
3799 bi_putblk(chn, str + l, max);
3800
3801 /* update counters. */
3802 l += max;
3803 lua_pop(L, 1);
3804 lua_pushinteger(L, l);
3805
3806 /* If some data is not send, declares the situation to the
3807 * applet, and returns a yield.
3808 */
3809 if (l < len) {
3810 si_applet_cant_put(si);
3811 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
3812 }
3813
3814 return 1;
3815}
3816
3817/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
3818 * yield the LUA process, and resume it without checking the
3819 * input arguments.
3820 */
3821__LJMP static int hlua_applet_http_send(lua_State *L)
3822{
3823 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3824 size_t len;
3825 char hex[10];
3826
3827 MAY_LJMP(luaL_checklstring(L, 2, &len));
3828
3829 /* If transfer encoding chunked is selected, we surround the data
3830 * by chunk data.
3831 */
3832 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
3833 snprintf(hex, 9, "%x", (unsigned int)len);
3834 lua_pushfstring(L, "%s\r\n", hex);
3835 lua_insert(L, 2); /* swap the last 2 entries. */
3836 lua_pushstring(L, "\r\n");
3837 lua_concat(L, 3);
3838 }
3839
3840 /* This interger is used for followinf the amount of data sent. */
3841 lua_pushinteger(L, 0);
3842
3843 /* We want to send some data. Headers must be sent. */
3844 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
3845 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
3846 WILL_LJMP(lua_error(L));
3847 }
3848
3849 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
3850}
3851
3852__LJMP static int hlua_applet_http_addheader(lua_State *L)
3853{
3854 const char *name;
3855 int ret;
3856
3857 MAY_LJMP(hlua_checkapplet_http(L, 1));
3858 name = MAY_LJMP(luaL_checkstring(L, 2));
3859 MAY_LJMP(luaL_checkstring(L, 3));
3860
3861 /* Push in the stack the "response" entry. */
3862 ret = lua_getfield(L, 1, "response");
3863 if (ret != LUA_TTABLE) {
3864 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
3865 "is expected as an array. %s found", lua_typename(L, ret));
3866 WILL_LJMP(lua_error(L));
3867 }
3868
3869 /* check if the header is already registered if it is not
3870 * the case, register it.
3871 */
3872 ret = lua_getfield(L, -1, name);
3873 if (ret == LUA_TNIL) {
3874
3875 /* Entry not found. */
3876 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
3877
3878 /* Insert the new header name in the array in the top of the stack.
3879 * It left the new array in the top of the stack.
3880 */
3881 lua_newtable(L);
3882 lua_pushvalue(L, 2);
3883 lua_pushvalue(L, -2);
3884 lua_settable(L, -4);
3885
3886 } else if (ret != LUA_TTABLE) {
3887
3888 /* corruption error. */
3889 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
3890 "is expected as an array. %s found", name, lua_typename(L, ret));
3891 WILL_LJMP(lua_error(L));
3892 }
3893
3894 /* Now the top od thestack is an array of values. We push
3895 * the header value as new entry.
3896 */
3897 lua_pushvalue(L, 3);
3898 ret = lua_rawlen(L, -2);
3899 lua_rawseti(L, -2, ret + 1);
3900 lua_pushboolean(L, 1);
3901 return 1;
3902}
3903
3904__LJMP static int hlua_applet_http_status(lua_State *L)
3905{
3906 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3907 int status = MAY_LJMP(luaL_checkinteger(L, 2));
3908
3909 if (status < 100 || status > 599) {
3910 lua_pushboolean(L, 0);
3911 return 1;
3912 }
3913
3914 appctx->appctx->ctx.hlua_apphttp.status = status;
3915 lua_pushboolean(L, 1);
3916 return 1;
3917}
3918
3919/* We will build the status line and the headers of the HTTP response.
3920 * We will try send at once if its not possible, we give back the hand
3921 * waiting for more room.
3922 */
3923__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
3924{
3925 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3926 struct stream_interface *si = appctx->appctx->owner;
3927 struct channel *chn = si_ic(si);
3928 int ret;
3929 size_t len;
3930 const char *msg;
3931
3932 /* Get the message as the first argument on the stack. */
3933 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
3934
3935 /* Send the message at once. */
3936 ret = bi_putblk(chn, msg, len);
3937
3938 /* if ret == -2 or -3 the channel closed or the message si too
3939 * big for the buffers.
3940 */
3941 if (ret == -2 || ret == -3) {
3942 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
3943 WILL_LJMP(lua_error(L));
3944 }
3945
3946 /* If ret is -1, we dont have room in the buffer, so we yield. */
3947 if (ret == -1) {
3948 si_applet_cant_put(si);
3949 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
3950 }
3951
3952 /* Headers sent, set the flag. */
3953 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
3954 return 0;
3955}
3956
3957__LJMP static int hlua_applet_http_start_response(lua_State *L)
3958{
3959 struct chunk *tmp = get_trash_chunk();
3960 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003961 const char *name;
3962 const char *value;
3963 int id;
3964 int hdr_connection = 0;
3965 int hdr_contentlength = -1;
3966 int hdr_chunked = 0;
3967
3968 /* Use the same http version than the request. */
3969 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01003970 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003971 appctx->appctx->ctx.hlua_apphttp.status,
3972 get_reason(appctx->appctx->ctx.hlua_apphttp.status));
3973
3974 /* Get the array associated to the field "response" in the object AppletHTTP. */
3975 lua_pushvalue(L, 0);
3976 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
3977 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
3978 appctx->appctx->rule->arg.hlua_rule->fcn.name);
3979 WILL_LJMP(lua_error(L));
3980 }
3981
3982 /* Browse the list of headers. */
3983 lua_pushnil(L);
3984 while(lua_next(L, -2) != 0) {
3985
3986 /* We expect a string as -2. */
3987 if (lua_type(L, -2) != LUA_TSTRING) {
3988 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
3989 appctx->appctx->rule->arg.hlua_rule->fcn.name,
3990 lua_typename(L, lua_type(L, -2)));
3991 WILL_LJMP(lua_error(L));
3992 }
3993 name = lua_tostring(L, -2);
3994
3995 /* We expect an array as -1. */
3996 if (lua_type(L, -1) != LUA_TTABLE) {
3997 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
3998 appctx->appctx->rule->arg.hlua_rule->fcn.name,
3999 name,
4000 lua_typename(L, lua_type(L, -1)));
4001 WILL_LJMP(lua_error(L));
4002 }
4003
4004 /* Browse the table who is on the top of the stack. */
4005 lua_pushnil(L);
4006 while(lua_next(L, -2) != 0) {
4007
4008 /* We expect a number as -2. */
4009 if (lua_type(L, -2) != LUA_TNUMBER) {
4010 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4011 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4012 name,
4013 lua_typename(L, lua_type(L, -2)));
4014 WILL_LJMP(lua_error(L));
4015 }
4016 id = lua_tointeger(L, -2);
4017
4018 /* We expect a string as -2. */
4019 if (lua_type(L, -1) != LUA_TSTRING) {
4020 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4021 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4022 name, id,
4023 lua_typename(L, lua_type(L, -1)));
4024 WILL_LJMP(lua_error(L));
4025 }
4026 value = lua_tostring(L, -1);
4027
4028 /* Catenate a new header. */
4029 chunk_appendf(tmp, "%s: %s\r\n", name, value);
4030
4031 /* Protocol checks. */
4032
4033 /* Check if the header conneciton is present. */
4034 if (strcasecmp("connection", name) == 0)
4035 hdr_connection = 1;
4036
4037 /* Copy the header content length. The length conversion
4038 * is done without control. If it contains a ad value, this
4039 * is not our problem.
4040 */
4041 if (strcasecmp("content-length", name) == 0)
4042 hdr_contentlength = atoi(value);
4043
4044 /* Check if the client annouces a transfer-encoding chunked it self. */
4045 if (strcasecmp("transfer-encoding", name) == 0 &&
4046 strcasecmp("chunked", value) == 0)
4047 hdr_chunked = 1;
4048
4049 /* Remove the array from the stack, and get next element with a remaining string. */
4050 lua_pop(L, 1);
4051 }
4052
4053 /* Remove the array from the stack, and get next element with a remaining string. */
4054 lua_pop(L, 1);
4055 }
4056
4057 /* If the http protocol version is 1.1, we expect an header "connection" set
4058 * to "close" to be HAProxy/keeplive compliant. Otherwise, we expect nothing.
4059 * If the header conneciton is present, don't change it, if it is not present,
4060 * we must set.
4061 *
4062 * we set a "connection: close" header for ensuring that the keepalive will be
4063 * respected by haproxy. HAProcy considers that the application cloe the connection
4064 * and it keep the connection from the client open.
4065 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004066 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 && !hdr_connection)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004067 chunk_appendf(tmp, "Connection: close\r\n");
4068
4069 /* If we dont have a content-length set, we must announce a transfer enconding
4070 * chunked. This is required by haproxy for the keepalive compliance.
4071 * If the applet annouce a transfer-encoding chunked itslef, don't
4072 * do anything.
4073 */
4074 if (hdr_contentlength == -1 && hdr_chunked == 0) {
4075 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4076 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4077 }
4078
4079 /* Finalize headers. */
4080 chunk_appendf(tmp, "\r\n");
4081
4082 /* Remove the last entry and the array of headers */
4083 lua_pop(L, 2);
4084
4085 /* Push the headers block. */
4086 lua_pushlstring(L, tmp->str, tmp->len);
4087
4088 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4089}
4090
4091/*
4092 *
4093 *
4094 * Class HTTP
4095 *
4096 *
4097 */
4098
4099/* Returns a struct hlua_txn if the stack entry "ud" is
4100 * a class stream, otherwise it throws an error.
4101 */
4102__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4103{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004104 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004105}
4106
4107/* This function creates and push in the stack a HTTP object
4108 * according with a current TXN.
4109 */
4110static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4111{
4112 struct hlua_txn *htxn;
4113
4114 /* Check stack size. */
4115 if (!lua_checkstack(L, 3))
4116 return 0;
4117
4118 /* Create the object: obj[0] = userdata.
4119 * Note that the base of the Converters object is the
4120 * same than the TXN object.
4121 */
4122 lua_newtable(L);
4123 htxn = lua_newuserdata(L, sizeof(*htxn));
4124 lua_rawseti(L, -2, 0);
4125
4126 htxn->s = txn->s;
4127 htxn->p = txn->p;
4128
4129 /* Pop a class stream metatable and affect it to the table. */
4130 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4131 lua_setmetatable(L, -2);
4132
4133 return 1;
4134}
4135
4136/* This function creates ans returns an array of HTTP headers.
4137 * This function does not fails. It is used as wrapper with the
4138 * 2 following functions.
4139 */
4140__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4141{
4142 const char *cur_ptr, *cur_next, *p;
4143 int old_idx, cur_idx;
4144 struct hdr_idx_elem *cur_hdr;
4145 const char *hn, *hv;
4146 int hnl, hvl;
4147 int type;
4148 const char *in;
4149 char *out;
4150 int len;
4151
4152 /* Create the table. */
4153 lua_newtable(L);
4154
4155 if (!htxn->s->txn)
4156 return 1;
4157
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004158 /* Check if a valid response is parsed */
4159 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4160 return 1;
4161
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004162 /* Build array of headers. */
4163 old_idx = 0;
4164 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4165
4166 while (1) {
4167 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4168 if (!cur_idx)
4169 break;
4170 old_idx = cur_idx;
4171
4172 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4173 cur_ptr = cur_next;
4174 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4175
4176 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4177 * and the next header starts at cur_next. We'll check
4178 * this header in the list as well as against the default
4179 * rule.
4180 */
4181
4182 /* look for ': *'. */
4183 hn = cur_ptr;
4184 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4185 if (p >= cur_ptr+cur_hdr->len)
4186 continue;
4187 hnl = p - hn;
4188 p++;
4189 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4190 p++;
4191 if (p >= cur_ptr+cur_hdr->len)
4192 continue;
4193 hv = p;
4194 hvl = cur_ptr+cur_hdr->len-p;
4195
4196 /* Lowercase the key. Don't check the size of trash, it have
4197 * the size of one buffer and the input data contains in one
4198 * buffer.
4199 */
4200 out = trash.str;
4201 for (in=hn; in<hn+hnl; in++, out++)
4202 *out = tolower(*in);
4203 *out = '\0';
4204
4205 /* Check for existing entry:
4206 * assume that the table is on the top of the stack, and
4207 * push the key in the stack, the function lua_gettable()
4208 * perform the lookup.
4209 */
4210 lua_pushlstring(L, trash.str, hnl);
4211 lua_gettable(L, -2);
4212 type = lua_type(L, -1);
4213
4214 switch (type) {
4215 case LUA_TNIL:
4216 /* Table not found, create it. */
4217 lua_pop(L, 1); /* remove the nil value. */
4218 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4219 lua_newtable(L); /* create and push empty table. */
4220 lua_pushlstring(L, hv, hvl); /* push header value. */
4221 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4222 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4223 break;
4224
4225 case LUA_TTABLE:
4226 /* Entry found: push the value in the table. */
4227 len = lua_rawlen(L, -1);
4228 lua_pushlstring(L, hv, hvl); /* push header value. */
4229 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4230 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4231 break;
4232
4233 default:
4234 /* Other cases are errors. */
4235 hlua_pusherror(L, "internal error during the parsing of headers.");
4236 WILL_LJMP(lua_error(L));
4237 }
4238 }
4239
4240 return 1;
4241}
4242
4243__LJMP static int hlua_http_req_get_headers(lua_State *L)
4244{
4245 struct hlua_txn *htxn;
4246
4247 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4248 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4249
4250 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4251}
4252
4253__LJMP static int hlua_http_res_get_headers(lua_State *L)
4254{
4255 struct hlua_txn *htxn;
4256
4257 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4258 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4259
4260 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4261}
4262
4263/* This function replace full header, or just a value in
4264 * the request or in the response. It is a wrapper fir the
4265 * 4 following functions.
4266 */
4267__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4268 struct http_msg *msg, int action)
4269{
4270 size_t name_len;
4271 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4272 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4273 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4274 struct my_regex re;
4275
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004276 /* Check if a valid response is parsed */
4277 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4278 return 0;
4279
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004280 if (!regex_comp(reg, &re, 1, 1, NULL))
4281 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4282
4283 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4284 regex_free(&re);
4285 return 0;
4286}
4287
4288__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4289{
4290 struct hlua_txn *htxn;
4291
4292 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4293 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4294
4295 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4296}
4297
4298__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4299{
4300 struct hlua_txn *htxn;
4301
4302 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4303 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4304
4305 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4306}
4307
4308__LJMP static int hlua_http_req_rep_val(lua_State *L)
4309{
4310 struct hlua_txn *htxn;
4311
4312 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4313 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4314
4315 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4316}
4317
4318__LJMP static int hlua_http_res_rep_val(lua_State *L)
4319{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004320 struct hlua_txn *htxn;
4321
4322 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4323 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4324
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004325 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004326}
4327
4328/* This function deletes all the occurences of an header.
4329 * It is a wrapper for the 2 following functions.
4330 */
4331__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4332{
4333 size_t len;
4334 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4335 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004336 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004337
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004338 /* Check if a valid response is parsed */
4339 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4340 return 0;
4341
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004342 ctx.idx = 0;
4343 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4344 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4345 return 0;
4346}
4347
4348__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4349{
4350 struct hlua_txn *htxn;
4351
4352 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4353 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4354
Willy Tarreaueee5b512015-04-03 23:46:31 +02004355 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004356}
4357
4358__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4359{
4360 struct hlua_txn *htxn;
4361
4362 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4363 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4364
Willy Tarreaueee5b512015-04-03 23:46:31 +02004365 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004366}
4367
4368/* This function adds an header. It is a wrapper used by
4369 * the 2 following functions.
4370 */
4371__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4372{
4373 size_t name_len;
4374 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4375 size_t value_len;
4376 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4377 char *p;
4378
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004379 /* Check if a valid message is parsed */
4380 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4381 return 0;
4382
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004383 /* Check length. */
4384 trash.len = value_len + name_len + 2;
4385 if (trash.len > trash.size)
4386 return 0;
4387
4388 /* Creates the header string. */
4389 p = trash.str;
4390 memcpy(p, name, name_len);
4391 p += name_len;
4392 *p = ':';
4393 p++;
4394 *p = ' ';
4395 p++;
4396 memcpy(p, value, value_len);
4397
Willy Tarreaueee5b512015-04-03 23:46:31 +02004398 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004399 trash.str, trash.len) != 0);
4400
4401 return 0;
4402}
4403
4404__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4405{
4406 struct hlua_txn *htxn;
4407
4408 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4409 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4410
Willy Tarreaueee5b512015-04-03 23:46:31 +02004411 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004412}
4413
4414__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4415{
4416 struct hlua_txn *htxn;
4417
4418 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4419 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4420
Willy Tarreaueee5b512015-04-03 23:46:31 +02004421 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004422}
4423
4424static int hlua_http_req_set_hdr(lua_State *L)
4425{
4426 struct hlua_txn *htxn;
4427
4428 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4429 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4430
Willy Tarreaueee5b512015-04-03 23:46:31 +02004431 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4432 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004433}
4434
4435static int hlua_http_res_set_hdr(lua_State *L)
4436{
4437 struct hlua_txn *htxn;
4438
4439 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4440 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4441
Willy Tarreaueee5b512015-04-03 23:46:31 +02004442 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4443 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004444}
4445
4446/* This function set the method. */
4447static int hlua_http_req_set_meth(lua_State *L)
4448{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004449 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004450 size_t name_len;
4451 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004452
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004453 /* Check if a valid request is parsed */
4454 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4455 lua_pushboolean(L, 0);
4456 return 1;
4457 }
4458
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004459 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004460 return 1;
4461}
4462
4463/* This function set the method. */
4464static int hlua_http_req_set_path(lua_State *L)
4465{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004466 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004467 size_t name_len;
4468 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004469
4470 /* Check if a valid request is parsed */
4471 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4472 lua_pushboolean(L, 0);
4473 return 1;
4474 }
4475
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004476 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004477 return 1;
4478}
4479
4480/* This function set the query-string. */
4481static int hlua_http_req_set_query(lua_State *L)
4482{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004483 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004484 size_t name_len;
4485 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004486
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004487 /* Check if a valid request is parsed */
4488 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4489 lua_pushboolean(L, 0);
4490 return 1;
4491 }
4492
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004493 /* Check length. */
4494 if (name_len > trash.size - 1) {
4495 lua_pushboolean(L, 0);
4496 return 1;
4497 }
4498
4499 /* Add the mark question as prefix. */
4500 chunk_reset(&trash);
4501 trash.str[trash.len++] = '?';
4502 memcpy(trash.str + trash.len, name, name_len);
4503 trash.len += name_len;
4504
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004505 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004506 return 1;
4507}
4508
4509/* This function set the uri. */
4510static int hlua_http_req_set_uri(lua_State *L)
4511{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004512 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004513 size_t name_len;
4514 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004515
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004516 /* Check if a valid request is parsed */
4517 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4518 lua_pushboolean(L, 0);
4519 return 1;
4520 }
4521
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004522 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004523 return 1;
4524}
4525
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004526/* This function set the response code. */
4527static int hlua_http_res_set_status(lua_State *L)
4528{
4529 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4530 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
4531
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004532 /* Check if a valid response is parsed */
4533 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4534 return 0;
4535
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004536 http_set_status(code, htxn->s);
4537 return 0;
4538}
4539
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004540/*
4541 *
4542 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004543 * Class TXN
4544 *
4545 *
4546 */
4547
4548/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004549 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004550 */
4551__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4552{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004553 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004554}
4555
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004556__LJMP static int hlua_set_var(lua_State *L)
4557{
4558 struct hlua_txn *htxn;
4559 const char *name;
4560 size_t len;
4561 struct sample smp;
4562
4563 MAY_LJMP(check_args(L, 3, "set_var"));
4564
4565 /* It is useles to retrieve the stream, but this function
4566 * runs only in a stream context.
4567 */
4568 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4569 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4570
4571 /* Converts the third argument in a sample. */
4572 hlua_lua2smp(L, 3, &smp);
4573
4574 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01004575 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004576 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004577 return 0;
4578}
4579
Christopher Faulet85d79c92016-11-09 16:54:56 +01004580__LJMP static int hlua_unset_var(lua_State *L)
4581{
4582 struct hlua_txn *htxn;
4583 const char *name;
4584 size_t len;
4585 struct sample smp;
4586
4587 MAY_LJMP(check_args(L, 2, "unset_var"));
4588
4589 /* It is useles to retrieve the stream, but this function
4590 * runs only in a stream context.
4591 */
4592 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4593 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4594
4595 /* Unset the variable. */
4596 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
4597 vars_unset_by_name(name, len, &smp);
4598 return 0;
4599}
4600
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004601__LJMP static int hlua_get_var(lua_State *L)
4602{
4603 struct hlua_txn *htxn;
4604 const char *name;
4605 size_t len;
4606 struct sample smp;
4607
4608 MAY_LJMP(check_args(L, 2, "get_var"));
4609
4610 /* It is useles to retrieve the stream, but this function
4611 * runs only in a stream context.
4612 */
4613 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4614 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4615
Willy Tarreau7560dd42016-03-10 16:28:58 +01004616 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004617 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004618 lua_pushnil(L);
4619 return 1;
4620 }
4621
4622 return hlua_smp2lua(L, &smp);
4623}
4624
Willy Tarreau59551662015-03-10 14:23:13 +01004625__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004626{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004627 struct hlua *hlua;
4628
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004629 MAY_LJMP(check_args(L, 2, "set_priv"));
4630
Willy Tarreau87b09662015-04-03 00:22:06 +02004631 /* It is useles to retrieve the stream, but this function
4632 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004633 */
4634 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004635 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004636
4637 /* Remove previous value. */
4638 if (hlua->Mref != -1)
4639 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
4640
4641 /* Get and store new value. */
4642 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4643 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4644
4645 return 0;
4646}
4647
Willy Tarreau59551662015-03-10 14:23:13 +01004648__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004649{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004650 struct hlua *hlua;
4651
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004652 MAY_LJMP(check_args(L, 1, "get_priv"));
4653
Willy Tarreau87b09662015-04-03 00:22:06 +02004654 /* It is useles to retrieve the stream, but this function
4655 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004656 */
4657 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004658 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004659
4660 /* Push configuration index in the stack. */
4661 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4662
4663 return 1;
4664}
4665
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004666/* Create stack entry containing a class TXN. This function
4667 * return 0 if the stack does not contains free slots,
4668 * otherwise it returns 1.
4669 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004670static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004671{
Willy Tarreaude491382015-04-06 11:04:28 +02004672 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004673
4674 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004675 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004676 return 0;
4677
4678 /* NOTE: The allocation never fails. The failure
4679 * throw an error, and the function never returns.
4680 * if the throw is not avalaible, the process is aborted.
4681 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004682 /* Create the object: obj[0] = userdata. */
4683 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004684 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004685 lua_rawseti(L, -2, 0);
4686
Willy Tarreaude491382015-04-06 11:04:28 +02004687 htxn->s = s;
4688 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004689 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004690 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004691
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004692 /* Create the "f" field that contains a list of fetches. */
4693 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004694 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004695 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004696 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004697
4698 /* Create the "sf" field that contains a list of stringsafe fetches. */
4699 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004700 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004701 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004702 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004703
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004704 /* Create the "c" field that contains a list of converters. */
4705 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004706 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004707 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004708 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004709
4710 /* Create the "sc" field that contains a list of stringsafe converters. */
4711 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004712 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004713 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004714 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004715
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004716 /* Create the "req" field that contains the request channel object. */
4717 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004718 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004719 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004720 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004721
4722 /* Create the "res" field that contains the response channel object. */
4723 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004724 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004725 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004726 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004727
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004728 /* Creates the HTTP object is the current proxy allows http. */
4729 lua_pushstring(L, "http");
4730 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02004731 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004732 return 0;
4733 }
4734 else
4735 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004736 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004737
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004738 /* Pop a class sesison metatable and affect it to the userdata. */
4739 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
4740 lua_setmetatable(L, -2);
4741
4742 return 1;
4743}
4744
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004745__LJMP static int hlua_txn_deflog(lua_State *L)
4746{
4747 const char *msg;
4748 struct hlua_txn *htxn;
4749
4750 MAY_LJMP(check_args(L, 2, "deflog"));
4751 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4752 msg = MAY_LJMP(luaL_checkstring(L, 2));
4753
4754 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
4755 return 0;
4756}
4757
4758__LJMP static int hlua_txn_log(lua_State *L)
4759{
4760 int level;
4761 const char *msg;
4762 struct hlua_txn *htxn;
4763
4764 MAY_LJMP(check_args(L, 3, "log"));
4765 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4766 level = MAY_LJMP(luaL_checkinteger(L, 2));
4767 msg = MAY_LJMP(luaL_checkstring(L, 3));
4768
4769 if (level < 0 || level >= NB_LOG_LEVELS)
4770 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4771
4772 hlua_sendlog(htxn->s->be, level, msg);
4773 return 0;
4774}
4775
4776__LJMP static int hlua_txn_log_debug(lua_State *L)
4777{
4778 const char *msg;
4779 struct hlua_txn *htxn;
4780
4781 MAY_LJMP(check_args(L, 2, "Debug"));
4782 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4783 msg = MAY_LJMP(luaL_checkstring(L, 2));
4784 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
4785 return 0;
4786}
4787
4788__LJMP static int hlua_txn_log_info(lua_State *L)
4789{
4790 const char *msg;
4791 struct hlua_txn *htxn;
4792
4793 MAY_LJMP(check_args(L, 2, "Info"));
4794 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4795 msg = MAY_LJMP(luaL_checkstring(L, 2));
4796 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
4797 return 0;
4798}
4799
4800__LJMP static int hlua_txn_log_warning(lua_State *L)
4801{
4802 const char *msg;
4803 struct hlua_txn *htxn;
4804
4805 MAY_LJMP(check_args(L, 2, "Warning"));
4806 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4807 msg = MAY_LJMP(luaL_checkstring(L, 2));
4808 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
4809 return 0;
4810}
4811
4812__LJMP static int hlua_txn_log_alert(lua_State *L)
4813{
4814 const char *msg;
4815 struct hlua_txn *htxn;
4816
4817 MAY_LJMP(check_args(L, 2, "Alert"));
4818 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4819 msg = MAY_LJMP(luaL_checkstring(L, 2));
4820 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
4821 return 0;
4822}
4823
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004824__LJMP static int hlua_txn_set_loglevel(lua_State *L)
4825{
4826 struct hlua_txn *htxn;
4827 int ll;
4828
4829 MAY_LJMP(check_args(L, 2, "set_loglevel"));
4830 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4831 ll = MAY_LJMP(luaL_checkinteger(L, 2));
4832
4833 if (ll < 0 || ll > 7)
4834 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
4835
4836 htxn->s->logs.level = ll;
4837 return 0;
4838}
4839
4840__LJMP static int hlua_txn_set_tos(lua_State *L)
4841{
4842 struct hlua_txn *htxn;
4843 struct connection *cli_conn;
4844 int tos;
4845
4846 MAY_LJMP(check_args(L, 2, "set_tos"));
4847 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4848 tos = MAY_LJMP(luaL_checkinteger(L, 2));
4849
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004850 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Vincent Bernat6e615892016-05-18 16:17:44 +02004851 inet_set_tos(cli_conn->t.sock.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004852
4853 return 0;
4854}
4855
4856__LJMP static int hlua_txn_set_mark(lua_State *L)
4857{
4858#ifdef SO_MARK
4859 struct hlua_txn *htxn;
4860 struct connection *cli_conn;
4861 int mark;
4862
4863 MAY_LJMP(check_args(L, 2, "set_mark"));
4864 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4865 mark = MAY_LJMP(luaL_checkinteger(L, 2));
4866
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004867 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02004868 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004869#endif
4870 return 0;
4871}
4872
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004873/* This function is an Lua binding that send pending data
4874 * to the client, and close the stream interface.
4875 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004876__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004877{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004878 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02004879 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01004880 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004881
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004882 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004883 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02004884 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004885
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004886 /* If the flags NOTERM is set, we cannot terminate the http
4887 * session, so we just end the execution of the current
4888 * lua code.
4889 */
4890 if (htxn->flags & HLUA_TXN_NOTERM) {
4891 WILL_LJMP(hlua_done(L));
4892 return 0;
4893 }
4894
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004895 ic = &htxn->s->req;
4896 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01004897
Willy Tarreau630ef452015-08-28 10:06:15 +02004898 if (htxn->s->txn) {
4899 /* HTTP mode, let's stay in sync with the stream */
4900 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
4901 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
4902 htxn->s->txn->req.sov = 0;
4903 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
4904 oc->analysers = AN_RES_HTTP_XFER_BODY;
4905 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
4906 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
4907
Willy Tarreau630ef452015-08-28 10:06:15 +02004908 /* Note that if we want to support keep-alive, we need
4909 * to bypass the close/shutr_now calls below, but that
4910 * may only be done if the HTTP request was already
4911 * processed and the connection header is known (ie
4912 * not during TCP rules).
4913 */
4914 }
4915
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004916 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01004917 channel_abort(ic);
4918 channel_auto_close(ic);
4919 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004920
4921 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01004922 channel_auto_read(oc);
4923 channel_auto_close(oc);
4924 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004925
Willy Tarreau0458b082015-08-28 09:40:04 +02004926 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004927
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02004928 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004929 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004930 return 0;
4931}
4932
4933__LJMP static int hlua_log(lua_State *L)
4934{
4935 int level;
4936 const char *msg;
4937
4938 MAY_LJMP(check_args(L, 2, "log"));
4939 level = MAY_LJMP(luaL_checkinteger(L, 1));
4940 msg = MAY_LJMP(luaL_checkstring(L, 2));
4941
4942 if (level < 0 || level >= NB_LOG_LEVELS)
4943 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4944
4945 hlua_sendlog(NULL, level, msg);
4946 return 0;
4947}
4948
4949__LJMP static int hlua_log_debug(lua_State *L)
4950{
4951 const char *msg;
4952
4953 MAY_LJMP(check_args(L, 1, "debug"));
4954 msg = MAY_LJMP(luaL_checkstring(L, 1));
4955 hlua_sendlog(NULL, LOG_DEBUG, msg);
4956 return 0;
4957}
4958
4959__LJMP static int hlua_log_info(lua_State *L)
4960{
4961 const char *msg;
4962
4963 MAY_LJMP(check_args(L, 1, "info"));
4964 msg = MAY_LJMP(luaL_checkstring(L, 1));
4965 hlua_sendlog(NULL, LOG_INFO, msg);
4966 return 0;
4967}
4968
4969__LJMP static int hlua_log_warning(lua_State *L)
4970{
4971 const char *msg;
4972
4973 MAY_LJMP(check_args(L, 1, "warning"));
4974 msg = MAY_LJMP(luaL_checkstring(L, 1));
4975 hlua_sendlog(NULL, LOG_WARNING, msg);
4976 return 0;
4977}
4978
4979__LJMP static int hlua_log_alert(lua_State *L)
4980{
4981 const char *msg;
4982
4983 MAY_LJMP(check_args(L, 1, "alert"));
4984 msg = MAY_LJMP(luaL_checkstring(L, 1));
4985 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004986 return 0;
4987}
4988
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004989__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004990{
4991 int wakeup_ms = lua_tointeger(L, -1);
4992 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004993 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004994 return 0;
4995}
4996
4997__LJMP static int hlua_sleep(lua_State *L)
4998{
4999 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005000 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005001
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005002 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005003
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005004 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005005 wakeup_ms = tick_add(now_ms, delay);
5006 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005007
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005008 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5009 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005010}
5011
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005012__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005013{
5014 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005015 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005016
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005017 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005018
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005019 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005020 wakeup_ms = tick_add(now_ms, delay);
5021 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005022
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005023 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5024 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005025}
5026
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005027/* This functionis an LUA binding. it permits to give back
5028 * the hand at the HAProxy scheduler. It is used when the
5029 * LUA processing consumes a lot of time.
5030 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005031__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005032{
5033 return 0;
5034}
5035
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005036__LJMP static int hlua_yield(lua_State *L)
5037{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005038 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5039 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005040}
5041
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005042/* This function change the nice of the currently executed
5043 * task. It is used set low or high priority at the current
5044 * task.
5045 */
Willy Tarreau59551662015-03-10 14:23:13 +01005046__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005047{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005048 struct hlua *hlua;
5049 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005050
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005051 MAY_LJMP(check_args(L, 1, "set_nice"));
5052 hlua = hlua_gethlua(L);
5053 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005054
5055 /* If he task is not set, I'm in a start mode. */
5056 if (!hlua || !hlua->task)
5057 return 0;
5058
5059 if (nice < -1024)
5060 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005061 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005062 nice = 1024;
5063
5064 hlua->task->nice = nice;
5065 return 0;
5066}
5067
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005068/* This function is used as a calback of a task. It is called by the
5069 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5070 * return an E_AGAIN signal, the emmiter of this signal must set a
5071 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005072 *
5073 * Task wrapper are longjmp safe because the only one Lua code
5074 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005075 */
5076static struct task *hlua_process_task(struct task *task)
5077{
5078 struct hlua *hlua = task->context;
5079 enum hlua_exec status;
5080
5081 /* We need to remove the task from the wait queue before executing
5082 * the Lua code because we don't know if it needs to wait for
5083 * another timer or not in the case of E_AGAIN.
5084 */
5085 task_delete(task);
5086
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005087 /* If it is the first call to the task, we must initialize the
5088 * execution timeouts.
5089 */
5090 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005091 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005092
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005093 /* Execute the Lua code. */
5094 status = hlua_ctx_resume(hlua, 1);
5095
5096 switch (status) {
5097 /* finished or yield */
5098 case HLUA_E_OK:
5099 hlua_ctx_destroy(hlua);
5100 task_delete(task);
5101 task_free(task);
5102 break;
5103
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005104 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5105 if (hlua->wake_time != TICK_ETERNITY)
5106 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005107 break;
5108
5109 /* finished with error. */
5110 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005111 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005112 hlua_ctx_destroy(hlua);
5113 task_delete(task);
5114 task_free(task);
5115 break;
5116
5117 case HLUA_E_ERR:
5118 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005119 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005120 hlua_ctx_destroy(hlua);
5121 task_delete(task);
5122 task_free(task);
5123 break;
5124 }
5125 return NULL;
5126}
5127
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005128/* This function is an LUA binding that register LUA function to be
5129 * executed after the HAProxy configuration parsing and before the
5130 * HAProxy scheduler starts. This function expect only one LUA
5131 * argument that is a function. This function returns nothing, but
5132 * throws if an error is encountered.
5133 */
5134__LJMP static int hlua_register_init(lua_State *L)
5135{
5136 struct hlua_init_function *init;
5137 int ref;
5138
5139 MAY_LJMP(check_args(L, 1, "register_init"));
5140
5141 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5142
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005143 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005144 if (!init)
5145 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5146
5147 init->function_ref = ref;
5148 LIST_ADDQ(&hlua_init_functions, &init->l);
5149 return 0;
5150}
5151
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005152/* This functio is an LUA binding. It permits to register a task
5153 * executed in parallel of the main HAroxy activity. The task is
5154 * created and it is set in the HAProxy scheduler. It can be called
5155 * from the "init" section, "post init" or during the runtime.
5156 *
5157 * Lua prototype:
5158 *
5159 * <none> core.register_task(<function>)
5160 */
5161static int hlua_register_task(lua_State *L)
5162{
5163 struct hlua *hlua;
5164 struct task *task;
5165 int ref;
5166
5167 MAY_LJMP(check_args(L, 1, "register_task"));
5168
5169 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5170
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005171 hlua = calloc(1, sizeof(*hlua));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005172 if (!hlua)
5173 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5174
5175 task = task_new();
5176 task->context = hlua;
5177 task->process = hlua_process_task;
5178
5179 if (!hlua_ctx_init(hlua, task))
5180 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5181
5182 /* Restore the function in the stack. */
5183 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5184 hlua->nargs = 0;
5185
5186 /* Schedule task. */
5187 task_schedule(task, now_ms);
5188
5189 return 0;
5190}
5191
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005192/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5193 * doesn't allow "yield" functions because the HAProxy engine cannot
5194 * resume converters.
5195 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005196static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005197{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005198 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005199 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005200 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005201
Willy Tarreaube508f12016-03-10 11:47:01 +01005202 if (!stream)
5203 return 0;
5204
Willy Tarreau87b09662015-04-03 00:22:06 +02005205 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005206 * Lua context can be not initialized. This behavior
5207 * permits to save performances because a systematic
5208 * Lua initialization cause 5% performances loss.
5209 */
Willy Tarreau87b09662015-04-03 00:22:06 +02005210 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005211 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005212 return 0;
5213 }
5214
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005215 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005216 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005217
5218 /* The following Lua calls can fail. */
5219 if (!SET_SAFE_LJMP(stream->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005220 if (lua_type(stream->hlua.T, -1) == LUA_TSTRING)
5221 error = lua_tostring(stream->hlua.T, -1);
5222 else
5223 error = "critical error";
5224 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005225 return 0;
5226 }
5227
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005228 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005229 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005230 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005231 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005232 return 0;
5233 }
5234
5235 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005236 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005237
5238 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005239 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005240 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005241 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005242 return 0;
5243 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005244 hlua_smp2lua(stream->hlua.T, smp);
Thierry Fournier4a53bfd2016-05-27 16:35:01 +02005245 stream->hlua.nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005246
5247 /* push keywords in the stack. */
5248 if (arg_p) {
5249 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02005250 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005251 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005252 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005253 return 0;
5254 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005255 hlua_arg2lua(stream->hlua.T, arg_p);
5256 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005257 }
5258 }
5259
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005260 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005261 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005262
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005263 /* At this point the execution is safe. */
5264 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005265 }
5266
5267 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005268 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005269 /* finished. */
5270 case HLUA_E_OK:
5271 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005272 hlua_lua2smp(stream->hlua.T, -1, smp);
5273 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005274 return 1;
5275
5276 /* yield. */
5277 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005278 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005279 return 0;
5280
5281 /* finished with error. */
5282 case HLUA_E_ERRMSG:
5283 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005284 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
5285 fcn->name, lua_tostring(stream->hlua.T, -1));
Willy Tarreau87b09662015-04-03 00:22:06 +02005286 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005287 return 0;
5288
5289 case HLUA_E_ERR:
5290 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005291 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005292
5293 default:
5294 return 0;
5295 }
5296}
5297
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005298/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5299 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005300 * resume sample-fetches. This function will be called by the sample
5301 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005302 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005303static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5304 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005305{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005306 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005307 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005308 const char *error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005309
Willy Tarreaube508f12016-03-10 11:47:01 +01005310 if (!stream)
5311 return 0;
5312
Willy Tarreau87b09662015-04-03 00:22:06 +02005313 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005314 * Lua context can be not initialized. This behavior
5315 * permits to save performances because a systematic
5316 * Lua initialization cause 5% performances loss.
5317 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005318 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005319 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005320 return 0;
5321 }
5322
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005323 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005324 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005325
5326 /* The following Lua calls can fail. */
5327 if (!SET_SAFE_LJMP(stream->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005328 if (lua_type(stream->hlua.T, -1) == LUA_TSTRING)
5329 error = lua_tostring(stream->hlua.T, -1);
5330 else
5331 error = "critical error";
5332 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005333 return 0;
5334 }
5335
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005336 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005337 if (!lua_checkstack(stream->hlua.T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005338 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005339 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005340 return 0;
5341 }
5342
5343 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005344 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005345
5346 /* push arguments in the stack. */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005347 if (!hlua_txn_new(stream->hlua.T, stream, smp->px, smp->opt & SMP_OPT_DIR,
5348 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005349 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005350 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005351 return 0;
5352 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005353 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005354
5355 /* push keywords in the stack. */
5356 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5357 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005358 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005359 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005360 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005361 return 0;
5362 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005363 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005364 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005365 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005366 return 0;
5367 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005368 hlua_arg2lua(stream->hlua.T, arg_p);
5369 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005370 }
5371
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005372 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005373 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005374
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005375 /* At this point the execution is safe. */
5376 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005377 }
5378
5379 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005380 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005381 /* finished. */
5382 case HLUA_E_OK:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005383 if (!hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005384 return 0;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005385 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005386 hlua_lua2smp(stream->hlua.T, -1, smp);
5387 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005388
5389 /* Set the end of execution flag. */
5390 smp->flags &= ~SMP_F_MAY_CHANGE;
5391 return 1;
5392
5393 /* yield. */
5394 case HLUA_E_AGAIN:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005395 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005396 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005397 return 0;
5398
5399 /* finished with error. */
5400 case HLUA_E_ERRMSG:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005401 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005402 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005403 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
5404 fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005405 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005406 return 0;
5407
5408 case HLUA_E_ERR:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005409 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005410 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005411 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005412
5413 default:
5414 return 0;
5415 }
5416}
5417
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005418/* This function is an LUA binding used for registering
5419 * "sample-conv" functions. It expects a converter name used
5420 * in the haproxy configuration file, and an LUA function.
5421 */
5422__LJMP static int hlua_register_converters(lua_State *L)
5423{
5424 struct sample_conv_kw_list *sck;
5425 const char *name;
5426 int ref;
5427 int len;
5428 struct hlua_function *fcn;
5429
5430 MAY_LJMP(check_args(L, 2, "register_converters"));
5431
5432 /* First argument : converter name. */
5433 name = MAY_LJMP(luaL_checkstring(L, 1));
5434
5435 /* Second argument : lua function. */
5436 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5437
5438 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005439 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005440 if (!sck)
5441 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005442 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005443 if (!fcn)
5444 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5445
5446 /* Fill fcn. */
5447 fcn->name = strdup(name);
5448 if (!fcn->name)
5449 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5450 fcn->function_ref = ref;
5451
5452 /* List head */
5453 sck->list.n = sck->list.p = NULL;
5454
5455 /* converter keyword. */
5456 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005457 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005458 if (!sck->kw[0].kw)
5459 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5460
5461 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5462 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005463 sck->kw[0].arg_mask = ARG12(0,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005464 sck->kw[0].val_args = NULL;
5465 sck->kw[0].in_type = SMP_T_STR;
5466 sck->kw[0].out_type = SMP_T_STR;
5467 sck->kw[0].private = fcn;
5468
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005469 /* Register this new converter */
5470 sample_register_convs(sck);
5471
5472 return 0;
5473}
5474
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005475/* This fucntion is an LUA binding used for registering
5476 * "sample-fetch" functions. It expects a converter name used
5477 * in the haproxy configuration file, and an LUA function.
5478 */
5479__LJMP static int hlua_register_fetches(lua_State *L)
5480{
5481 const char *name;
5482 int ref;
5483 int len;
5484 struct sample_fetch_kw_list *sfk;
5485 struct hlua_function *fcn;
5486
5487 MAY_LJMP(check_args(L, 2, "register_fetches"));
5488
5489 /* First argument : sample-fetch name. */
5490 name = MAY_LJMP(luaL_checkstring(L, 1));
5491
5492 /* Second argument : lua function. */
5493 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5494
5495 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005496 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005497 if (!sfk)
5498 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005499 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005500 if (!fcn)
5501 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5502
5503 /* Fill fcn. */
5504 fcn->name = strdup(name);
5505 if (!fcn->name)
5506 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5507 fcn->function_ref = ref;
5508
5509 /* List head */
5510 sfk->list.n = sfk->list.p = NULL;
5511
5512 /* sample-fetch keyword. */
5513 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005514 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005515 if (!sfk->kw[0].kw)
5516 return luaL_error(L, "lua out of memory error.");
5517
5518 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5519 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005520 sfk->kw[0].arg_mask = ARG12(0,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005521 sfk->kw[0].val_args = NULL;
5522 sfk->kw[0].out_type = SMP_T_STR;
5523 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5524 sfk->kw[0].val = 0;
5525 sfk->kw[0].private = fcn;
5526
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005527 /* Register this new fetch. */
5528 sample_register_fetches(sfk);
5529
5530 return 0;
5531}
5532
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005533/* This function is a wrapper to execute each LUA function declared
5534 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005535 * return ACT_RET_CONT if the processing is finished (with or without
5536 * error) and return ACT_RET_YIELD if the function must be called again
5537 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005538 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005539static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005540 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005541{
5542 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005543 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005544 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005545 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005546
5547 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01005548 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
5549 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
5550 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
5551 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005552 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005553 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005554 return ACT_RET_CONT;
5555 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005556
Willy Tarreau87b09662015-04-03 00:22:06 +02005557 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005558 * Lua context can be not initialized. This behavior
5559 * permits to save performances because a systematic
5560 * Lua initialization cause 5% performances loss.
5561 */
5562 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005563 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005564 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005565 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005566 }
5567
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005568 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01005569 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005570
5571 /* The following Lua calls can fail. */
5572 if (!SET_SAFE_LJMP(s->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005573 if (lua_type(s->hlua.T, -1) == LUA_TSTRING)
5574 error = lua_tostring(s->hlua.T, -1);
5575 else
5576 error = "critical error";
5577 SEND_ERR(px, "Lua function '%s': %s.\n",
5578 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005579 return ACT_RET_CONT;
5580 }
5581
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005582 /* Check stack available size. */
5583 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005584 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005585 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005586 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005587 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005588 }
5589
5590 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005591 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005592
Willy Tarreau87b09662015-04-03 00:22:06 +02005593 /* Create and and push object stream in the stack. */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005594 if (!hlua_txn_new(s->hlua.T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005595 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005596 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005597 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005598 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005599 }
5600 s->hlua.nargs = 1;
5601
5602 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005603 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005604 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005605 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005606 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005607 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005608 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005609 }
5610 lua_pushstring(s->hlua.T, *arg);
5611 s->hlua.nargs++;
5612 }
5613
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005614 /* Now the execution is safe. */
5615 RESET_SAFE_LJMP(s->hlua.T);
5616
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005617 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005618 s->hlua.max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005619 }
5620
5621 /* Execute the function. */
Willy Tarreau528192d2015-09-27 10:48:01 +02005622 switch (hlua_ctx_resume(&s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005623 /* finished. */
5624 case HLUA_E_OK:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005625 if (!hlua_check_proto(s, dir))
5626 return ACT_RET_ERR;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005627 if (s->hlua.flags & HLUA_STOP)
5628 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005629 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005630
5631 /* yield. */
5632 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005633 /* Set timeout in the required channel. */
5634 if (s->hlua.wake_time != TICK_ETERNITY) {
5635 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005636 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005637 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005638 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005639 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005640 /* Some actions can be wake up when a "write" event
5641 * is detected on a response channel. This is useful
5642 * only for actions targetted on the requests.
5643 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01005644 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005645 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005646 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005647 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005648 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01005649 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005650 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005651 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005652
5653 /* finished with error. */
5654 case HLUA_E_ERRMSG:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005655 if (!hlua_check_proto(s, dir))
5656 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005657 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005658 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005659 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005660 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005661 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005662
5663 case HLUA_E_ERR:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005664 if (!hlua_check_proto(s, dir))
5665 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005666 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005667 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005668 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005669
5670 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005671 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005672 }
5673}
5674
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005675struct task *hlua_applet_wakeup(struct task *t)
5676{
5677 struct appctx *ctx = t->context;
5678 struct stream_interface *si = ctx->owner;
5679
5680 /* If the applet is wake up without any expected work, the sheduler
5681 * remove it from the run queue. This flag indicate that the applet
5682 * is waiting for write. If the buffer is full, the main processing
5683 * will send some data and after call the applet, otherwise it call
5684 * the applet ASAP.
5685 */
5686 si_applet_cant_put(si);
5687 appctx_wakeup(ctx);
5688 return NULL;
5689}
5690
5691static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5692{
5693 struct stream_interface *si = ctx->owner;
5694 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5695 struct task *task;
5696 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005697 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005698
5699 HLUA_INIT(hlua);
5700 ctx->ctx.hlua_apptcp.flags = 0;
5701
5702 /* Create task used by signal to wakeup applets. */
5703 task = task_new();
5704 if (!task) {
5705 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5706 ctx->rule->arg.hlua_rule->fcn.name);
5707 return 0;
5708 }
5709 task->nice = 0;
5710 task->context = ctx;
5711 task->process = hlua_applet_wakeup;
5712 ctx->ctx.hlua_apptcp.task = task;
5713
5714 /* In the execution wrappers linked with a stream, the
5715 * Lua context can be not initialized. This behavior
5716 * permits to save performances because a systematic
5717 * Lua initialization cause 5% performances loss.
5718 */
5719 if (!hlua_ctx_init(hlua, task)) {
5720 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
5721 ctx->rule->arg.hlua_rule->fcn.name);
5722 return 0;
5723 }
5724
5725 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005726 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005727
5728 /* The following Lua calls can fail. */
5729 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005730 if (lua_type(hlua->T, -1) == LUA_TSTRING)
5731 error = lua_tostring(hlua->T, -1);
5732 else
5733 error = "critical error";
5734 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
5735 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005736 RESET_SAFE_LJMP(hlua->T);
5737 return 0;
5738 }
5739
5740 /* Check stack available size. */
5741 if (!lua_checkstack(hlua->T, 1)) {
5742 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5743 ctx->rule->arg.hlua_rule->fcn.name);
5744 RESET_SAFE_LJMP(hlua->T);
5745 return 0;
5746 }
5747
5748 /* Restore the function in the stack. */
5749 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5750
5751 /* Create and and push object stream in the stack. */
5752 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
5753 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5754 ctx->rule->arg.hlua_rule->fcn.name);
5755 RESET_SAFE_LJMP(hlua->T);
5756 return 0;
5757 }
5758 hlua->nargs = 1;
5759
5760 /* push keywords in the stack. */
5761 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5762 if (!lua_checkstack(hlua->T, 1)) {
5763 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5764 ctx->rule->arg.hlua_rule->fcn.name);
5765 RESET_SAFE_LJMP(hlua->T);
5766 return 0;
5767 }
5768 lua_pushstring(hlua->T, *arg);
5769 hlua->nargs++;
5770 }
5771
5772 RESET_SAFE_LJMP(hlua->T);
5773
5774 /* Wakeup the applet ASAP. */
5775 si_applet_cant_get(si);
5776 si_applet_cant_put(si);
5777
5778 return 1;
5779}
5780
5781static void hlua_applet_tcp_fct(struct appctx *ctx)
5782{
5783 struct stream_interface *si = ctx->owner;
5784 struct stream *strm = si_strm(si);
5785 struct channel *res = si_ic(si);
5786 struct act_rule *rule = ctx->rule;
5787 struct proxy *px = strm->be;
5788 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5789
5790 /* The applet execution is already done. */
5791 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
5792 return;
5793
5794 /* If the stream is disconnect or closed, ldo nothing. */
5795 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5796 return;
5797
5798 /* Execute the function. */
5799 switch (hlua_ctx_resume(hlua, 1)) {
5800 /* finished. */
5801 case HLUA_E_OK:
5802 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5803
5804 /* log time */
5805 strm->logs.tv_request = now;
5806
5807 /* eat the whole request */
5808 bo_skip(si_oc(si), si_ob(si)->o);
5809 res->flags |= CF_READ_NULL;
5810 si_shutr(si);
5811 return;
5812
5813 /* yield. */
5814 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01005815 if (hlua->wake_time != TICK_ETERNITY)
5816 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005817 return;
5818
5819 /* finished with error. */
5820 case HLUA_E_ERRMSG:
5821 /* Display log. */
5822 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
5823 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
5824 lua_pop(hlua->T, 1);
5825 goto error;
5826
5827 case HLUA_E_ERR:
5828 /* Display log. */
5829 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
5830 rule->arg.hlua_rule->fcn.name);
5831 goto error;
5832
5833 default:
5834 goto error;
5835 }
5836
5837error:
5838
5839 /* For all other cases, just close the stream. */
5840 si_shutw(si);
5841 si_shutr(si);
5842 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5843}
5844
5845static void hlua_applet_tcp_release(struct appctx *ctx)
5846{
5847 task_free(ctx->ctx.hlua_apptcp.task);
5848 ctx->ctx.hlua_apptcp.task = NULL;
5849 hlua_ctx_destroy(&ctx->ctx.hlua_apptcp.hlua);
5850}
5851
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005852/* The function returns 1 if the initialisation is complete, 0 if
5853 * an errors occurs and -1 if more data are required for initializing
5854 * the applet.
5855 */
5856static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5857{
5858 struct stream_interface *si = ctx->owner;
5859 struct channel *req = si_oc(si);
5860 struct http_msg *msg;
5861 struct http_txn *txn;
5862 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5863 char **arg;
5864 struct hdr_ctx hdr;
5865 struct task *task;
5866 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01005867 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005868
5869 /* Wait for a full HTTP request. */
5870 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
5871 if (smp.flags & SMP_F_MAY_CHANGE)
5872 return -1;
5873 return 0;
5874 }
5875 txn = strm->txn;
5876 msg = &txn->req;
5877
Willy Tarreau0078bfc2015-10-07 20:20:28 +02005878 /* We want two things in HTTP mode :
5879 * - enforce server-close mode if we were in keep-alive, so that the
5880 * applet is released after each response ;
5881 * - enable request body transfer to the applet in order to resync
5882 * with the response body.
5883 */
5884 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
5885 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02005886
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005887 HLUA_INIT(hlua);
5888 ctx->ctx.hlua_apphttp.left_bytes = -1;
5889 ctx->ctx.hlua_apphttp.flags = 0;
5890
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01005891 if (txn->req.flags & HTTP_MSGF_VER_11)
5892 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
5893
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005894 /* Create task used by signal to wakeup applets. */
5895 task = task_new();
5896 if (!task) {
5897 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
5898 ctx->rule->arg.hlua_rule->fcn.name);
5899 return 0;
5900 }
5901 task->nice = 0;
5902 task->context = ctx;
5903 task->process = hlua_applet_wakeup;
5904 ctx->ctx.hlua_apphttp.task = task;
5905
5906 /* In the execution wrappers linked with a stream, the
5907 * Lua context can be not initialized. This behavior
5908 * permits to save performances because a systematic
5909 * Lua initialization cause 5% performances loss.
5910 */
5911 if (!hlua_ctx_init(hlua, task)) {
5912 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
5913 ctx->rule->arg.hlua_rule->fcn.name);
5914 return 0;
5915 }
5916
5917 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005918 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005919
5920 /* The following Lua calls can fail. */
5921 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005922 if (lua_type(hlua->T, -1) == LUA_TSTRING)
5923 error = lua_tostring(hlua->T, -1);
5924 else
5925 error = "critical error";
5926 SEND_ERR(px, "Lua applet http '%s': %s.\n",
5927 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005928 return 0;
5929 }
5930
5931 /* Check stack available size. */
5932 if (!lua_checkstack(hlua->T, 1)) {
5933 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5934 ctx->rule->arg.hlua_rule->fcn.name);
5935 RESET_SAFE_LJMP(hlua->T);
5936 return 0;
5937 }
5938
5939 /* Restore the function in the stack. */
5940 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5941
5942 /* Create and and push object stream in the stack. */
5943 if (!hlua_applet_http_new(hlua->T, ctx)) {
5944 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5945 ctx->rule->arg.hlua_rule->fcn.name);
5946 RESET_SAFE_LJMP(hlua->T);
5947 return 0;
5948 }
5949 hlua->nargs = 1;
5950
5951 /* Look for a 100-continue expected. */
5952 if (msg->flags & HTTP_MSGF_VER_11) {
5953 hdr.idx = 0;
5954 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
5955 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
5956 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
5957 }
5958
5959 /* push keywords in the stack. */
5960 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5961 if (!lua_checkstack(hlua->T, 1)) {
5962 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5963 ctx->rule->arg.hlua_rule->fcn.name);
5964 RESET_SAFE_LJMP(hlua->T);
5965 return 0;
5966 }
5967 lua_pushstring(hlua->T, *arg);
5968 hlua->nargs++;
5969 }
5970
5971 RESET_SAFE_LJMP(hlua->T);
5972
5973 /* Wakeup the applet when data is ready for read. */
5974 si_applet_cant_get(si);
5975
5976 return 1;
5977}
5978
5979static void hlua_applet_http_fct(struct appctx *ctx)
5980{
5981 struct stream_interface *si = ctx->owner;
5982 struct stream *strm = si_strm(si);
5983 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005984 struct act_rule *rule = ctx->rule;
5985 struct proxy *px = strm->be;
5986 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5987 char *blk1;
5988 int len1;
5989 char *blk2;
5990 int len2;
5991 int ret;
5992
5993 /* If the stream is disconnect or closed, ldo nothing. */
5994 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5995 return;
5996
5997 /* Set the currently running flag. */
5998 if (!HLUA_IS_RUNNING(hlua) &&
5999 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6000
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006001 /* Wait for full HTTP analysys. */
6002 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6003 si_applet_cant_get(si);
6004 return;
6005 }
6006
6007 /* Store the max amount of bytes that we can read. */
6008 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6009
6010 /* We need to flush the request header. This left the body
6011 * for the Lua.
6012 */
6013
6014 /* Read the maximum amount of data avalaible. */
6015 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
6016 if (ret == -1)
6017 return;
6018
6019 /* No data available, ask for more data. */
6020 if (ret == 1)
6021 len2 = 0;
6022 if (ret == 0)
6023 len1 = 0;
6024 if (len1 + len2 < strm->txn->req.eoh + 2) {
6025 si_applet_cant_get(si);
6026 return;
6027 }
6028
6029 /* skip the requests bytes. */
6030 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
6031 }
6032
6033 /* Executes The applet if it is not done. */
6034 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6035
6036 /* Execute the function. */
6037 switch (hlua_ctx_resume(hlua, 1)) {
6038 /* finished. */
6039 case HLUA_E_OK:
6040 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6041 break;
6042
6043 /* yield. */
6044 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006045 if (hlua->wake_time != TICK_ETERNITY)
6046 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006047 return;
6048
6049 /* finished with error. */
6050 case HLUA_E_ERRMSG:
6051 /* Display log. */
6052 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6053 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6054 lua_pop(hlua->T, 1);
6055 goto error;
6056
6057 case HLUA_E_ERR:
6058 /* Display log. */
6059 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6060 rule->arg.hlua_rule->fcn.name);
6061 goto error;
6062
6063 default:
6064 goto error;
6065 }
6066 }
6067
6068 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6069
6070 /* We must send the final chunk. */
6071 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6072 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6073
6074 /* sent last chunk at once. */
6075 ret = bi_putblk(res, "0\r\n\r\n", 5);
6076
6077 /* critical error. */
6078 if (ret == -2 || ret == -3) {
6079 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6080 rule->arg.hlua_rule->fcn.name);
6081 goto error;
6082 }
6083
6084 /* no enough space error. */
6085 if (ret == -1) {
6086 si_applet_cant_put(si);
6087 return;
6088 }
6089
6090 /* set the last chunk sent. */
6091 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6092 }
6093
6094 /* close the connection. */
6095
6096 /* status / log */
6097 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6098 strm->logs.tv_request = now;
6099
6100 /* eat the whole request */
6101 bo_skip(si_oc(si), si_ob(si)->o);
6102 res->flags |= CF_READ_NULL;
6103 si_shutr(si);
6104
6105 return;
6106 }
6107
6108error:
6109
6110 /* If we are in HTTP mode, and we are not send any
6111 * data, return a 500 server error in best effort:
6112 * if there are no room avalaible in the buffer,
6113 * just close the connection.
6114 */
6115 bi_putblk(res, error_500, strlen(error_500));
6116 if (!(strm->flags & SF_ERR_MASK))
6117 strm->flags |= SF_ERR_RESOURCE;
6118 si_shutw(si);
6119 si_shutr(si);
6120 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6121}
6122
6123static void hlua_applet_http_release(struct appctx *ctx)
6124{
6125 task_free(ctx->ctx.hlua_apphttp.task);
6126 ctx->ctx.hlua_apphttp.task = NULL;
6127 hlua_ctx_destroy(&ctx->ctx.hlua_apphttp.hlua);
6128}
6129
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006130/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6131 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006132 *
6133 * This function can fail with an abort() due to an Lua critical error.
6134 * We are in the configuration parsing process of HAProxy, this abort() is
6135 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006136 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006137static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6138 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006139{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006140 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006141
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006142 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006143 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006144 if (!rule->arg.hlua_rule) {
6145 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006146 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006147 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006148
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006149 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006150 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006151
6152 /* TODO: later accept arguments. */
6153 rule->arg.hlua_rule->args = NULL;
6154
Thierry FOURNIER42148732015-09-02 17:17:33 +02006155 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006156 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006157 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006158}
6159
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006160static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6161 struct act_rule *rule, char **err)
6162{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006163 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006164
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006165 /* HTTP applets are forbidden in tcp-request rules.
6166 * HTTP applet request requires everything initilized by
6167 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6168 * The applet will be immediately initilized, but its before
6169 * the call of this analyzer.
6170 */
6171 if (rule->from != ACT_F_HTTP_REQ) {
6172 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6173 return ACT_RET_PRS_ERR;
6174 }
6175
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006176 /* Memory for the rule. */
6177 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6178 if (!rule->arg.hlua_rule) {
6179 memprintf(err, "out of memory error");
6180 return ACT_RET_PRS_ERR;
6181 }
6182
6183 /* Reference the Lua function and store the reference. */
6184 rule->arg.hlua_rule->fcn = *fcn;
6185
6186 /* TODO: later accept arguments. */
6187 rule->arg.hlua_rule->args = NULL;
6188
6189 /* Add applet pointer in the rule. */
6190 rule->applet.obj_type = OBJ_TYPE_APPLET;
6191 rule->applet.name = fcn->name;
6192 rule->applet.init = hlua_applet_http_init;
6193 rule->applet.fct = hlua_applet_http_fct;
6194 rule->applet.release = hlua_applet_http_release;
6195 rule->applet.timeout = hlua_timeout_applet;
6196
6197 return ACT_RET_PRS_OK;
6198}
6199
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006200/* This function is an LUA binding used for registering
6201 * "sample-conv" functions. It expects a converter name used
6202 * in the haproxy configuration file, and an LUA function.
6203 */
6204__LJMP static int hlua_register_action(lua_State *L)
6205{
6206 struct action_kw_list *akl;
6207 const char *name;
6208 int ref;
6209 int len;
6210 struct hlua_function *fcn;
6211
Thierry FOURNIERed0bdaa2015-12-20 19:51:06 +01006212 MAY_LJMP(check_args(L, 3, "register_action"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006213
6214 /* First argument : converter name. */
6215 name = MAY_LJMP(luaL_checkstring(L, 1));
6216
6217 /* Second argument : environment. */
6218 if (lua_type(L, 2) != LUA_TTABLE)
6219 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6220
6221 /* Third argument : lua function. */
6222 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6223
6224 /* browse the second argulent as an array. */
6225 lua_pushnil(L);
6226 while (lua_next(L, 2) != 0) {
6227 if (lua_type(L, -1) != LUA_TSTRING)
6228 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6229
6230 /* Check required environment. Only accepted "http" or "tcp". */
6231 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006232 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006233 if (!akl)
6234 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006235 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006236 if (!fcn)
6237 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6238
6239 /* Fill fcn. */
6240 fcn->name = strdup(name);
6241 if (!fcn->name)
6242 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6243 fcn->function_ref = ref;
6244
6245 /* List head */
6246 akl->list.n = akl->list.p = NULL;
6247
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006248 /* action keyword. */
6249 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006250 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006251 if (!akl->kw[0].kw)
6252 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6253
6254 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6255
6256 akl->kw[0].match_pfx = 0;
6257 akl->kw[0].private = fcn;
6258 akl->kw[0].parse = action_register_lua;
6259
6260 /* select the action registering point. */
6261 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6262 tcp_req_cont_keywords_register(akl);
6263 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6264 tcp_res_cont_keywords_register(akl);
6265 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6266 http_req_keywords_register(akl);
6267 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6268 http_res_keywords_register(akl);
6269 else
6270 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6271 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6272 "are expected.", lua_tostring(L, -1)));
6273
6274 /* pop the environment string. */
6275 lua_pop(L, 1);
6276 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006277 return ACT_RET_PRS_OK;
6278}
6279
6280static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6281 struct act_rule *rule, char **err)
6282{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006283 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006284
6285 /* Memory for the rule. */
6286 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6287 if (!rule->arg.hlua_rule) {
6288 memprintf(err, "out of memory error");
6289 return ACT_RET_PRS_ERR;
6290 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006291
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006292 /* Reference the Lua function and store the reference. */
6293 rule->arg.hlua_rule->fcn = *fcn;
6294
6295 /* TODO: later accept arguments. */
6296 rule->arg.hlua_rule->args = NULL;
6297
6298 /* Add applet pointer in the rule. */
6299 rule->applet.obj_type = OBJ_TYPE_APPLET;
6300 rule->applet.name = fcn->name;
6301 rule->applet.init = hlua_applet_tcp_init;
6302 rule->applet.fct = hlua_applet_tcp_fct;
6303 rule->applet.release = hlua_applet_tcp_release;
6304 rule->applet.timeout = hlua_timeout_applet;
6305
6306 return 0;
6307}
6308
6309/* This function is an LUA binding used for registering
6310 * "sample-conv" functions. It expects a converter name used
6311 * in the haproxy configuration file, and an LUA function.
6312 */
6313__LJMP static int hlua_register_service(lua_State *L)
6314{
6315 struct action_kw_list *akl;
6316 const char *name;
6317 const char *env;
6318 int ref;
6319 int len;
6320 struct hlua_function *fcn;
6321
6322 MAY_LJMP(check_args(L, 3, "register_service"));
6323
6324 /* First argument : converter name. */
6325 name = MAY_LJMP(luaL_checkstring(L, 1));
6326
6327 /* Second argument : environment. */
6328 env = MAY_LJMP(luaL_checkstring(L, 2));
6329
6330 /* Third argument : lua function. */
6331 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6332
6333 /* Check required environment. Only accepted "http" or "tcp". */
6334 /* Allocate and fill the sample fetch keyword struct. */
6335 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6336 if (!akl)
6337 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6338 fcn = calloc(1, sizeof(*fcn));
6339 if (!fcn)
6340 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6341
6342 /* Fill fcn. */
6343 len = strlen("<lua.>") + strlen(name) + 1;
6344 fcn->name = calloc(1, len);
6345 if (!fcn->name)
6346 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6347 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6348 fcn->function_ref = ref;
6349
6350 /* List head */
6351 akl->list.n = akl->list.p = NULL;
6352
6353 /* converter keyword. */
6354 len = strlen("lua.") + strlen(name) + 1;
6355 akl->kw[0].kw = calloc(1, len);
6356 if (!akl->kw[0].kw)
6357 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6358
6359 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6360
6361 if (strcmp(env, "tcp") == 0)
6362 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006363 else if (strcmp(env, "http") == 0)
6364 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006365 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006366 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6367 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006368
6369 akl->kw[0].match_pfx = 0;
6370 akl->kw[0].private = fcn;
6371
6372 /* End of array. */
6373 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6374
6375 /* Register this new converter */
6376 service_keywords_register(akl);
6377
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006378 return 0;
6379}
6380
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006381static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
6382 struct proxy *defpx, const char *file, int line,
6383 char **err, unsigned int *timeout)
6384{
6385 const char *error;
6386
6387 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
6388 if (error && *error != '\0') {
6389 memprintf(err, "%s: invalid timeout", args[0]);
6390 return -1;
6391 }
6392 return 0;
6393}
6394
6395static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
6396 struct proxy *defpx, const char *file, int line,
6397 char **err)
6398{
6399 return hlua_read_timeout(args, section_type, curpx, defpx,
6400 file, line, err, &hlua_timeout_session);
6401}
6402
6403static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
6404 struct proxy *defpx, const char *file, int line,
6405 char **err)
6406{
6407 return hlua_read_timeout(args, section_type, curpx, defpx,
6408 file, line, err, &hlua_timeout_task);
6409}
6410
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006411static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
6412 struct proxy *defpx, const char *file, int line,
6413 char **err)
6414{
6415 return hlua_read_timeout(args, section_type, curpx, defpx,
6416 file, line, err, &hlua_timeout_applet);
6417}
6418
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006419static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
6420 struct proxy *defpx, const char *file, int line,
6421 char **err)
6422{
6423 char *error;
6424
6425 hlua_nb_instruction = strtoll(args[1], &error, 10);
6426 if (*error != '\0') {
6427 memprintf(err, "%s: invalid number", args[0]);
6428 return -1;
6429 }
6430 return 0;
6431}
6432
Willy Tarreau32f61e22015-03-18 17:54:59 +01006433static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
6434 struct proxy *defpx, const char *file, int line,
6435 char **err)
6436{
6437 char *error;
6438
6439 if (*(args[1]) == 0) {
6440 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
6441 return -1;
6442 }
6443 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
6444 if (*error != '\0') {
6445 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
6446 return -1;
6447 }
6448 return 0;
6449}
6450
6451
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006452/* This function is called by the main configuration key "lua-load". It loads and
6453 * execute an lua file during the parsing of the HAProxy configuration file. It is
6454 * the main lua entry point.
6455 *
6456 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
6457 * occured, otherwise it returns 0.
6458 *
6459 * In some error case, LUA set an error message in top of the stack. This function
6460 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006461 *
6462 * This function can fail with an abort() due to an Lua critical error.
6463 * We are in the configuration parsing process of HAProxy, this abort() is
6464 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006465 */
6466static int hlua_load(char **args, int section_type, struct proxy *curpx,
6467 struct proxy *defpx, const char *file, int line,
6468 char **err)
6469{
6470 int error;
6471
6472 /* Just load and compile the file. */
6473 error = luaL_loadfile(gL.T, args[1]);
6474 if (error) {
6475 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
6476 lua_pop(gL.T, 1);
6477 return -1;
6478 }
6479
6480 /* If no syntax error where detected, execute the code. */
6481 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
6482 switch (error) {
6483 case LUA_OK:
6484 break;
6485 case LUA_ERRRUN:
6486 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
6487 lua_pop(gL.T, 1);
6488 return -1;
6489 case LUA_ERRMEM:
6490 memprintf(err, "lua out of memory error\n");
6491 return -1;
6492 case LUA_ERRERR:
6493 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
6494 lua_pop(gL.T, 1);
6495 return -1;
6496 case LUA_ERRGCMM:
6497 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
6498 lua_pop(gL.T, 1);
6499 return -1;
6500 default:
6501 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
6502 lua_pop(gL.T, 1);
6503 return -1;
6504 }
6505
6506 return 0;
6507}
6508
6509/* configuration keywords declaration */
6510static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006511 { CFG_GLOBAL, "lua-load", hlua_load },
6512 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
6513 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02006514 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006515 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01006516 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006517 { 0, NULL, NULL },
6518}};
6519
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006520/* This function can fail with an abort() due to an Lua critical error.
6521 * We are in the initialisation process of HAProxy, this abort() is
6522 * tolerated.
6523 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006524int hlua_post_init()
6525{
6526 struct hlua_init_function *init;
6527 const char *msg;
6528 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006529 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006530
Thierry Fournier3d4a6752016-02-19 20:53:30 +01006531 /* Call post initialisation function in safe environement. */
6532 if (!SET_SAFE_LJMP(gL.T)) {
6533 if (lua_type(gL.T, -1) == LUA_TSTRING)
6534 error = lua_tostring(gL.T, -1);
6535 else
6536 error = "critical error";
6537 fprintf(stderr, "Lua post-init: %s.\n", error);
6538 exit(1);
6539 }
6540 hlua_fcn_post_init(gL.T);
6541 RESET_SAFE_LJMP(gL.T);
6542
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006543 list_for_each_entry(init, &hlua_init_functions, l) {
6544 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
6545 ret = hlua_ctx_resume(&gL, 0);
6546 switch (ret) {
6547 case HLUA_E_OK:
6548 lua_pop(gL.T, -1);
6549 return 1;
6550 case HLUA_E_AGAIN:
6551 Alert("lua init: yield not allowed.\n");
6552 return 0;
6553 case HLUA_E_ERRMSG:
6554 msg = lua_tostring(gL.T, -1);
6555 Alert("lua init: %s.\n", msg);
6556 return 0;
6557 case HLUA_E_ERR:
6558 default:
6559 Alert("lua init: unknown runtime error.\n");
6560 return 0;
6561 }
6562 }
6563 return 1;
6564}
6565
Willy Tarreau32f61e22015-03-18 17:54:59 +01006566/* The memory allocator used by the Lua stack. <ud> is a pointer to the
6567 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
6568 * is the previously allocated size or the kind of object in case of a new
6569 * allocation. <nsize> is the requested new size.
6570 */
6571static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
6572{
6573 struct hlua_mem_allocator *zone = ud;
6574
6575 if (nsize == 0) {
6576 /* it's a free */
6577 if (ptr)
6578 zone->allocated -= osize;
6579 free(ptr);
6580 return NULL;
6581 }
6582
6583 if (!ptr) {
6584 /* it's a new allocation */
6585 if (zone->limit && zone->allocated + nsize > zone->limit)
6586 return NULL;
6587
6588 ptr = malloc(nsize);
6589 if (ptr)
6590 zone->allocated += nsize;
6591 return ptr;
6592 }
6593
6594 /* it's a realloc */
6595 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
6596 return NULL;
6597
6598 ptr = realloc(ptr, nsize);
6599 if (ptr)
6600 zone->allocated += nsize - osize;
6601 return ptr;
6602}
6603
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006604/* Ithis function can fail with an abort() due to an Lua critical error.
6605 * We are in the initialisation process of HAProxy, this abort() is
6606 * tolerated.
6607 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01006608void hlua_init(void)
6609{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006610 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006611 int idx;
6612 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006613 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006614 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006615 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006616#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006617 struct srv_kw *kw;
6618 int tmp_error;
6619 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01006620 char *args[] = { /* SSL client configuration. */
6621 "ssl",
6622 "verify",
6623 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01006624 NULL
6625 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006626#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006627
Willy Tarreau87b09662015-04-03 00:22:06 +02006628 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006629 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
6630
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006631 /* Register configuration keywords. */
6632 cfg_register_keywords(&cfg_kws);
6633
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006634 /* Init main lua stack. */
6635 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01006636 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006637 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006638 gL.T = luaL_newstate();
6639 hlua_sethlua(&gL);
6640 gL.Tref = LUA_REFNIL;
6641 gL.task = NULL;
6642
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006643 /* From this point, until the end of the initialisation fucntion,
6644 * the Lua function can fail with an abort. We are in the initialisation
6645 * process of HAProxy, this abort() is tolerated.
6646 */
6647
Willy Tarreau32f61e22015-03-18 17:54:59 +01006648 /* change the memory allocators to track memory usage */
6649 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
6650
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006651 /* Initialise lua. */
6652 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006653
Thierry Fournier75933d42016-01-21 09:30:18 +01006654 /* Set safe environment for the initialisation. */
6655 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006656 if (lua_type(gL.T, -1) == LUA_TSTRING)
6657 error_msg = lua_tostring(gL.T, -1);
6658 else
6659 error_msg = "critical error";
6660 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01006661 exit(1);
6662 }
6663
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006664 /*
6665 *
6666 * Create "core" object.
6667 *
6668 */
6669
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01006670 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006671 lua_newtable(gL.T);
6672
6673 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006674 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006675 hlua_class_const_int(gL.T, log_levels[i], i);
6676
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006677 /* Register special functions. */
6678 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006679 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006680 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006681 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006682 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006683 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006684 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01006685 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006686 hlua_class_function(gL.T, "sleep", hlua_sleep);
6687 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01006688 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
6689 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
6690 hlua_class_function(gL.T, "set_map", hlua_set_map);
6691 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006692 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006693 hlua_class_function(gL.T, "log", hlua_log);
6694 hlua_class_function(gL.T, "Debug", hlua_log_debug);
6695 hlua_class_function(gL.T, "Info", hlua_log_info);
6696 hlua_class_function(gL.T, "Warning", hlua_log_warning);
6697 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02006698 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01006699 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006700
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006701 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006702
6703 /*
6704 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006705 * Register class Map
6706 *
6707 */
6708
6709 /* This table entry is the object "Map" base. */
6710 lua_newtable(gL.T);
6711
6712 /* register pattern types. */
6713 for (i=0; i<PAT_MATCH_NUM; i++)
6714 hlua_class_const_int(gL.T, pat_match_names[i], i);
6715
6716 /* register constructor. */
6717 hlua_class_function(gL.T, "new", hlua_map_new);
6718
6719 /* Create and fill the metatable. */
6720 lua_newtable(gL.T);
6721
6722 /* Create and fille the __index entry. */
6723 lua_pushstring(gL.T, "__index");
6724 lua_newtable(gL.T);
6725
6726 /* Register . */
6727 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
6728 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
6729
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006730 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006731
Thierry Fournier45e78d72016-02-19 18:34:46 +01006732 /* Register previous table in the registry with reference and named entry.
6733 * The function hlua_register_metatable() pops the stack, so we
6734 * previously create a copy of the table.
6735 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006736 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01006737 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006738
6739 /* Assign the metatable to the mai Map object. */
6740 lua_setmetatable(gL.T, -2);
6741
6742 /* Set a name to the table. */
6743 lua_setglobal(gL.T, "Map");
6744
6745 /*
6746 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006747 * Register class Channel
6748 *
6749 */
6750
6751 /* Create and fill the metatable. */
6752 lua_newtable(gL.T);
6753
6754 /* Create and fille the __index entry. */
6755 lua_pushstring(gL.T, "__index");
6756 lua_newtable(gL.T);
6757
6758 /* Register . */
6759 hlua_class_function(gL.T, "get", hlua_channel_get);
6760 hlua_class_function(gL.T, "dup", hlua_channel_dup);
6761 hlua_class_function(gL.T, "getline", hlua_channel_getline);
6762 hlua_class_function(gL.T, "set", hlua_channel_set);
6763 hlua_class_function(gL.T, "append", hlua_channel_append);
6764 hlua_class_function(gL.T, "send", hlua_channel_send);
6765 hlua_class_function(gL.T, "forward", hlua_channel_forward);
6766 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
6767 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
6768
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006769 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006770
6771 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01006772 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006773
6774 /*
6775 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006776 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006777 *
6778 */
6779
6780 /* Create and fill the metatable. */
6781 lua_newtable(gL.T);
6782
6783 /* Create and fille the __index entry. */
6784 lua_pushstring(gL.T, "__index");
6785 lua_newtable(gL.T);
6786
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006787 /* Browse existing fetches and create the associated
6788 * object method.
6789 */
6790 sf = NULL;
6791 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
6792
6793 /* Dont register the keywork if the arguments check function are
6794 * not safe during the runtime.
6795 */
6796 if ((sf->val_args != NULL) &&
6797 (sf->val_args != val_payload_lv) &&
6798 (sf->val_args != val_hdr))
6799 continue;
6800
6801 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
6802 * by an underscore.
6803 */
6804 strncpy(trash.str, sf->kw, trash.size);
6805 trash.str[trash.size - 1] = '\0';
6806 for (p = trash.str; *p; p++)
6807 if (*p == '.' || *p == '-' || *p == '+')
6808 *p = '_';
6809
6810 /* Register the function. */
6811 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01006812 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006813 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006814 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006815 }
6816
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006817 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006818
6819 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01006820 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006821
6822 /*
6823 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006824 * Register class Converters
6825 *
6826 */
6827
6828 /* Create and fill the metatable. */
6829 lua_newtable(gL.T);
6830
6831 /* Create and fill the __index entry. */
6832 lua_pushstring(gL.T, "__index");
6833 lua_newtable(gL.T);
6834
6835 /* Browse existing converters and create the associated
6836 * object method.
6837 */
6838 sc = NULL;
6839 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
6840 /* Dont register the keywork if the arguments check function are
6841 * not safe during the runtime.
6842 */
6843 if (sc->val_args != NULL)
6844 continue;
6845
6846 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
6847 * by an underscore.
6848 */
6849 strncpy(trash.str, sc->kw, trash.size);
6850 trash.str[trash.size - 1] = '\0';
6851 for (p = trash.str; *p; p++)
6852 if (*p == '.' || *p == '-' || *p == '+')
6853 *p = '_';
6854
6855 /* Register the function. */
6856 lua_pushstring(gL.T, trash.str);
6857 lua_pushlightuserdata(gL.T, sc);
6858 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006859 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006860 }
6861
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006862 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006863
6864 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01006865 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006866
6867 /*
6868 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006869 * Register class HTTP
6870 *
6871 */
6872
6873 /* Create and fill the metatable. */
6874 lua_newtable(gL.T);
6875
6876 /* Create and fille the __index entry. */
6877 lua_pushstring(gL.T, "__index");
6878 lua_newtable(gL.T);
6879
6880 /* Register Lua functions. */
6881 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
6882 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
6883 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
6884 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
6885 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
6886 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
6887 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
6888 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
6889 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
6890 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
6891
6892 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
6893 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
6894 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
6895 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
6896 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
6897 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006898 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006899
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006900 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006901
6902 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01006903 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006904
6905 /*
6906 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006907 * Register class AppletTCP
6908 *
6909 */
6910
6911 /* Create and fill the metatable. */
6912 lua_newtable(gL.T);
6913
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006914 /* Create and fille the __index entry. */
6915 lua_pushstring(gL.T, "__index");
6916 lua_newtable(gL.T);
6917
6918 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01006919 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
6920 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
6921 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
6922 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
6923 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006924
6925 lua_settable(gL.T, -3);
6926
6927 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01006928 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006929
6930 /*
6931 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006932 * Register class AppletHTTP
6933 *
6934 */
6935
6936 /* Create and fill the metatable. */
6937 lua_newtable(gL.T);
6938
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006939 /* Create and fille the __index entry. */
6940 lua_pushstring(gL.T, "__index");
6941 lua_newtable(gL.T);
6942
6943 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01006944 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
6945 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006946 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
6947 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
6948 hlua_class_function(gL.T, "send", hlua_applet_http_send);
6949 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
6950 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
6951 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
6952
6953 lua_settable(gL.T, -3);
6954
6955 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01006956 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006957
6958 /*
6959 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006960 * Register class TXN
6961 *
6962 */
6963
6964 /* Create and fill the metatable. */
6965 lua_newtable(gL.T);
6966
6967 /* Create and fille the __index entry. */
6968 lua_pushstring(gL.T, "__index");
6969 lua_newtable(gL.T);
6970
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006971 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01006972 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
6973 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006974 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01006975 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006976 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006977 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006978 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
6979 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
6980 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006981 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
6982 hlua_class_function(gL.T, "log", hlua_txn_log);
6983 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
6984 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
6985 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
6986 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006987
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006988 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006989
6990 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01006991 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006992
6993 /*
6994 *
6995 * Register class Socket
6996 *
6997 */
6998
6999 /* Create and fill the metatable. */
7000 lua_newtable(gL.T);
7001
7002 /* Create and fille the __index entry. */
7003 lua_pushstring(gL.T, "__index");
7004 lua_newtable(gL.T);
7005
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007006#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007007 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007008#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007009 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7010 hlua_class_function(gL.T, "send", hlua_socket_send);
7011 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7012 hlua_class_function(gL.T, "close", hlua_socket_close);
7013 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7014 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7015 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7016 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7017
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007018 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007019
7020 /* Register the garbage collector entry. */
7021 lua_pushstring(gL.T, "__gc");
7022 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007023 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007024
7025 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007026 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007027
7028 /* Proxy and server configuration initialisation. */
7029 memset(&socket_proxy, 0, sizeof(socket_proxy));
7030 init_new_proxy(&socket_proxy);
7031 socket_proxy.parent = NULL;
7032 socket_proxy.last_change = now.tv_sec;
7033 socket_proxy.id = "LUA-SOCKET";
7034 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7035 socket_proxy.maxconn = 0;
7036 socket_proxy.accept = NULL;
7037 socket_proxy.options2 |= PR_O2_INDEPSTR;
7038 socket_proxy.srv = NULL;
7039 socket_proxy.conn_retries = 0;
7040 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7041
7042 /* Init TCP server: unchanged parameters */
7043 memset(&socket_tcp, 0, sizeof(socket_tcp));
7044 socket_tcp.next = NULL;
7045 socket_tcp.proxy = &socket_proxy;
7046 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7047 LIST_INIT(&socket_tcp.actconns);
7048 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007049 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007050 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007051 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007052 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
7053 socket_tcp.last_change = 0;
7054 socket_tcp.id = "LUA-TCP-CONN";
7055 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7056 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7057 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7058
7059 /* XXX: Copy default parameter from default server,
7060 * but the default server is not initialized.
7061 */
7062 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7063 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7064 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7065 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7066 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7067 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7068 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7069 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7070 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7071 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7072
7073 socket_tcp.check.status = HCHK_STATUS_INI;
7074 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7075 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7076 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7077 socket_tcp.check.server = &socket_tcp;
7078
7079 socket_tcp.agent.status = HCHK_STATUS_INI;
7080 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7081 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7082 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7083 socket_tcp.agent.server = &socket_tcp;
7084
7085 socket_tcp.xprt = &raw_sock;
7086
7087#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007088 /* Init TCP server: unchanged parameters */
7089 memset(&socket_ssl, 0, sizeof(socket_ssl));
7090 socket_ssl.next = NULL;
7091 socket_ssl.proxy = &socket_proxy;
7092 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7093 LIST_INIT(&socket_ssl.actconns);
7094 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007095 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007096 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007097 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007098 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
7099 socket_ssl.last_change = 0;
7100 socket_ssl.id = "LUA-SSL-CONN";
7101 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7102 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7103 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7104
7105 /* XXX: Copy default parameter from default server,
7106 * but the default server is not initialized.
7107 */
7108 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7109 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7110 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7111 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7112 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7113 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7114 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7115 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7116 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7117 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7118
7119 socket_ssl.check.status = HCHK_STATUS_INI;
7120 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7121 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7122 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7123 socket_ssl.check.server = &socket_ssl;
7124
7125 socket_ssl.agent.status = HCHK_STATUS_INI;
7126 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7127 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7128 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7129 socket_ssl.agent.server = &socket_ssl;
7130
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007131 socket_ssl.use_ssl = 1;
7132 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007133
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007134 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007135 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7136 /*
7137 *
7138 * If the keyword is not known, we can search in the registered
7139 * server keywords. This is usefull to configure special SSL
7140 * features like client certificates and ssl_verify.
7141 *
7142 */
7143 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7144 if (tmp_error != 0) {
7145 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7146 abort(); /* This must be never arrives because the command line
7147 not editable by the user. */
7148 }
7149 idx += kw->skip;
7150 }
7151 }
7152
7153 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007154 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007155#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007156
7157 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007158}