blob: d5b54ff75f4495133f75ee03264adacdc53057f7 [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 FOURNIERc798b5d2015-03-17 01:09:57 +010013#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020014#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010016#include <lauxlib.h>
17#include <lua.h>
18#include <lualib.h>
19
Thierry FOURNIER463119c2015-03-10 00:35:36 +010020#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
21#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010022#endif
23
Thierry FOURNIER380d0932015-01-23 14:27:52 +010024#include <ebpttree.h>
25
26#include <common/cfgparse.h>
27
William Lallemand9ed62032016-11-21 17:49:11 +010028#include <types/cli.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010029#include <types/hlua.h>
30#include <types/proxy.h>
William Lallemand9ed62032016-11-21 17:49:11 +010031#include <types/stats.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010032
Thierry FOURNIER55da1652015-01-23 11:36:30 +010033#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020034#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010035#include <proto/channel.h>
William Lallemand9ed62032016-11-21 17:49:11 +010036#include <proto/cli.h>
Willy Tarreaua71f6422016-11-16 17:00:14 +010037#include <proto/connection.h>
William Lallemand9ed62032016-11-21 17:49:11 +010038#include <proto/stats.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010039#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010040#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010041#include <proto/hlua_fcn.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020042#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010043#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010044#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010045#include <proto/payload.h>
46#include <proto/proto_http.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010047#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010048#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010049#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020050#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020051#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010052#include <proto/ssl_sock.h>
53#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010054#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010055#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020056#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010057
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010058/* Lua uses longjmp to perform yield or throwing errors. This
59 * macro is used only for identifying the function that can
60 * not return because a longjmp is executed.
61 * __LJMP marks a prototype of hlua file that can use longjmp.
62 * WILL_LJMP() marks an lua function that will use longjmp.
63 * MAY_LJMP() marks an lua function that may use longjmp.
64 */
65#define __LJMP
66#define WILL_LJMP(func) func
67#define MAY_LJMP(func) func
68
Thierry FOURNIERbabae282015-09-17 11:36:37 +020069/* This couple of function executes securely some Lua calls outside of
70 * the lua runtime environment. Each Lua call can return a longjmp
71 * if it encounter a memory error.
72 *
73 * Lua documentation extract:
74 *
75 * If an error happens outside any protected environment, Lua calls
76 * a panic function (see lua_atpanic) and then calls abort, thus
77 * exiting the host application. Your panic function can avoid this
78 * exit by never returning (e.g., doing a long jump to your own
79 * recovery point outside Lua).
80 *
81 * The panic function runs as if it were a message handler (see
82 * §2.3); in particular, the error message is at the top of the
83 * stack. However, there is no guarantee about stack space. To push
84 * anything on the stack, the panic function must first check the
85 * available space (see §4.2).
86 *
87 * We must check all the Lua entry point. This includes:
88 * - The include/proto/hlua.h exported functions
89 * - the task wrapper function
90 * - The action wrapper function
91 * - The converters wrapper function
92 * - The sample-fetch wrapper functions
93 *
94 * It is tolerated that the initilisation function returns an abort.
95 * Before each Lua abort, an error message is writed on stderr.
96 *
97 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
98 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
99 * because they must be exists in the program stack when the longjmp
100 * is called.
101 */
102jmp_buf safe_ljmp_env;
103static int hlua_panic_safe(lua_State *L) { return 0; }
104static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
105
106#define SET_SAFE_LJMP(__L) \
107 ({ \
108 int ret; \
109 if (setjmp(safe_ljmp_env) != 0) { \
110 lua_atpanic(__L, hlua_panic_safe); \
111 ret = 0; \
112 } else { \
113 lua_atpanic(__L, hlua_panic_ljmp); \
114 ret = 1; \
115 } \
116 ret; \
117 })
118
119/* If we are the last function catching Lua errors, we
120 * must reset the panic function.
121 */
122#define RESET_SAFE_LJMP(__L) \
123 do { \
124 lua_atpanic(__L, hlua_panic_safe); \
125 } while(0)
126
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200127/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200128#define APPLET_DONE 0x01 /* applet processing is done. */
129#define APPLET_100C 0x02 /* 100 continue expected. */
130#define APPLET_HDR_SENT 0x04 /* Response header sent. */
131#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
132#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100133#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200134
135#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200136
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100137/* The main Lua execution context. */
138struct hlua gL;
139
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100140/* This is the memory pool containing all the signal structs. These
141 * struct are used to store each requiered signal between two tasks.
142 */
143struct pool_head *pool2_hlua_com;
144
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100145/* Used for Socket connection. */
146static struct proxy socket_proxy;
147static struct server socket_tcp;
148#ifdef USE_OPENSSL
149static struct server socket_ssl;
150#endif
151
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100152/* List head of the function called at the initialisation time. */
153struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
154
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100155/* The following variables contains the reference of the different
156 * Lua classes. These references are useful for identify metadata
157 * associated with an object.
158 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100159static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100160static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100161static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100162static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100163static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100164static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200165static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200166static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200167static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100168
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100169/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200170 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100171 * short timeout. Lua linked with tasks doesn't have a timeout
172 * because a task may remain alive during all the haproxy execution.
173 */
174static unsigned int hlua_timeout_session = 4000; /* session timeout. */
175static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200176static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100177
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100178/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
179 * it is used for preventing infinite loops.
180 *
181 * I test the scheer with an infinite loop containing one incrementation
182 * and one test. I run this loop between 10 seconds, I raise a ceil of
183 * 710M loops from one interrupt each 9000 instructions, so I fix the value
184 * to one interrupt each 10 000 instructions.
185 *
186 * configured | Number of
187 * instructions | loops executed
188 * between two | in milions
189 * forced yields |
190 * ---------------+---------------
191 * 10 | 160
192 * 500 | 670
193 * 1000 | 680
194 * 5000 | 700
195 * 7000 | 700
196 * 8000 | 700
197 * 9000 | 710 <- ceil
198 * 10000 | 710
199 * 100000 | 710
200 * 1000000 | 710
201 *
202 */
203static unsigned int hlua_nb_instruction = 10000;
204
Willy Tarreau32f61e22015-03-18 17:54:59 +0100205/* Descriptor for the memory allocation state. If limit is not null, it will
206 * be enforced on any memory allocation.
207 */
208struct hlua_mem_allocator {
209 size_t allocated;
210 size_t limit;
211};
212
213static struct hlua_mem_allocator hlua_global_allocator;
214
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200215static const char error_500[] =
216 "HTTP/1.0 500 Server Error\r\n"
217 "Cache-Control: no-cache\r\n"
218 "Connection: close\r\n"
219 "Content-Type: text/html\r\n"
220 "\r\n"
221 "<html><body><h1>500 Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
222
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100223/* These functions converts types between HAProxy internal args or
224 * sample and LUA types. Another function permits to check if the
225 * LUA stack contains arguments according with an required ARG_T
226 * format.
227 */
228static int hlua_arg2lua(lua_State *L, const struct arg *arg);
229static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100230__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100231 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100232static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100233static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100234static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
235
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200236__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
237
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200238#define SEND_ERR(__be, __fmt, __args...) \
239 do { \
240 send_log(__be, LOG_ERR, __fmt, ## __args); \
241 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
242 Alert(__fmt, ## __args); \
243 } while (0)
244
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100245/* Used to check an Lua function type in the stack. It creates and
246 * returns a reference of the function. This function throws an
247 * error if the rgument is not a "function".
248 */
249__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
250{
251 if (!lua_isfunction(L, argno)) {
252 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
253 WILL_LJMP(luaL_argerror(L, argno, msg));
254 }
255 lua_pushvalue(L, argno);
256 return luaL_ref(L, LUA_REGISTRYINDEX);
257}
258
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200259/* Return the string that is of the top of the stack. */
260const char *hlua_get_top_error_string(lua_State *L)
261{
262 if (lua_gettop(L) < 1)
263 return "unknown error";
264 if (lua_type(L, -1) != LUA_TSTRING)
265 return "unknown error";
266 return lua_tostring(L, -1);
267}
268
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100269/* This function check the number of arguments available in the
270 * stack. If the number of arguments available is not the same
271 * then <nb> an error is throwed.
272 */
273__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
274{
275 if (lua_gettop(L) == nb)
276 return;
277 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
278}
279
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100280/* This fucntion push an error string prefixed by the file name
281 * and the line number where the error is encountered.
282 */
283static int hlua_pusherror(lua_State *L, const char *fmt, ...)
284{
285 va_list argp;
286 va_start(argp, fmt);
287 luaL_where(L, 1);
288 lua_pushvfstring(L, fmt, argp);
289 va_end(argp);
290 lua_concat(L, 2);
291 return 1;
292}
293
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100294/* This function register a new signal. "lua" is the current lua
295 * execution context. It contains a pointer to the associated task.
296 * "link" is a list head attached to an other task that must be wake
297 * the lua task if an event occurs. This is useful with external
298 * events like TCP I/O or sleep functions. This funcion allocate
299 * memory for the signal.
300 */
301static int hlua_com_new(struct hlua *lua, struct list *link)
302{
303 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
304 if (!com)
305 return 0;
306 LIST_ADDQ(&lua->com, &com->purge_me);
307 LIST_ADDQ(link, &com->wake_me);
308 com->task = lua->task;
309 return 1;
310}
311
312/* This function purge all the pending signals when the LUA execution
313 * is finished. This prevent than a coprocess try to wake a deleted
314 * task. This function remove the memory associated to the signal.
315 */
316static void hlua_com_purge(struct hlua *lua)
317{
318 struct hlua_com *com, *back;
319
320 /* Delete all pending communication signals. */
321 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
322 LIST_DEL(&com->purge_me);
323 LIST_DEL(&com->wake_me);
324 pool_free2(pool2_hlua_com, com);
325 }
326}
327
328/* This function sends signals. It wakes all the tasks attached
329 * to a list head, and remove the signal, and free the used
330 * memory.
331 */
332static void hlua_com_wake(struct list *wake)
333{
334 struct hlua_com *com, *back;
335
336 /* Wake task and delete all pending communication signals. */
337 list_for_each_entry_safe(com, back, wake, wake_me) {
338 LIST_DEL(&com->purge_me);
339 LIST_DEL(&com->wake_me);
340 task_wakeup(com->task, TASK_WOKEN_MSG);
341 pool_free2(pool2_hlua_com, com);
342 }
343}
344
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100345/* This functions is used with sample fetch and converters. It
346 * converts the HAProxy configuration argument in a lua stack
347 * values.
348 *
349 * It takes an array of "arg", and each entry of the array is
350 * converted and pushed in the LUA stack.
351 */
352static int hlua_arg2lua(lua_State *L, const struct arg *arg)
353{
354 switch (arg->type) {
355 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100356 case ARGT_TIME:
357 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100358 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100359 break;
360
361 case ARGT_STR:
362 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
363 break;
364
365 case ARGT_IPV4:
366 case ARGT_IPV6:
367 case ARGT_MSK4:
368 case ARGT_MSK6:
369 case ARGT_FE:
370 case ARGT_BE:
371 case ARGT_TAB:
372 case ARGT_SRV:
373 case ARGT_USR:
374 case ARGT_MAP:
375 default:
376 lua_pushnil(L);
377 break;
378 }
379 return 1;
380}
381
382/* This function take one entrie in an LUA stack at the index "ud",
383 * and try to convert it in an HAProxy argument entry. This is useful
384 * with sample fetch wrappers. The input arguments are gived to the
385 * lua wrapper and converted as arg list by thi function.
386 */
387static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
388{
389 switch (lua_type(L, ud)) {
390
391 case LUA_TNUMBER:
392 case LUA_TBOOLEAN:
393 arg->type = ARGT_SINT;
394 arg->data.sint = lua_tointeger(L, ud);
395 break;
396
397 case LUA_TSTRING:
398 arg->type = ARGT_STR;
399 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
400 break;
401
402 case LUA_TUSERDATA:
403 case LUA_TNIL:
404 case LUA_TTABLE:
405 case LUA_TFUNCTION:
406 case LUA_TTHREAD:
407 case LUA_TLIGHTUSERDATA:
408 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200409 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100410 break;
411 }
412 return 1;
413}
414
415/* the following functions are used to convert a struct sample
416 * in Lua type. This useful to convert the return of the
417 * fetchs or converters.
418 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100419static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100420{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200421 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100422 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100423 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200424 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100425 break;
426
427 case SMP_T_BIN:
428 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200429 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100430 break;
431
432 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200433 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100434 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
435 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
436 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
437 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
438 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
439 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
440 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
441 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
442 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200443 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100444 break;
445 default:
446 lua_pushnil(L);
447 break;
448 }
449 break;
450
451 case SMP_T_IPV4:
452 case SMP_T_IPV6:
453 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200454 if (sample_casts[smp->data.type][SMP_T_STR] &&
455 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200456 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100457 else
458 lua_pushnil(L);
459 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100460 default:
461 lua_pushnil(L);
462 break;
463 }
464 return 1;
465}
466
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100467/* the following functions are used to convert a struct sample
468 * in Lua strings. This is useful to convert the return of the
469 * fetchs or converters.
470 */
471static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
472{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200473 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100474
475 case SMP_T_BIN:
476 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200477 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100478 break;
479
480 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200481 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100482 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
483 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
484 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
485 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
486 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
487 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
488 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
489 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
490 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200491 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100492 break;
493 default:
494 lua_pushstring(L, "");
495 break;
496 }
497 break;
498
499 case SMP_T_SINT:
500 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100501 case SMP_T_IPV4:
502 case SMP_T_IPV6:
503 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200504 if (sample_casts[smp->data.type][SMP_T_STR] &&
505 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200506 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100507 else
508 lua_pushstring(L, "");
509 break;
510 default:
511 lua_pushstring(L, "");
512 break;
513 }
514 return 1;
515}
516
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100517/* the following functions are used to convert an Lua type in a
518 * struct sample. This is useful to provide data from a converter
519 * to the LUA code.
520 */
521static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
522{
523 switch (lua_type(L, ud)) {
524
525 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200526 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200527 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100528 break;
529
530
531 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200532 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200533 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100534 break;
535
536 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200537 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100538 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200539 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100540 break;
541
542 case LUA_TUSERDATA:
543 case LUA_TNIL:
544 case LUA_TTABLE:
545 case LUA_TFUNCTION:
546 case LUA_TTHREAD:
547 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200548 case LUA_TNONE:
549 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200550 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200551 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100552 break;
553 }
554 return 1;
555}
556
557/* This function check the "argp" builded by another conversion function
558 * is in accord with the expected argp defined by the "mask". The fucntion
559 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100560 *
561 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
562 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100563 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100564__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100565 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100566{
567 int min_arg;
568 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100569 struct proxy *px;
570 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100571
572 idx = 0;
573 min_arg = ARGM(mask);
574 mask >>= ARGM_BITS;
575
576 while (1) {
577
578 /* Check oversize. */
579 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100580 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100581 }
582
583 /* Check for mandatory arguments. */
584 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100585 if (idx < min_arg) {
586
587 /* If miss other argument than the first one, we return an error. */
588 if (idx > 0)
589 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
590
591 /* If first argument have a certain type, some default values
592 * may be used. See the function smp_resolve_args().
593 */
594 switch (mask & ARGT_MASK) {
595
596 case ARGT_FE:
597 if (!(p->cap & PR_CAP_FE))
598 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
599 argp[idx].data.prx = p;
600 argp[idx].type = ARGT_FE;
601 argp[idx+1].type = ARGT_STOP;
602 break;
603
604 case ARGT_BE:
605 if (!(p->cap & PR_CAP_BE))
606 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
607 argp[idx].data.prx = p;
608 argp[idx].type = ARGT_BE;
609 argp[idx+1].type = ARGT_STOP;
610 break;
611
612 case ARGT_TAB:
613 argp[idx].data.prx = p;
614 argp[idx].type = ARGT_TAB;
615 argp[idx+1].type = ARGT_STOP;
616 break;
617
618 default:
619 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
620 break;
621 }
622 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100623 return 0;
624 }
625
626 /* Check for exceed the number of requiered argument. */
627 if ((mask & ARGT_MASK) == ARGT_STOP &&
628 argp[idx].type != ARGT_STOP) {
629 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
630 }
631
632 if ((mask & ARGT_MASK) == ARGT_STOP &&
633 argp[idx].type == ARGT_STOP) {
634 return 0;
635 }
636
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100637 /* Convert some argument types. */
638 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100639 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100640 if (argp[idx].type != ARGT_SINT)
641 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
642 argp[idx].type = ARGT_SINT;
643 break;
644
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100645 case ARGT_TIME:
646 if (argp[idx].type != ARGT_SINT)
647 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200648 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100649 break;
650
651 case ARGT_SIZE:
652 if (argp[idx].type != ARGT_SINT)
653 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200654 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100655 break;
656
657 case ARGT_FE:
658 if (argp[idx].type != ARGT_STR)
659 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
660 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
661 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200662 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100663 if (!argp[idx].data.prx)
664 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
665 argp[idx].type = ARGT_FE;
666 break;
667
668 case ARGT_BE:
669 if (argp[idx].type != ARGT_STR)
670 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
671 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
672 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200673 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100674 if (!argp[idx].data.prx)
675 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
676 argp[idx].type = ARGT_BE;
677 break;
678
679 case ARGT_TAB:
680 if (argp[idx].type != ARGT_STR)
681 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
682 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
683 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200684 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100685 if (!argp[idx].data.prx)
686 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
687 argp[idx].type = ARGT_TAB;
688 break;
689
690 case ARGT_SRV:
691 if (argp[idx].type != ARGT_STR)
692 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
693 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
694 trash.str[argp[idx].data.str.len] = 0;
695 sname = strrchr(trash.str, '/');
696 if (sname) {
697 *sname++ = '\0';
698 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200699 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100700 if (!px)
701 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
702 }
703 else {
704 sname = trash.str;
705 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100706 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100707 argp[idx].data.srv = findserver(px, sname);
708 if (!argp[idx].data.srv)
709 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
710 argp[idx].type = ARGT_SRV;
711 break;
712
713 case ARGT_IPV4:
714 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
715 trash.str[argp[idx].data.str.len] = 0;
716 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
717 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
718 argp[idx].type = ARGT_IPV4;
719 break;
720
721 case ARGT_MSK4:
722 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
723 trash.str[argp[idx].data.str.len] = 0;
724 if (!str2mask(trash.str, &argp[idx].data.ipv4))
725 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
726 argp[idx].type = ARGT_MSK4;
727 break;
728
729 case ARGT_IPV6:
730 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
731 trash.str[argp[idx].data.str.len] = 0;
732 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
733 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
734 argp[idx].type = ARGT_IPV6;
735 break;
736
737 case ARGT_MSK6:
738 case ARGT_MAP:
739 case ARGT_REG:
740 case ARGT_USR:
741 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100742 break;
743 }
744
745 /* Check for type of argument. */
746 if ((mask & ARGT_MASK) != argp[idx].type) {
747 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
748 arg_type_names[(mask & ARGT_MASK)],
749 arg_type_names[argp[idx].type & ARGT_MASK]);
750 WILL_LJMP(luaL_argerror(L, first + idx, msg));
751 }
752
753 /* Next argument. */
754 mask >>= ARGT_BITS;
755 idx++;
756 }
757}
758
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100759/*
760 * The following functions are used to make correspondance between the the
761 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100762 *
763 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100764 * - hlua_sethlua : create the association between hlua context and lua_state.
765 */
766static inline struct hlua *hlua_gethlua(lua_State *L)
767{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100768 struct hlua **hlua = lua_getextraspace(L);
769 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100770}
771static inline void hlua_sethlua(struct hlua *hlua)
772{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100773 struct hlua **hlua_store = lua_getextraspace(hlua->T);
774 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100775}
776
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100777/* This function is used to send logs. It try to send on screen (stderr)
778 * and on the default syslog server.
779 */
780static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
781{
782 struct tm tm;
783 char *p;
784
785 /* Cleanup the log message. */
786 p = trash.str;
787 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200788 if (p >= trash.str + trash.size - 1) {
789 /* Break the message if exceed the buffer size. */
790 *(p-4) = ' ';
791 *(p-3) = '.';
792 *(p-2) = '.';
793 *(p-1) = '.';
794 break;
795 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100796 if (isprint(*msg))
797 *p = *msg;
798 else
799 *p = '.';
800 }
801 *p = '\0';
802
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200803 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100804 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200805 get_localtime(date.tv_sec, &tm);
806 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100807 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
808 (int)getpid(), trash.str);
809 fflush(stderr);
810 }
811}
812
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100813/* This function just ensure that the yield will be always
814 * returned with a timeout and permit to set some flags
815 */
816__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100817 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100818{
819 struct hlua *hlua = hlua_gethlua(L);
820
821 /* Set the wake timeout. If timeout is required, we set
822 * the expiration time.
823 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200824 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100825
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100826 hlua->flags |= flags;
827
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100828 /* Process the yield. */
829 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
830}
831
Willy Tarreau87b09662015-04-03 00:22:06 +0200832/* This function initialises the Lua environment stored in the stream.
833 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100834 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200835 *
836 * This function is particular. it initialises a new Lua thread. If the
837 * initialisation fails (example: out of memory error), the lua function
838 * throws an error (longjmp).
839 *
840 * This function manipulates two Lua stack: the main and the thread. Only
841 * the main stack can fail. The thread is not manipulated. This function
842 * MUST NOT manipulate the created thread stack state, because is not
843 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100844 */
845int hlua_ctx_init(struct hlua *lua, struct task *task)
846{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200847 if (!SET_SAFE_LJMP(gL.T)) {
848 lua->Tref = LUA_REFNIL;
849 return 0;
850 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100851 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100852 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100853 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100854 lua->T = lua_newthread(gL.T);
855 if (!lua->T) {
856 lua->Tref = LUA_REFNIL;
857 return 0;
858 }
859 hlua_sethlua(lua);
860 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
861 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200862 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100863 return 1;
864}
865
Willy Tarreau87b09662015-04-03 00:22:06 +0200866/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100867 * is destroyed. The destroy also the memory context. The struct "lua"
868 * is not freed.
869 */
870void hlua_ctx_destroy(struct hlua *lua)
871{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100872 if (!lua->T)
873 return;
874
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100875 /* Purge all the pending signals. */
876 hlua_com_purge(lua);
877
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100878 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
879 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200880
881 /* Forces a garbage collecting process. If the Lua program is finished
882 * without error, we run the GC on the thread pointer. Its freed all
883 * the unused memory.
884 * If the thread is finnish with an error or is currently yielded,
885 * it seems that the GC applied on the thread doesn't clean anything,
886 * so e run the GC on the main thread.
887 * NOTE: maybe this action locks all the Lua threads untiml the en of
888 * the garbage collection.
889 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200890 if (lua->flags & HLUA_MUST_GC) {
891 lua_gc(lua->T, LUA_GCCOLLECT, 0);
892 if (lua_status(lua->T) != LUA_OK)
893 lua_gc(gL.T, LUA_GCCOLLECT, 0);
894 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200895
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200896 lua->T = NULL;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100897}
898
899/* This function is used to restore the Lua context when a coroutine
900 * fails. This function copy the common memory between old coroutine
901 * and the new coroutine. The old coroutine is destroyed, and its
902 * replaced by the new coroutine.
903 * If the flag "keep_msg" is set, the last entry of the old is assumed
904 * as string error message and it is copied in the new stack.
905 */
906static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
907{
908 lua_State *T;
909 int new_ref;
910
911 /* Renew the main LUA stack doesn't have sense. */
912 if (lua == &gL)
913 return 0;
914
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100915 /* New Lua coroutine. */
916 T = lua_newthread(gL.T);
917 if (!T)
918 return 0;
919
920 /* Copy last error message. */
921 if (keep_msg)
922 lua_xmove(lua->T, T, 1);
923
924 /* Copy data between the coroutines. */
925 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
926 lua_xmove(lua->T, T, 1);
927 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
928
929 /* Destroy old data. */
930 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
931
932 /* The thread is garbage collected by Lua. */
933 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
934
935 /* Fill the struct with the new coroutine values. */
936 lua->Mref = new_ref;
937 lua->T = T;
938 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
939
940 /* Set context. */
941 hlua_sethlua(lua);
942
943 return 1;
944}
945
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100946void hlua_hook(lua_State *L, lua_Debug *ar)
947{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100948 struct hlua *hlua = hlua_gethlua(L);
949
950 /* Lua cannot yield when its returning from a function,
951 * so, we can fix the interrupt hook to 1 instruction,
952 * expecting that the function is finnished.
953 */
954 if (lua_gethookmask(L) & LUA_MASKRET) {
955 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
956 return;
957 }
958
959 /* restore the interrupt condition. */
960 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
961
962 /* If we interrupt the Lua processing in yieldable state, we yield.
963 * If the state is not yieldable, trying yield causes an error.
964 */
965 if (lua_isyieldable(L))
966 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
967
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100968 /* If we cannot yield, update the clock and check the timeout. */
969 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200970 hlua->run_time += now_ms - hlua->start_time;
971 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100972 lua_pushfstring(L, "execution timeout");
973 WILL_LJMP(lua_error(L));
974 }
975
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200976 /* Update the start time. */
977 hlua->start_time = now_ms;
978
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100979 /* Try to interrupt the process at the end of the current
980 * unyieldable function.
981 */
982 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100983}
984
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100985/* This function start or resumes the Lua stack execution. If the flag
986 * "yield_allowed" if no set and the LUA stack execution returns a yield
987 * The function return an error.
988 *
989 * The function can returns 4 values:
990 * - HLUA_E_OK : The execution is terminated without any errors.
991 * - HLUA_E_AGAIN : The execution must continue at the next associated
992 * task wakeup.
993 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
994 * the top of the stack.
995 * - HLUA_E_ERR : An error has occured without error message.
996 *
997 * If an error occured, the stack is renewed and it is ready to run new
998 * LUA code.
999 */
1000static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1001{
1002 int ret;
1003 const char *msg;
1004
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001005 /* Initialise run time counter. */
1006 if (!HLUA_IS_RUNNING(lua))
1007 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001008
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001009resume_execution:
1010
1011 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1012 * instructions. it is used for preventing infinite loops.
1013 */
1014 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1015
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001016 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001017 HLUA_SET_RUN(lua);
1018 HLUA_CLR_CTRLYIELD(lua);
1019 HLUA_CLR_WAKERESWR(lua);
1020 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001021
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001022 /* Update the start time. */
1023 lua->start_time = now_ms;
1024
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001025 /* Call the function. */
1026 ret = lua_resume(lua->T, gL.T, lua->nargs);
1027 switch (ret) {
1028
1029 case LUA_OK:
1030 ret = HLUA_E_OK;
1031 break;
1032
1033 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001034 /* Check if the execution timeout is expired. It it is the case, we
1035 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001036 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001037 tv_update_date(0, 1);
1038 lua->run_time += now_ms - lua->start_time;
1039 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001040 lua_settop(lua->T, 0); /* Empty the stack. */
1041 if (!lua_checkstack(lua->T, 1)) {
1042 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001043 break;
1044 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001045 lua_pushfstring(lua->T, "execution timeout");
1046 ret = HLUA_E_ERRMSG;
1047 break;
1048 }
1049 /* Process the forced yield. if the general yield is not allowed or
1050 * if no task were associated this the current Lua execution
1051 * coroutine, we resume the execution. Else we want to return in the
1052 * scheduler and we want to be waked up again, to continue the
1053 * current Lua execution. So we schedule our own task.
1054 */
1055 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001056 if (!yield_allowed || !lua->task)
1057 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001058 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001059 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001060 if (!yield_allowed) {
1061 lua_settop(lua->T, 0); /* Empty the stack. */
1062 if (!lua_checkstack(lua->T, 1)) {
1063 ret = HLUA_E_ERR;
1064 break;
1065 }
1066 lua_pushfstring(lua->T, "yield not allowed");
1067 ret = HLUA_E_ERRMSG;
1068 break;
1069 }
1070 ret = HLUA_E_AGAIN;
1071 break;
1072
1073 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001074
1075 /* Special exit case. The traditionnal exit is returned as an error
1076 * because the errors ares the only one mean to return immediately
1077 * from and lua execution.
1078 */
1079 if (lua->flags & HLUA_EXIT) {
1080 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001081 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001082 break;
1083 }
1084
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001085 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001086 if (!lua_checkstack(lua->T, 1)) {
1087 ret = HLUA_E_ERR;
1088 break;
1089 }
1090 msg = lua_tostring(lua->T, -1);
1091 lua_settop(lua->T, 0); /* Empty the stack. */
1092 lua_pop(lua->T, 1);
1093 if (msg)
1094 lua_pushfstring(lua->T, "runtime error: %s", msg);
1095 else
1096 lua_pushfstring(lua->T, "unknown runtime error");
1097 ret = HLUA_E_ERRMSG;
1098 break;
1099
1100 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001101 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001102 lua_settop(lua->T, 0); /* Empty the stack. */
1103 if (!lua_checkstack(lua->T, 1)) {
1104 ret = HLUA_E_ERR;
1105 break;
1106 }
1107 lua_pushfstring(lua->T, "out of memory error");
1108 ret = HLUA_E_ERRMSG;
1109 break;
1110
1111 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001112 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001113 if (!lua_checkstack(lua->T, 1)) {
1114 ret = HLUA_E_ERR;
1115 break;
1116 }
1117 msg = lua_tostring(lua->T, -1);
1118 lua_settop(lua->T, 0); /* Empty the stack. */
1119 lua_pop(lua->T, 1);
1120 if (msg)
1121 lua_pushfstring(lua->T, "message handler error: %s", msg);
1122 else
1123 lua_pushfstring(lua->T, "message handler error");
1124 ret = HLUA_E_ERRMSG;
1125 break;
1126
1127 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001128 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001129 lua_settop(lua->T, 0); /* Empty the stack. */
1130 if (!lua_checkstack(lua->T, 1)) {
1131 ret = HLUA_E_ERR;
1132 break;
1133 }
1134 lua_pushfstring(lua->T, "unknonwn error");
1135 ret = HLUA_E_ERRMSG;
1136 break;
1137 }
1138
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001139 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001140 if (lua->flags & HLUA_MUST_GC &&
1141 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001142 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1143
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001144 switch (ret) {
1145 case HLUA_E_AGAIN:
1146 break;
1147
1148 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001149 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001150 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001151 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001152 break;
1153
1154 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001155 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001156 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001157 hlua_ctx_renew(lua, 0);
1158 break;
1159
1160 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001161 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001162 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001163 break;
1164 }
1165
1166 return ret;
1167}
1168
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001169/* This function exit the current code. */
1170__LJMP static int hlua_done(lua_State *L)
1171{
1172 struct hlua *hlua = hlua_gethlua(L);
1173
1174 hlua->flags |= HLUA_EXIT;
1175 WILL_LJMP(lua_error(L));
1176
1177 return 0;
1178}
1179
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001180/* This function is an LUA binding. It provides a function
1181 * for deleting ACL from a referenced ACL file.
1182 */
1183__LJMP static int hlua_del_acl(lua_State *L)
1184{
1185 const char *name;
1186 const char *key;
1187 struct pat_ref *ref;
1188
1189 MAY_LJMP(check_args(L, 2, "del_acl"));
1190
1191 name = MAY_LJMP(luaL_checkstring(L, 1));
1192 key = MAY_LJMP(luaL_checkstring(L, 2));
1193
1194 ref = pat_ref_lookup(name);
1195 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001196 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001197
1198 pat_ref_delete(ref, key);
1199 return 0;
1200}
1201
1202/* This function is an LUA binding. It provides a function
1203 * for deleting map entry from a referenced map file.
1204 */
1205static int hlua_del_map(lua_State *L)
1206{
1207 const char *name;
1208 const char *key;
1209 struct pat_ref *ref;
1210
1211 MAY_LJMP(check_args(L, 2, "del_map"));
1212
1213 name = MAY_LJMP(luaL_checkstring(L, 1));
1214 key = MAY_LJMP(luaL_checkstring(L, 2));
1215
1216 ref = pat_ref_lookup(name);
1217 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001218 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001219
1220 pat_ref_delete(ref, key);
1221 return 0;
1222}
1223
1224/* This function is an LUA binding. It provides a function
1225 * for adding ACL pattern from a referenced ACL file.
1226 */
1227static int hlua_add_acl(lua_State *L)
1228{
1229 const char *name;
1230 const char *key;
1231 struct pat_ref *ref;
1232
1233 MAY_LJMP(check_args(L, 2, "add_acl"));
1234
1235 name = MAY_LJMP(luaL_checkstring(L, 1));
1236 key = MAY_LJMP(luaL_checkstring(L, 2));
1237
1238 ref = pat_ref_lookup(name);
1239 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001240 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001241
1242 if (pat_ref_find_elt(ref, key) == NULL)
1243 pat_ref_add(ref, key, NULL, NULL);
1244 return 0;
1245}
1246
1247/* This function is an LUA binding. It provides a function
1248 * for setting map pattern and sample from a referenced map
1249 * file.
1250 */
1251static int hlua_set_map(lua_State *L)
1252{
1253 const char *name;
1254 const char *key;
1255 const char *value;
1256 struct pat_ref *ref;
1257
1258 MAY_LJMP(check_args(L, 3, "set_map"));
1259
1260 name = MAY_LJMP(luaL_checkstring(L, 1));
1261 key = MAY_LJMP(luaL_checkstring(L, 2));
1262 value = MAY_LJMP(luaL_checkstring(L, 3));
1263
1264 ref = pat_ref_lookup(name);
1265 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001266 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001267
1268 if (pat_ref_find_elt(ref, key) != NULL)
1269 pat_ref_set(ref, key, value, NULL);
1270 else
1271 pat_ref_add(ref, key, value, NULL);
1272 return 0;
1273}
1274
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001275/* A class is a lot of memory that contain data. This data can be a table,
1276 * an integer or user data. This data is associated with a metatable. This
1277 * metatable have an original version registred in the global context with
1278 * the name of the object (_G[<name>] = <metable> ).
1279 *
1280 * A metable is a table that modify the standard behavior of a standard
1281 * access to the associated data. The entries of this new metatable are
1282 * defined as is:
1283 *
1284 * http://lua-users.org/wiki/MetatableEvents
1285 *
1286 * __index
1287 *
1288 * we access an absent field in a table, the result is nil. This is
1289 * true, but it is not the whole truth. Actually, such access triggers
1290 * the interpreter to look for an __index metamethod: If there is no
1291 * such method, as usually happens, then the access results in nil;
1292 * otherwise, the metamethod will provide the result.
1293 *
1294 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1295 * the key does not appear in the table, but the metatable has an __index
1296 * property:
1297 *
1298 * - if the value is a function, the function is called, passing in the
1299 * table and the key; the return value of that function is returned as
1300 * the result.
1301 *
1302 * - if the value is another table, the value of the key in that table is
1303 * asked for and returned (and if it doesn't exist in that table, but that
1304 * table's metatable has an __index property, then it continues on up)
1305 *
1306 * - Use "rawget(myTable,key)" to skip this metamethod.
1307 *
1308 * http://www.lua.org/pil/13.4.1.html
1309 *
1310 * __newindex
1311 *
1312 * Like __index, but control property assignment.
1313 *
1314 * __mode - Control weak references. A string value with one or both
1315 * of the characters 'k' and 'v' which specifies that the the
1316 * keys and/or values in the table are weak references.
1317 *
1318 * __call - Treat a table like a function. When a table is followed by
1319 * parenthesis such as "myTable( 'foo' )" and the metatable has
1320 * a __call key pointing to a function, that function is invoked
1321 * (passing any specified arguments) and the return value is
1322 * returned.
1323 *
1324 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1325 * called, if the metatable for myTable has a __metatable
1326 * key, the value of that key is returned instead of the
1327 * actual metatable.
1328 *
1329 * __tostring - Control string representation. When the builtin
1330 * "tostring( myTable )" function is called, if the metatable
1331 * for myTable has a __tostring property set to a function,
1332 * that function is invoked (passing myTable to it) and the
1333 * return value is used as the string representation.
1334 *
1335 * __len - Control table length. When the table length is requested using
1336 * the length operator ( '#' ), if the metatable for myTable has
1337 * a __len key pointing to a function, that function is invoked
1338 * (passing myTable to it) and the return value used as the value
1339 * of "#myTable".
1340 *
1341 * __gc - Userdata finalizer code. When userdata is set to be garbage
1342 * collected, if the metatable has a __gc field pointing to a
1343 * function, that function is first invoked, passing the userdata
1344 * to it. The __gc metamethod is not called for tables.
1345 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1346 *
1347 * Special metamethods for redefining standard operators:
1348 * http://www.lua.org/pil/13.1.html
1349 *
1350 * __add "+"
1351 * __sub "-"
1352 * __mul "*"
1353 * __div "/"
1354 * __unm "!"
1355 * __pow "^"
1356 * __concat ".."
1357 *
1358 * Special methods for redfining standar relations
1359 * http://www.lua.org/pil/13.2.html
1360 *
1361 * __eq "=="
1362 * __lt "<"
1363 * __le "<="
1364 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001365
1366/*
1367 *
1368 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001369 * Class Map
1370 *
1371 *
1372 */
1373
1374/* Returns a struct hlua_map if the stack entry "ud" is
1375 * a class session, otherwise it throws an error.
1376 */
1377__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1378{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001379 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001380}
1381
1382/* This function is the map constructor. It don't need
1383 * the class Map object. It creates and return a new Map
1384 * object. It must be called only during "body" or "init"
1385 * context because it process some filesystem accesses.
1386 */
1387__LJMP static int hlua_map_new(struct lua_State *L)
1388{
1389 const char *fn;
1390 int match = PAT_MATCH_STR;
1391 struct sample_conv conv;
1392 const char *file = "";
1393 int line = 0;
1394 lua_Debug ar;
1395 char *err = NULL;
1396 struct arg args[2];
1397
1398 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1399 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1400
1401 fn = MAY_LJMP(luaL_checkstring(L, 1));
1402
1403 if (lua_gettop(L) >= 2) {
1404 match = MAY_LJMP(luaL_checkinteger(L, 2));
1405 if (match < 0 || match >= PAT_MATCH_NUM)
1406 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1407 }
1408
1409 /* Get Lua filename and line number. */
1410 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1411 lua_getinfo(L, "Sl", &ar); /* get info about it */
1412 if (ar.currentline > 0) { /* is there info? */
1413 file = ar.short_src;
1414 line = ar.currentline;
1415 }
1416 }
1417
1418 /* fill fake sample_conv struct. */
1419 conv.kw = ""; /* unused. */
1420 conv.process = NULL; /* unused. */
1421 conv.arg_mask = 0; /* unused. */
1422 conv.val_args = NULL; /* unused. */
1423 conv.out_type = SMP_T_STR;
1424 conv.private = (void *)(long)match;
1425 switch (match) {
1426 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1427 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1428 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1429 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1430 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1431 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1432 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001433 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001434 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1435 default:
1436 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1437 }
1438
1439 /* fill fake args. */
1440 args[0].type = ARGT_STR;
1441 args[0].data.str.str = (char *)fn;
1442 args[1].type = ARGT_STOP;
1443
1444 /* load the map. */
1445 if (!sample_load_map(args, &conv, file, line, &err)) {
1446 /* error case: we cant use luaL_error because we must
1447 * free the err variable.
1448 */
1449 luaL_where(L, 1);
1450 lua_pushfstring(L, "'new': %s.", err);
1451 lua_concat(L, 2);
1452 free(err);
1453 WILL_LJMP(lua_error(L));
1454 }
1455
1456 /* create the lua object. */
1457 lua_newtable(L);
1458 lua_pushlightuserdata(L, args[0].data.map);
1459 lua_rawseti(L, -2, 0);
1460
1461 /* Pop a class Map metatable and affect it to the userdata. */
1462 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1463 lua_setmetatable(L, -2);
1464
1465
1466 return 1;
1467}
1468
1469__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1470{
1471 struct map_descriptor *desc;
1472 struct pattern *pat;
1473 struct sample smp;
1474
1475 MAY_LJMP(check_args(L, 2, "lookup"));
1476 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001477 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001478 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001479 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001480 }
1481 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001482 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001483 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001484 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 +02001485 }
1486
1487 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001488 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001489 if (str)
1490 lua_pushstring(L, "");
1491 else
1492 lua_pushnil(L);
1493 return 1;
1494 }
1495
1496 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001497 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001498 return 1;
1499}
1500
1501__LJMP static int hlua_map_lookup(struct lua_State *L)
1502{
1503 return _hlua_map_lookup(L, 0);
1504}
1505
1506__LJMP static int hlua_map_slookup(struct lua_State *L)
1507{
1508 return _hlua_map_lookup(L, 1);
1509}
1510
1511/*
1512 *
1513 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001514 * Class Socket
1515 *
1516 *
1517 */
1518
1519__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1520{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001521 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001522}
1523
1524/* This function is the handler called for each I/O on the established
1525 * connection. It is used for notify space avalaible to send or data
1526 * received.
1527 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001528static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001529{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001530 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001531 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001532
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001533 /* If the connection object is not avalaible, close all the
1534 * streams and wakeup everithing waiting for.
1535 */
1536 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001537 si_shutw(si);
1538 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001539 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001540 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1541 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001542 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001543 }
1544
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001545 /* If we cant write, wakeup the pending write signals. */
1546 if (channel_output_closed(si_ic(si)))
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001547 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001548
1549 /* If we cant read, wakeup the pending read signals. */
1550 if (channel_input_closed(si_oc(si)))
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001551 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001552
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001553 /* if the connection is not estabkished, inform the stream that we want
1554 * to be notified whenever the connection completes.
1555 */
1556 if (!(c->flags & CO_FL_CONNECTED)) {
1557 si_applet_cant_get(si);
1558 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001559 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001560 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001561
1562 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001563 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001564
1565 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001566 if (channel_may_recv(si_ic(si)))
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001567 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001568
1569 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001570 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001571 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001572}
1573
Willy Tarreau87b09662015-04-03 00:22:06 +02001574/* This function is called when the "struct stream" is destroyed.
1575 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001576 * Wake all the pending signals.
1577 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001578static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001579{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001580 /* Remove my link in the original object. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001581 if (appctx->ctx.hlua_cosocket.socket)
1582 appctx->ctx.hlua_cosocket.socket->s = NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001583
1584 /* Wake all the task waiting for me. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001585 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1586 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001587}
1588
1589/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001590 * uses this object. If the stream does not exists, just quit.
1591 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001592 * pending signal can rest in the read and write lists. destroy
1593 * it.
1594 */
1595__LJMP static int hlua_socket_gc(lua_State *L)
1596{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001597 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001598 struct appctx *appctx;
1599
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001600 MAY_LJMP(check_args(L, 1, "__gc"));
1601
1602 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001603 if (!socket->s)
1604 return 0;
1605
Willy Tarreau87b09662015-04-03 00:22:06 +02001606 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001607 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001608 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001609 socket->s = NULL;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001610 appctx->ctx.hlua_cosocket.socket = NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001611
1612 return 0;
1613}
1614
1615/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001616 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001617 */
1618__LJMP static int hlua_socket_close(lua_State *L)
1619{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001620 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001621 struct appctx *appctx;
1622
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001623 MAY_LJMP(check_args(L, 1, "close"));
1624
1625 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001626 if (!socket->s)
1627 return 0;
1628
Willy Tarreau87b09662015-04-03 00:22:06 +02001629 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001630 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001631 appctx = objt_appctx(socket->s->si[0].end);
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001632 appctx->ctx.hlua_cosocket.socket = NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001633 socket->s = NULL;
1634
1635 return 0;
1636}
1637
1638/* This Lua function assumes that the stack contain three parameters.
1639 * 1 - USERDATA containing a struct socket
1640 * 2 - INTEGER with values of the macro defined below
1641 * If the integer is -1, we must read at most one line.
1642 * If the integer is -2, we ust read all the data until the
1643 * end of the stream.
1644 * If the integer is positive value, we must read a number of
1645 * bytes corresponding to this value.
1646 */
1647#define HLSR_READ_LINE (-1)
1648#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001649__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001650{
1651 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1652 int wanted = lua_tointeger(L, 2);
1653 struct hlua *hlua = hlua_gethlua(L);
1654 struct appctx *appctx;
1655 int len;
1656 int nblk;
1657 char *blk1;
1658 int len1;
1659 char *blk2;
1660 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001661 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001662 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001663
1664 /* Check if this lua stack is schedulable. */
1665 if (!hlua || !hlua->task)
1666 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1667 "'frontend', 'backend' or 'task'"));
1668
1669 /* check for connection closed. If some data where read, return it. */
1670 if (!socket->s)
1671 goto connection_closed;
1672
Willy Tarreau94aa6172015-03-13 14:19:06 +01001673 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001674 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001675 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001676 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001677 if (nblk < 0) /* Connection close. */
1678 goto connection_closed;
1679 if (nblk == 0) /* No data avalaible. */
1680 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001681
1682 /* remove final \r\n. */
1683 if (nblk == 1) {
1684 if (blk1[len1-1] == '\n') {
1685 len1--;
1686 skip_at_end++;
1687 if (blk1[len1-1] == '\r') {
1688 len1--;
1689 skip_at_end++;
1690 }
1691 }
1692 }
1693 else {
1694 if (blk2[len2-1] == '\n') {
1695 len2--;
1696 skip_at_end++;
1697 if (blk2[len2-1] == '\r') {
1698 len2--;
1699 skip_at_end++;
1700 }
1701 }
1702 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001703 }
1704
1705 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001706 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001707 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001708 if (nblk < 0) /* Connection close. */
1709 goto connection_closed;
1710 if (nblk == 0) /* No data avalaible. */
1711 goto connection_empty;
1712 }
1713
1714 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001715 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001716 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001717 if (nblk < 0) /* Connection close. */
1718 goto connection_closed;
1719 if (nblk == 0) /* No data avalaible. */
1720 goto connection_empty;
1721
1722 if (len1 > wanted) {
1723 nblk = 1;
1724 len1 = wanted;
1725 } if (nblk == 2 && len1 + len2 > wanted)
1726 len2 = wanted - len1;
1727 }
1728
1729 len = len1;
1730
1731 luaL_addlstring(&socket->b, blk1, len1);
1732 if (nblk == 2) {
1733 len += len2;
1734 luaL_addlstring(&socket->b, blk2, len2);
1735 }
1736
1737 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001738 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001739
1740 /* Don't wait anything. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001741 stream_int_notify(&socket->s->si[0]);
1742 stream_int_update_applet(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001743
1744 /* If the pattern reclaim to read all the data
1745 * in the connection, got out.
1746 */
1747 if (wanted == HLSR_READ_ALL)
1748 goto connection_empty;
1749 else if (wanted >= 0 && len < wanted)
1750 goto connection_empty;
1751
1752 /* Return result. */
1753 luaL_pushresult(&socket->b);
1754 return 1;
1755
1756connection_closed:
1757
1758 /* If the buffer containds data. */
1759 if (socket->b.n > 0) {
1760 luaL_pushresult(&socket->b);
1761 return 1;
1762 }
1763 lua_pushnil(L);
1764 lua_pushstring(L, "connection closed.");
1765 return 2;
1766
1767connection_empty:
1768
1769 appctx = objt_appctx(socket->s->si[0].end);
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001770 if (!hlua_com_new(hlua, &appctx->ctx.hlua_cosocket.wake_on_read))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001771 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001772 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001773 return 0;
1774}
1775
1776/* This Lus function gets two parameters. The first one can be string
1777 * or a number. If the string is "*l", the user require one line. If
1778 * the string is "*a", the user require all the content of the stream.
1779 * If the value is a number, the user require a number of bytes equal
1780 * to the value. The default value is "*l" (a line).
1781 *
1782 * This paraeter with a variable type is converted in integer. This
1783 * integer takes this values:
1784 * -1 : read a line
1785 * -2 : read all the stream
1786 * >0 : amount if bytes.
1787 *
1788 * The second parameter is optinal. It contains a string that must be
1789 * concatenated with the read data.
1790 */
1791__LJMP static int hlua_socket_receive(struct lua_State *L)
1792{
1793 int wanted = HLSR_READ_LINE;
1794 const char *pattern;
1795 int type;
1796 char *error;
1797 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001798 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001799
1800 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1801 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1802
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001803 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001804
1805 /* check for pattern. */
1806 if (lua_gettop(L) >= 2) {
1807 type = lua_type(L, 2);
1808 if (type == LUA_TSTRING) {
1809 pattern = lua_tostring(L, 2);
1810 if (strcmp(pattern, "*a") == 0)
1811 wanted = HLSR_READ_ALL;
1812 else if (strcmp(pattern, "*l") == 0)
1813 wanted = HLSR_READ_LINE;
1814 else {
1815 wanted = strtoll(pattern, &error, 10);
1816 if (*error != '\0')
1817 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1818 }
1819 }
1820 else if (type == LUA_TNUMBER) {
1821 wanted = lua_tointeger(L, 2);
1822 if (wanted < 0)
1823 WILL_LJMP(luaL_error(L, "Unsupported size."));
1824 }
1825 }
1826
1827 /* Set pattern. */
1828 lua_pushinteger(L, wanted);
1829 lua_replace(L, 2);
1830
1831 /* init bufffer, and fiil it wih prefix. */
1832 luaL_buffinit(L, &socket->b);
1833
1834 /* Check prefix. */
1835 if (lua_gettop(L) >= 3) {
1836 if (lua_type(L, 3) != LUA_TSTRING)
1837 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1838 pattern = lua_tolstring(L, 3, &len);
1839 luaL_addlstring(&socket->b, pattern, len);
1840 }
1841
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001842 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001843}
1844
1845/* Write the Lua input string in the output buffer.
1846 * This fucntion returns a yield if no space are available.
1847 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001848static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001849{
1850 struct hlua_socket *socket;
1851 struct hlua *hlua = hlua_gethlua(L);
1852 struct appctx *appctx;
1853 size_t buf_len;
1854 const char *buf;
1855 int len;
1856 int send_len;
1857 int sent;
1858
1859 /* Check if this lua stack is schedulable. */
1860 if (!hlua || !hlua->task)
1861 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1862 "'frontend', 'backend' or 'task'"));
1863
1864 /* Get object */
1865 socket = MAY_LJMP(hlua_checksocket(L, 1));
1866 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001867 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001868
1869 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001870 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001871 lua_pushinteger(L, -1);
1872 return 1;
1873 }
1874
1875 /* Update the input buffer data. */
1876 buf += sent;
1877 send_len = buf_len - sent;
1878
1879 /* All the data are sent. */
1880 if (sent >= buf_len)
1881 return 1; /* Implicitly return the length sent. */
1882
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001883 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1884 * the request buffer if its not required.
1885 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001886 if (socket->s->req.buf->size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01001887 si_applet_cant_put(&socket->s->si[0]);
1888 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001889 }
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);
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001933 if (!hlua_com_new(hlua, &appctx->ctx.hlua_cosocket.wake_on_write))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001934 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
Willy Tarreaua71f6422016-11-16 17:00:14 +01002086 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002087 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Willy Tarreaua71f6422016-11-16 17:00:14 +01002088 lua_pushnil(L);
2089 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002090 }
2091
2092 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2093}
2094
2095/* Returns information about my connection side. */
2096static int hlua_socket_getsockname(struct lua_State *L)
2097{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002098 struct hlua_socket *socket;
2099 struct connection *conn;
2100
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002101 MAY_LJMP(check_args(L, 1, "getsockname"));
2102
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002103 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002104
2105 /* Check if the tcp object is avalaible. */
2106 if (!socket->s) {
2107 lua_pushnil(L);
2108 return 1;
2109 }
2110
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002111 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002112 if (!conn) {
2113 lua_pushnil(L);
2114 return 1;
2115 }
2116
Willy Tarreaua71f6422016-11-16 17:00:14 +01002117 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002118 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Willy Tarreaua71f6422016-11-16 17:00:14 +01002119 lua_pushnil(L);
2120 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002121 }
2122
2123 return hlua_socket_info(L, &conn->addr.from);
2124}
2125
2126/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002127static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002128 .obj_type = OBJ_TYPE_APPLET,
2129 .name = "<LUA_TCP>",
2130 .fct = hlua_socket_handler,
2131 .release = hlua_socket_release,
2132};
2133
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002134__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002135{
2136 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2137 struct hlua *hlua = hlua_gethlua(L);
2138 struct appctx *appctx;
2139
2140 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002141 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002142 lua_pushnil(L);
2143 lua_pushstring(L, "Can't connect");
2144 return 2;
2145 }
2146
2147 appctx = objt_appctx(socket->s->si[0].end);
2148
2149 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002150 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002151 lua_pushinteger(L, 1);
2152 return 1;
2153 }
2154
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002155 if (!hlua_com_new(hlua, &appctx->ctx.hlua_cosocket.wake_on_write))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002156 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002157 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002158 return 0;
2159}
2160
2161/* This function fail or initite the connection. */
2162__LJMP static int hlua_socket_connect(struct lua_State *L)
2163{
2164 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002165 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002166 const char *ip;
2167 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002168 struct hlua *hlua;
2169 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002170 int low, high;
2171 struct sockaddr_storage *addr;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002172
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002173 if (lua_gettop(L) < 2)
2174 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002175
2176 /* Get args. */
2177 socket = MAY_LJMP(hlua_checksocket(L, 1));
2178 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002179 if (lua_gettop(L) >= 3)
2180 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002181
Willy Tarreau973a5422015-08-05 21:47:23 +02002182 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002183 if (!conn)
2184 WILL_LJMP(luaL_error(L, "connect: internal error"));
2185
Willy Tarreau3adac082015-09-26 17:51:09 +02002186 /* needed for the connection not to be closed */
2187 conn->target = socket->s->target;
2188
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002189 /* Parse ip address. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002190 addr = str2sa_range(ip, &low, &high, NULL, NULL, NULL, 0);
2191 if (!addr)
2192 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
2193 if (low != high)
2194 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
2195 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002196
2197 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002198 if (low == 0) {
2199 if (conn->addr.to.ss_family == AF_INET) {
2200 if (port == -1)
2201 WILL_LJMP(luaL_error(L, "connect: port missing"));
2202 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2203 } else if (conn->addr.to.ss_family == AF_INET6) {
2204 if (port == -1)
2205 WILL_LJMP(luaL_error(L, "connect: port missing"));
2206 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2207 }
2208 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002209
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002210 hlua = hlua_gethlua(L);
2211 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002212
2213 /* inform the stream that we want to be notified whenever the
2214 * connection completes.
2215 */
2216 si_applet_cant_get(&socket->s->si[0]);
2217 si_applet_cant_put(&socket->s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002218 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002219
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002220 hlua->flags |= HLUA_MUST_GC;
2221
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002222 if (!hlua_com_new(hlua, &appctx->ctx.hlua_cosocket.wake_on_write))
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002223 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002224 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002225
2226 return 0;
2227}
2228
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002229#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002230__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2231{
2232 struct hlua_socket *socket;
2233
2234 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2235 socket = MAY_LJMP(hlua_checksocket(L, 1));
2236 socket->s->target = &socket_ssl.obj_type;
2237 return MAY_LJMP(hlua_socket_connect(L));
2238}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002239#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002240
2241__LJMP static int hlua_socket_setoption(struct lua_State *L)
2242{
2243 return 0;
2244}
2245
2246__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2247{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002248 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002249 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002250
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002251 MAY_LJMP(check_args(L, 2, "settimeout"));
2252
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002253 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002254 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002255
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002256 socket->s->req.rto = tmout;
2257 socket->s->req.wto = tmout;
2258 socket->s->res.rto = tmout;
2259 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002260
2261 return 0;
2262}
2263
2264__LJMP static int hlua_socket_new(lua_State *L)
2265{
2266 struct hlua_socket *socket;
2267 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002268 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002269 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002270 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002271
2272 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002273 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002274 hlua_pusherror(L, "socket: full stack");
2275 goto out_fail_conf;
2276 }
2277
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002278 /* Create the object: obj[0] = userdata. */
2279 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002280 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002281 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002282 memset(socket, 0, sizeof(*socket));
2283
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002284 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002285 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002286 hlua_pusherror(L, "socket: uninitialized pools.");
2287 goto out_fail_conf;
2288 }
2289
Willy Tarreau87b09662015-04-03 00:22:06 +02002290 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002291 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2292 lua_setmetatable(L, -2);
2293
Willy Tarreaud420a972015-04-06 00:39:18 +02002294 /* Create the applet context */
2295 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002296 if (!appctx) {
2297 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002298 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002299 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002300
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002301 appctx->ctx.hlua_cosocket.socket = socket;
2302 appctx->ctx.hlua_cosocket.connected = 0;
2303 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2304 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002305
Willy Tarreaud420a972015-04-06 00:39:18 +02002306 /* Now create a session, task and stream for this applet */
2307 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2308 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002309 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002310 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311 }
2312
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002313 task = task_new();
2314 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002315 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002316 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002317 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002318 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002319
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002320 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002321 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002322 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002323 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002324 }
2325
Willy Tarreaud420a972015-04-06 00:39:18 +02002326 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002327 socket->s = strm;
2328 strm->hlua.T = NULL;
2329 strm->hlua.Tref = LUA_REFNIL;
2330 strm->hlua.Mref = LUA_REFNIL;
2331 strm->hlua.nargs = 0;
2332 strm->hlua.flags = 0;
2333 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002334
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002335 /* Configure "right" stream interface. this "si" is used to connect
2336 * and retrieve data from the server. The connection is initialized
2337 * with the "struct server".
2338 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002339 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002340
2341 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002342 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2343 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002344
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002345 /* Update statistics counters. */
2346 socket_proxy.feconn++; /* beconn will be increased later */
2347 jobs++;
2348 totalconn++;
2349
2350 /* Return yield waiting for connection. */
2351 return 1;
2352
Willy Tarreaud420a972015-04-06 00:39:18 +02002353 out_fail_stream:
2354 task_free(task);
2355 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002356 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002357 out_fail_sess:
2358 appctx_free(appctx);
2359 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002360 WILL_LJMP(lua_error(L));
2361 return 0;
2362}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002363
2364/*
2365 *
2366 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002367 * Class Channel
2368 *
2369 *
2370 */
2371
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002372/* The state between the channel data and the HTTP parser state can be
2373 * unconsistent, so reset the parser and call it again. Warning, this
2374 * action not revalidate the request and not send a 400 if the modified
2375 * resuest is not valid.
2376 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002377 * This function never fails. The direction is set using dir, which equals
2378 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002379 */
2380static void hlua_resynchonize_proto(struct stream *stream, int dir)
2381{
2382 /* Protocol HTTP. */
2383 if (stream->be->mode == PR_MODE_HTTP) {
2384
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002385 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002386 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002387 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002388 http_txn_reset_res(stream->txn);
2389
2390 if (stream->txn->hdr_idx.v)
2391 hdr_idx_init(&stream->txn->hdr_idx);
2392
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002393 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002394 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002395 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002396 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2397 }
2398}
2399
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002400/* This function is called before the Lua execution. It stores
2401 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002402 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002403static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002404{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002405 c->mode = stream->be->mode;
2406 switch (c->mode) {
2407 case PR_MODE_HTTP:
2408 c->data.http.dir = opt & SMP_OPT_DIR;
2409 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2410 c->data.http.state = stream->txn->req.msg_state;
2411 else
2412 c->data.http.state = stream->txn->rsp.msg_state;
2413 break;
2414 default:
2415 break;
2416 }
2417}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002418
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002419/* This function is called after the Lua execution. it
2420 * returns true if the parser state is consistent, otherwise,
2421 * it return false.
2422 *
2423 * In HTTP mode, the parser state must be in the same state
2424 * or greater when we exit the function. Even if we do a
2425 * control yield. This prevent to break the HTTP message
2426 * from the Lua code.
2427 */
2428static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2429{
2430 if (c->mode != stream->be->mode)
2431 return 0;
2432
2433 switch (c->mode) {
2434 case PR_MODE_HTTP:
2435 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002436 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002437 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2438 return stream->txn->req.msg_state >= c->data.http.state;
2439 else
2440 return stream->txn->rsp.msg_state >= c->data.http.state;
2441 default:
2442 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002443 }
2444 return 1;
2445}
2446
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002447/* Returns the struct hlua_channel join to the class channel in the
2448 * stack entry "ud" or throws an argument error.
2449 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002450__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002451{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002452 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002453}
2454
Willy Tarreau47860ed2015-03-10 14:07:50 +01002455/* Pushes the channel onto the top of the stack. If the stask does not have a
2456 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002457 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002458static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002459{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002460 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002461 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002462 return 0;
2463
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002464 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002465 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002466 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002467
2468 /* Pop a class sesison metatable and affect it to the userdata. */
2469 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2470 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002471 return 1;
2472}
2473
2474/* Duplicate all the data present in the input channel and put it
2475 * in a string LUA variables. Returns -1 and push a nil value in
2476 * the stack if the channel is closed and all the data are consumed,
2477 * returns 0 if no data are available, otherwise it returns the length
2478 * of the builded string.
2479 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002480static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002481{
2482 char *blk1;
2483 char *blk2;
2484 int len1;
2485 int len2;
2486 int ret;
2487 luaL_Buffer b;
2488
Willy Tarreau47860ed2015-03-10 14:07:50 +01002489 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002490 if (unlikely(ret == 0))
2491 return 0;
2492
2493 if (unlikely(ret < 0)) {
2494 lua_pushnil(L);
2495 return -1;
2496 }
2497
2498 luaL_buffinit(L, &b);
2499 luaL_addlstring(&b, blk1, len1);
2500 if (unlikely(ret == 2))
2501 luaL_addlstring(&b, blk2, len2);
2502 luaL_pushresult(&b);
2503
2504 if (unlikely(ret == 2))
2505 return len1 + len2;
2506 return len1;
2507}
2508
2509/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2510 * a yield. This function keep the data in the buffer.
2511 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002512__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002513{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002514 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002515
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002516 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2517
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002518 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002519 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002520 return 1;
2521}
2522
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002523/* Check arguments for the function "hlua_channel_dup_yield". */
2524__LJMP static int hlua_channel_dup(lua_State *L)
2525{
2526 MAY_LJMP(check_args(L, 1, "dup"));
2527 MAY_LJMP(hlua_checkchannel(L, 1));
2528 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2529}
2530
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002531/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2532 * a yield. This function consumes the data in the buffer. It returns
2533 * a string containing the data or a nil pointer if no data are available
2534 * and the channel is closed.
2535 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002536__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002537{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002538 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002539 int ret;
2540
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002541 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002542
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002543 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002544 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002545 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002546
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002547 if (unlikely(ret == -1))
2548 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002549
Willy Tarreau47860ed2015-03-10 14:07:50 +01002550 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002551 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002552 return 1;
2553}
2554
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002555/* Check arguments for the fucntion "hlua_channel_get_yield". */
2556__LJMP static int hlua_channel_get(lua_State *L)
2557{
2558 MAY_LJMP(check_args(L, 1, "get"));
2559 MAY_LJMP(hlua_checkchannel(L, 1));
2560 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2561}
2562
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002563/* This functions consumes and returns one line. If the channel is closed,
2564 * and the last data does not contains a final '\n', the data are returned
2565 * without the final '\n'. When no more data are avalaible, it returns nil
2566 * value.
2567 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002568__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002569{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002570 char *blk1;
2571 char *blk2;
2572 int len1;
2573 int len2;
2574 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002575 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002576 int ret;
2577 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002578
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002579 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2580
Willy Tarreau47860ed2015-03-10 14:07:50 +01002581 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002582 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002583 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002584
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002585 if (ret == -1) {
2586 lua_pushnil(L);
2587 return 1;
2588 }
2589
2590 luaL_buffinit(L, &b);
2591 luaL_addlstring(&b, blk1, len1);
2592 len = len1;
2593 if (unlikely(ret == 2)) {
2594 luaL_addlstring(&b, blk2, len2);
2595 len += len2;
2596 }
2597 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002598 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002599 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002600 return 1;
2601}
2602
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002603/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2604__LJMP static int hlua_channel_getline(lua_State *L)
2605{
2606 MAY_LJMP(check_args(L, 1, "getline"));
2607 MAY_LJMP(hlua_checkchannel(L, 1));
2608 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2609}
2610
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002611/* This function takes a string as input, and append it at the
2612 * input side of channel. If the data is too big, but a space
2613 * is probably available after sending some data, the function
2614 * yield. If the data is bigger than the buffer, or if the
2615 * channel is closed, it returns -1. otherwise, it returns the
2616 * amount of data writed.
2617 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002618__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002619{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002620 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002621 size_t len;
2622 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2623 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2624 int ret;
2625 int max;
2626
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002627 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2628 * the request buffer if its not required.
2629 */
2630 if (chn->buf->size == 0) {
2631 si_applet_cant_put(chn_prod(chn));
2632 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2633 }
2634
Willy Tarreau47860ed2015-03-10 14:07:50 +01002635 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002636 if (max > len - l)
2637 max = len - l;
2638
Willy Tarreau47860ed2015-03-10 14:07:50 +01002639 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002640 if (ret == -2 || ret == -3) {
2641 lua_pushinteger(L, -1);
2642 return 1;
2643 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002644 if (ret == -1) {
2645 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002646 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002647 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002648 l += ret;
2649 lua_pop(L, 1);
2650 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002651 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002652
Willy Tarreau47860ed2015-03-10 14:07:50 +01002653 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2654 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002655 /* There are no space avalaible, and the output buffer is empty.
2656 * in this case, we cannot add more data, so we cannot yield,
2657 * we return the amount of copyied data.
2658 */
2659 return 1;
2660 }
2661 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002662 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002663 return 1;
2664}
2665
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002666/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002667 * of the writed string, or -1 if the channel is closed or if the
2668 * buffer size is too little for the data.
2669 */
2670__LJMP static int hlua_channel_append(lua_State *L)
2671{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002672 size_t len;
2673
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002674 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002675 MAY_LJMP(hlua_checkchannel(L, 1));
2676 MAY_LJMP(luaL_checklstring(L, 2, &len));
2677 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002678 lua_pushinteger(L, 0);
2679
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002680 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002681}
2682
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002683/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002684 * his process by cleaning the buffer. The result is a replacement
2685 * of the current data. It returns the length of the writed string,
2686 * or -1 if the channel is closed or if the buffer size is too
2687 * little for the data.
2688 */
2689__LJMP static int hlua_channel_set(lua_State *L)
2690{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002691 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002692
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002693 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002694 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002695 lua_pushinteger(L, 0);
2696
Willy Tarreau47860ed2015-03-10 14:07:50 +01002697 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002698
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002699 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002700}
2701
2702/* Append data in the output side of the buffer. This data is immediatly
2703 * sent. The fcuntion returns the ammount of data writed. If the buffer
2704 * cannot contains the data, the function yield. The function returns -1
2705 * if the channel is closed.
2706 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002707__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002708{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002709 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002710 size_t len;
2711 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2712 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2713 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002714 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002715
Willy Tarreau47860ed2015-03-10 14:07:50 +01002716 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002717 lua_pushinteger(L, -1);
2718 return 1;
2719 }
2720
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002721 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2722 * the request buffer if its not required.
2723 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002724 if (chn->buf->size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002725 si_applet_cant_put(chn_prod(chn));
2726 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002727 }
2728
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002729 /* the writed data will be immediatly sent, so we can check
2730 * the avalaible space without taking in account the reserve.
2731 * The reserve is guaranted for the processing of incoming
2732 * data, because the buffer will be flushed.
2733 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002734 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002735
2736 /* If there are no space avalaible, and the output buffer is empty.
2737 * in this case, we cannot add more data, so we cannot yield,
2738 * we return the amount of copyied data.
2739 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002740 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002741 return 1;
2742
2743 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002744 if (max > len - l)
2745 max = len - l;
2746
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002747 /* The buffer avalaible size may be not contiguous. This test
2748 * detects a non contiguous buffer and realign it.
2749 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002750 if (bi_space_for_replace(chn->buf) < max)
2751 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002752
2753 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002754 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002755
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002756 /* buffer replace considers that the input part is filled.
2757 * so, I must forward these new data in the output part.
2758 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002759 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002760
2761 l += max;
2762 lua_pop(L, 1);
2763 lua_pushinteger(L, l);
2764
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002765 /* If there are no space avalaible, and the output buffer is empty.
2766 * in this case, we cannot add more data, so we cannot yield,
2767 * we return the amount of copyied data.
2768 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002769 max = chn->buf->size - buffer_len(chn->buf);
2770 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002771 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002772
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002773 if (l < len) {
2774 /* If we are waiting for space in the response buffer, we
2775 * must set the flag WAKERESWR. This flag required the task
2776 * wake up if any activity is detected on the response buffer.
2777 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002778 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002779 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002780 else
2781 HLUA_SET_WAKEREQWR(hlua);
2782 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002783 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002784
2785 return 1;
2786}
2787
2788/* Just a wraper of "_hlua_channel_send". This wrapper permits
2789 * yield the LUA process, and resume it without checking the
2790 * input arguments.
2791 */
2792__LJMP static int hlua_channel_send(lua_State *L)
2793{
2794 MAY_LJMP(check_args(L, 2, "send"));
2795 lua_pushinteger(L, 0);
2796
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002797 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002798}
2799
2800/* This function forward and amount of butes. The data pass from
2801 * the input side of the buffer to the output side, and can be
2802 * forwarded. This function never fails.
2803 *
2804 * The Lua function takes an amount of bytes to be forwarded in
2805 * imput. It returns the number of bytes forwarded.
2806 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002807__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002808{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002809 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002810 int len;
2811 int l;
2812 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002813 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002814
2815 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2816 len = MAY_LJMP(luaL_checkinteger(L, 2));
2817 l = MAY_LJMP(luaL_checkinteger(L, -1));
2818
2819 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002820 if (max > chn->buf->i)
2821 max = chn->buf->i;
2822 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002823 l += max;
2824
2825 lua_pop(L, 1);
2826 lua_pushinteger(L, l);
2827
2828 /* Check if it miss bytes to forward. */
2829 if (l < len) {
2830 /* The the input channel or the output channel are closed, we
2831 * must return the amount of data forwarded.
2832 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002833 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002834 return 1;
2835
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002836 /* If we are waiting for space data in the response buffer, we
2837 * must set the flag WAKERESWR. This flag required the task
2838 * wake up if any activity is detected on the response buffer.
2839 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002840 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002841 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002842 else
2843 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002844
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002845 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002846 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002847 }
2848
2849 return 1;
2850}
2851
2852/* Just check the input and prepare the stack for the previous
2853 * function "hlua_channel_forward_yield"
2854 */
2855__LJMP static int hlua_channel_forward(lua_State *L)
2856{
2857 MAY_LJMP(check_args(L, 2, "forward"));
2858 MAY_LJMP(hlua_checkchannel(L, 1));
2859 MAY_LJMP(luaL_checkinteger(L, 2));
2860
2861 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002862 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002863}
2864
2865/* Just returns the number of bytes available in the input
2866 * side of the buffer. This function never fails.
2867 */
2868__LJMP static int hlua_channel_get_in_len(lua_State *L)
2869{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002870 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002871
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002872 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002873 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002874 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002875 return 1;
2876}
2877
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01002878/* Returns true if the channel is full. */
2879__LJMP static int hlua_channel_is_full(lua_State *L)
2880{
2881 struct channel *chn;
2882 int rem;
2883
2884 MAY_LJMP(check_args(L, 1, "is_full"));
2885 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2886
2887 rem = chn->buf->size;
2888 rem -= chn->buf->o; /* Output size */
2889 rem -= chn->buf->i; /* Input size */
2890 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
2891
2892 lua_pushboolean(L, rem <= 0);
2893 return 1;
2894}
2895
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002896/* Just returns the number of bytes available in the output
2897 * side of the buffer. This function never fails.
2898 */
2899__LJMP static int hlua_channel_get_out_len(lua_State *L)
2900{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002901 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002902
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002903 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002904 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002905 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002906 return 1;
2907}
2908
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002909/*
2910 *
2911 *
2912 * Class Fetches
2913 *
2914 *
2915 */
2916
2917/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002918 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002919 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002920__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002921{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002922 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002923}
2924
2925/* This function creates and push in the stack a fetch object according
2926 * with a current TXN.
2927 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002928static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002929{
Willy Tarreau7073c472015-04-06 11:15:40 +02002930 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002931
2932 /* Check stack size. */
2933 if (!lua_checkstack(L, 3))
2934 return 0;
2935
2936 /* Create the object: obj[0] = userdata.
2937 * Note that the base of the Fetches object is the
2938 * transaction object.
2939 */
2940 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002941 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002942 lua_rawseti(L, -2, 0);
2943
Willy Tarreau7073c472015-04-06 11:15:40 +02002944 hsmp->s = txn->s;
2945 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01002946 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002947 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002948
2949 /* Pop a class sesison metatable and affect it to the userdata. */
2950 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2951 lua_setmetatable(L, -2);
2952
2953 return 1;
2954}
2955
2956/* This function is an LUA binding. It is called with each sample-fetch.
2957 * It uses closure argument to store the associated sample-fetch. It
2958 * returns only one argument or throws an error. An error is thrown
2959 * only if an error is encountered during the argument parsing. If
2960 * the "sample-fetch" function fails, nil is returned.
2961 */
2962__LJMP static int hlua_run_sample_fetch(lua_State *L)
2963{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002964 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002965 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002966 struct arg args[ARGM_NBARGS + 1];
2967 int i;
2968 struct sample smp;
2969
2970 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002971 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002972
2973 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002974 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002975
Thierry FOURNIERca988662015-12-20 18:43:03 +01002976 /* Check execution authorization. */
2977 if (f->use & SMP_USE_HTTP_ANY &&
2978 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
2979 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
2980 "is not available in Lua services", f->kw);
2981 WILL_LJMP(lua_error(L));
2982 }
2983
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002984 /* Get extra arguments. */
2985 for (i = 0; i < lua_gettop(L) - 1; i++) {
2986 if (i >= ARGM_NBARGS)
2987 break;
2988 hlua_lua2arg(L, i + 2, &args[i]);
2989 }
2990 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01002991 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002992
2993 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002994 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002995
2996 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002997 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002998 lua_pushfstring(L, "error in arguments");
2999 WILL_LJMP(lua_error(L));
3000 }
3001
3002 /* Initialise the sample. */
3003 memset(&smp, 0, sizeof(smp));
3004
3005 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003006 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003007 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003008 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003009 lua_pushstring(L, "");
3010 else
3011 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003012 return 1;
3013 }
3014
3015 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003016 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003017 hlua_smp2lua_str(L, &smp);
3018 else
3019 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003020 return 1;
3021}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003022
3023/*
3024 *
3025 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003026 * Class Converters
3027 *
3028 *
3029 */
3030
3031/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003032 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003033 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003034__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003035{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003036 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003037}
3038
3039/* This function creates and push in the stack a Converters object
3040 * according with a current TXN.
3041 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003042static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003043{
Willy Tarreau7073c472015-04-06 11:15:40 +02003044 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003045
3046 /* Check stack size. */
3047 if (!lua_checkstack(L, 3))
3048 return 0;
3049
3050 /* Create the object: obj[0] = userdata.
3051 * Note that the base of the Converters object is the
3052 * same than the TXN object.
3053 */
3054 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003055 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003056 lua_rawseti(L, -2, 0);
3057
Willy Tarreau7073c472015-04-06 11:15:40 +02003058 hsmp->s = txn->s;
3059 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003060 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003061 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003062
Willy Tarreau87b09662015-04-03 00:22:06 +02003063 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003064 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3065 lua_setmetatable(L, -2);
3066
3067 return 1;
3068}
3069
3070/* This function is an LUA binding. It is called with each converter.
3071 * It uses closure argument to store the associated converter. It
3072 * returns only one argument or throws an error. An error is thrown
3073 * only if an error is encountered during the argument parsing. If
3074 * the converter function function fails, nil is returned.
3075 */
3076__LJMP static int hlua_run_sample_conv(lua_State *L)
3077{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003078 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003079 struct sample_conv *conv;
3080 struct arg args[ARGM_NBARGS + 1];
3081 int i;
3082 struct sample smp;
3083
3084 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003085 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003086
3087 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003088 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003089
3090 /* Get extra arguments. */
3091 for (i = 0; i < lua_gettop(L) - 2; i++) {
3092 if (i >= ARGM_NBARGS)
3093 break;
3094 hlua_lua2arg(L, i + 3, &args[i]);
3095 }
3096 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003097 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003098
3099 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003100 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003101
3102 /* Run the special args checker. */
3103 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3104 hlua_pusherror(L, "error in arguments");
3105 WILL_LJMP(lua_error(L));
3106 }
3107
3108 /* Initialise the sample. */
3109 if (!hlua_lua2smp(L, 2, &smp)) {
3110 hlua_pusherror(L, "error in the input argument");
3111 WILL_LJMP(lua_error(L));
3112 }
3113
Willy Tarreau1777ea62016-03-10 16:15:46 +01003114 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3115
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003116 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003117 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003118 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003119 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003120 WILL_LJMP(lua_error(L));
3121 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003122 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3123 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003124 hlua_pusherror(L, "error during the input argument casting");
3125 WILL_LJMP(lua_error(L));
3126 }
3127
3128 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003129 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003130 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003131 lua_pushstring(L, "");
3132 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003133 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003134 return 1;
3135 }
3136
3137 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003138 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003139 hlua_smp2lua_str(L, &smp);
3140 else
3141 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003142 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003143}
3144
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003145/*
3146 *
3147 *
3148 * Class AppletTCP
3149 *
3150 *
3151 */
3152
3153/* Returns a struct hlua_txn if the stack entry "ud" is
3154 * a class stream, otherwise it throws an error.
3155 */
3156__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3157{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003158 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003159}
3160
3161/* This function creates and push in the stack an Applet object
3162 * according with a current TXN.
3163 */
3164static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3165{
3166 struct hlua_appctx *appctx;
3167 struct stream_interface *si = ctx->owner;
3168 struct stream *s = si_strm(si);
3169 struct proxy *p = s->be;
3170
3171 /* Check stack size. */
3172 if (!lua_checkstack(L, 3))
3173 return 0;
3174
3175 /* Create the object: obj[0] = userdata.
3176 * Note that the base of the Converters object is the
3177 * same than the TXN object.
3178 */
3179 lua_newtable(L);
3180 appctx = lua_newuserdata(L, sizeof(*appctx));
3181 lua_rawseti(L, -2, 0);
3182 appctx->appctx = ctx;
3183 appctx->htxn.s = s;
3184 appctx->htxn.p = p;
3185
3186 /* Create the "f" field that contains a list of fetches. */
3187 lua_pushstring(L, "f");
3188 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3189 return 0;
3190 lua_settable(L, -3);
3191
3192 /* Create the "sf" field that contains a list of stringsafe fetches. */
3193 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003194 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003195 return 0;
3196 lua_settable(L, -3);
3197
3198 /* Create the "c" field that contains a list of converters. */
3199 lua_pushstring(L, "c");
3200 if (!hlua_converters_new(L, &appctx->htxn, 0))
3201 return 0;
3202 lua_settable(L, -3);
3203
3204 /* Create the "sc" field that contains a list of stringsafe converters. */
3205 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003206 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003207 return 0;
3208 lua_settable(L, -3);
3209
3210 /* Pop a class stream metatable and affect it to the table. */
3211 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3212 lua_setmetatable(L, -2);
3213
3214 return 1;
3215}
3216
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003217__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3218{
3219 struct hlua_appctx *appctx;
3220 struct stream *s;
3221 const char *name;
3222 size_t len;
3223 struct sample smp;
3224
3225 MAY_LJMP(check_args(L, 3, "set_var"));
3226
3227 /* It is useles to retrieve the stream, but this function
3228 * runs only in a stream context.
3229 */
3230 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3231 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3232 s = appctx->htxn.s;
3233
3234 /* Converts the third argument in a sample. */
3235 hlua_lua2smp(L, 3, &smp);
3236
3237 /* Store the sample in a variable. */
3238 smp_set_owner(&smp, s->be, s->sess, s, 0);
3239 vars_set_by_name(name, len, &smp);
3240 return 0;
3241}
3242
3243__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3244{
3245 struct hlua_appctx *appctx;
3246 struct stream *s;
3247 const char *name;
3248 size_t len;
3249 struct sample smp;
3250
3251 MAY_LJMP(check_args(L, 2, "unset_var"));
3252
3253 /* It is useles to retrieve the stream, but this function
3254 * runs only in a stream context.
3255 */
3256 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3257 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3258 s = appctx->htxn.s;
3259
3260 /* Unset the variable. */
3261 smp_set_owner(&smp, s->be, s->sess, s, 0);
3262 vars_unset_by_name(name, len, &smp);
3263 return 0;
3264}
3265
3266__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3267{
3268 struct hlua_appctx *appctx;
3269 struct stream *s;
3270 const char *name;
3271 size_t len;
3272 struct sample smp;
3273
3274 MAY_LJMP(check_args(L, 2, "get_var"));
3275
3276 /* It is useles to retrieve the stream, but this function
3277 * runs only in a stream context.
3278 */
3279 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3280 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3281 s = appctx->htxn.s;
3282
3283 smp_set_owner(&smp, s->be, s->sess, s, 0);
3284 if (!vars_get_by_name(name, len, &smp)) {
3285 lua_pushnil(L);
3286 return 1;
3287 }
3288
3289 return hlua_smp2lua(L, &smp);
3290}
3291
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003292__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3293{
3294 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3295 struct stream *s = appctx->htxn.s;
3296 struct hlua *hlua = &s->hlua;
3297
3298 MAY_LJMP(check_args(L, 2, "set_priv"));
3299
3300 /* Remove previous value. */
3301 if (hlua->Mref != -1)
3302 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3303
3304 /* Get and store new value. */
3305 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3306 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3307
3308 return 0;
3309}
3310
3311__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3312{
3313 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3314 struct stream *s = appctx->htxn.s;
3315 struct hlua *hlua = &s->hlua;
3316
3317 /* Push configuration index in the stack. */
3318 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3319
3320 return 1;
3321}
3322
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003323/* If expected data not yet available, it returns a yield. This function
3324 * consumes the data in the buffer. It returns a string containing the
3325 * data. This string can be empty.
3326 */
3327__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3328{
3329 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3330 struct stream_interface *si = appctx->appctx->owner;
3331 int ret;
3332 char *blk1;
3333 int len1;
3334 char *blk2;
3335 int len2;
3336
3337 /* Read the maximum amount of data avalaible. */
3338 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3339
3340 /* Data not yet avalaible. return yield. */
3341 if (ret == 0) {
3342 si_applet_cant_get(si);
3343 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3344 }
3345
3346 /* End of data: commit the total strings and return. */
3347 if (ret < 0) {
3348 luaL_pushresult(&appctx->b);
3349 return 1;
3350 }
3351
3352 /* Ensure that the block 2 length is usable. */
3353 if (ret == 1)
3354 len2 = 0;
3355
3356 /* dont check the max length read and dont check. */
3357 luaL_addlstring(&appctx->b, blk1, len1);
3358 luaL_addlstring(&appctx->b, blk2, len2);
3359
3360 /* Consume input channel output buffer data. */
3361 bo_skip(si_oc(si), len1 + len2);
3362 luaL_pushresult(&appctx->b);
3363 return 1;
3364}
3365
3366/* Check arguments for the fucntion "hlua_channel_get_yield". */
3367__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3368{
3369 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3370
3371 /* Initialise the string catenation. */
3372 luaL_buffinit(L, &appctx->b);
3373
3374 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3375}
3376
3377/* If expected data not yet available, it returns a yield. This function
3378 * consumes the data in the buffer. It returns a string containing the
3379 * data. This string can be empty.
3380 */
3381__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3382{
3383 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3384 struct stream_interface *si = appctx->appctx->owner;
3385 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3386 int ret;
3387 char *blk1;
3388 int len1;
3389 char *blk2;
3390 int len2;
3391
3392 /* Read the maximum amount of data avalaible. */
3393 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3394
3395 /* Data not yet avalaible. return yield. */
3396 if (ret == 0) {
3397 si_applet_cant_get(si);
3398 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3399 }
3400
3401 /* End of data: commit the total strings and return. */
3402 if (ret < 0) {
3403 luaL_pushresult(&appctx->b);
3404 return 1;
3405 }
3406
3407 /* Ensure that the block 2 length is usable. */
3408 if (ret == 1)
3409 len2 = 0;
3410
3411 if (len == -1) {
3412
3413 /* If len == -1, catenate all the data avalaile and
3414 * yield because we want to get all the data until
3415 * the end of data stream.
3416 */
3417 luaL_addlstring(&appctx->b, blk1, len1);
3418 luaL_addlstring(&appctx->b, blk2, len2);
3419 bo_skip(si_oc(si), len1 + len2);
3420 si_applet_cant_get(si);
3421 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3422
3423 } else {
3424
3425 /* Copy the fisrt block caping to the length required. */
3426 if (len1 > len)
3427 len1 = len;
3428 luaL_addlstring(&appctx->b, blk1, len1);
3429 len -= len1;
3430
3431 /* Copy the second block. */
3432 if (len2 > len)
3433 len2 = len;
3434 luaL_addlstring(&appctx->b, blk2, len2);
3435 len -= len2;
3436
3437 /* Consume input channel output buffer data. */
3438 bo_skip(si_oc(si), len1 + len2);
3439
3440 /* If we are no other data avalaible, yield waiting for new data. */
3441 if (len > 0) {
3442 lua_pushinteger(L, len);
3443 lua_replace(L, 2);
3444 si_applet_cant_get(si);
3445 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3446 }
3447
3448 /* return the result. */
3449 luaL_pushresult(&appctx->b);
3450 return 1;
3451 }
3452
3453 /* we never executes this */
3454 hlua_pusherror(L, "Lua: internal error");
3455 WILL_LJMP(lua_error(L));
3456 return 0;
3457}
3458
3459/* Check arguments for the fucntion "hlua_channel_get_yield". */
3460__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3461{
3462 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3463 int len = -1;
3464
3465 if (lua_gettop(L) > 2)
3466 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3467 if (lua_gettop(L) >= 2) {
3468 len = MAY_LJMP(luaL_checkinteger(L, 2));
3469 lua_pop(L, 1);
3470 }
3471
3472 /* Confirm or set the required length */
3473 lua_pushinteger(L, len);
3474
3475 /* Initialise the string catenation. */
3476 luaL_buffinit(L, &appctx->b);
3477
3478 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3479}
3480
3481/* Append data in the output side of the buffer. This data is immediatly
3482 * sent. The fcuntion returns the ammount of data writed. If the buffer
3483 * cannot contains the data, the function yield. The function returns -1
3484 * if the channel is closed.
3485 */
3486__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3487{
3488 size_t len;
3489 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3490 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3491 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3492 struct stream_interface *si = appctx->appctx->owner;
3493 struct channel *chn = si_ic(si);
3494 int max;
3495
3496 /* Get the max amount of data which can write as input in the channel. */
3497 max = channel_recv_max(chn);
3498 if (max > (len - l))
3499 max = len - l;
3500
3501 /* Copy data. */
3502 bi_putblk(chn, str + l, max);
3503
3504 /* update counters. */
3505 l += max;
3506 lua_pop(L, 1);
3507 lua_pushinteger(L, l);
3508
3509 /* If some data is not send, declares the situation to the
3510 * applet, and returns a yield.
3511 */
3512 if (l < len) {
3513 si_applet_cant_put(si);
3514 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3515 }
3516
3517 return 1;
3518}
3519
3520/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3521 * yield the LUA process, and resume it without checking the
3522 * input arguments.
3523 */
3524__LJMP static int hlua_applet_tcp_send(lua_State *L)
3525{
3526 MAY_LJMP(check_args(L, 2, "send"));
3527 lua_pushinteger(L, 0);
3528
3529 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3530}
3531
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003532/*
3533 *
3534 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003535 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003536 *
3537 *
3538 */
3539
3540/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003541 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003542 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003543__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003544{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003545 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003546}
3547
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003548/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003549 * according with a current TXN.
3550 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003551static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003552{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003553 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003554 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003555 struct stream_interface *si = ctx->owner;
3556 struct stream *s = si_strm(si);
3557 struct proxy *px = s->be;
3558 struct http_txn *txn = s->txn;
3559 const char *path;
3560 const char *end;
3561 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003562
3563 /* Check stack size. */
3564 if (!lua_checkstack(L, 3))
3565 return 0;
3566
3567 /* Create the object: obj[0] = userdata.
3568 * Note that the base of the Converters object is the
3569 * same than the TXN object.
3570 */
3571 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003572 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003573 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003574 appctx->appctx = ctx;
3575 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
3576 appctx->htxn.s = s;
3577 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003578
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003579 /* Create the "f" field that contains a list of fetches. */
3580 lua_pushstring(L, "f");
3581 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3582 return 0;
3583 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003584
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003585 /* Create the "sf" field that contains a list of stringsafe fetches. */
3586 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003587 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003588 return 0;
3589 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003590
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003591 /* Create the "c" field that contains a list of converters. */
3592 lua_pushstring(L, "c");
3593 if (!hlua_converters_new(L, &appctx->htxn, 0))
3594 return 0;
3595 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003596
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003597 /* Create the "sc" field that contains a list of stringsafe converters. */
3598 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003599 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003600 return 0;
3601 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003602
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003603 /* Stores the request method. */
3604 lua_pushstring(L, "method");
3605 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3606 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003607
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003608 /* Stores the http version. */
3609 lua_pushstring(L, "version");
3610 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3611 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003612
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003613 /* creates an array of headers. hlua_http_get_headers() crates and push
3614 * the array on the top of the stack.
3615 */
3616 lua_pushstring(L, "headers");
3617 htxn.s = s;
3618 htxn.p = px;
3619 htxn.dir = SMP_OPT_DIR_REQ;
3620 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3621 return 0;
3622 lua_settable(L, -3);
3623
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003624 /* Get path and qs */
3625 path = http_get_path(txn);
3626 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3627 p = path;
3628 while (p < end && *p != '?')
3629 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003630
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003631 /* Stores the request path. */
3632 lua_pushstring(L, "path");
3633 lua_pushlstring(L, path, p - path);
3634 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003635
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003636 /* Stores the query string. */
3637 lua_pushstring(L, "qs");
3638 if (*p == '?')
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003639 p++;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003640 lua_pushlstring(L, p, end - p);
3641 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003642
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003643 /* Stores the request path. */
3644 lua_pushstring(L, "length");
3645 lua_pushinteger(L, txn->req.body_len);
3646 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003647
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003648 /* Create an array of HTTP request headers. */
3649 lua_pushstring(L, "headers");
3650 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3651 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003652
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003653 /* Create an empty array of HTTP request headers. */
3654 lua_pushstring(L, "response");
3655 lua_newtable(L);
3656 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003657
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003658 /* Pop a class stream metatable and affect it to the table. */
3659 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3660 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003661
3662 return 1;
3663}
3664
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003665__LJMP static int hlua_applet_http_set_var(lua_State *L)
3666{
3667 struct hlua_appctx *appctx;
3668 struct stream *s;
3669 const char *name;
3670 size_t len;
3671 struct sample smp;
3672
3673 MAY_LJMP(check_args(L, 3, "set_var"));
3674
3675 /* It is useles to retrieve the stream, but this function
3676 * runs only in a stream context.
3677 */
3678 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3679 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3680 s = appctx->htxn.s;
3681
3682 /* Converts the third argument in a sample. */
3683 hlua_lua2smp(L, 3, &smp);
3684
3685 /* Store the sample in a variable. */
3686 smp_set_owner(&smp, s->be, s->sess, s, 0);
3687 vars_set_by_name(name, len, &smp);
3688 return 0;
3689}
3690
3691__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3692{
3693 struct hlua_appctx *appctx;
3694 struct stream *s;
3695 const char *name;
3696 size_t len;
3697 struct sample smp;
3698
3699 MAY_LJMP(check_args(L, 2, "unset_var"));
3700
3701 /* It is useles to retrieve the stream, but this function
3702 * runs only in a stream context.
3703 */
3704 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3705 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3706 s = appctx->htxn.s;
3707
3708 /* Unset the variable. */
3709 smp_set_owner(&smp, s->be, s->sess, s, 0);
3710 vars_unset_by_name(name, len, &smp);
3711 return 0;
3712}
3713
3714__LJMP static int hlua_applet_http_get_var(lua_State *L)
3715{
3716 struct hlua_appctx *appctx;
3717 struct stream *s;
3718 const char *name;
3719 size_t len;
3720 struct sample smp;
3721
3722 MAY_LJMP(check_args(L, 2, "get_var"));
3723
3724 /* It is useles to retrieve the stream, but this function
3725 * runs only in a stream context.
3726 */
3727 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3728 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3729 s = appctx->htxn.s;
3730
3731 smp_set_owner(&smp, s->be, s->sess, s, 0);
3732 if (!vars_get_by_name(name, len, &smp)) {
3733 lua_pushnil(L);
3734 return 1;
3735 }
3736
3737 return hlua_smp2lua(L, &smp);
3738}
3739
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003740__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3741{
3742 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3743 struct stream *s = appctx->htxn.s;
3744 struct hlua *hlua = &s->hlua;
3745
3746 MAY_LJMP(check_args(L, 2, "set_priv"));
3747
3748 /* Remove previous value. */
3749 if (hlua->Mref != -1)
3750 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3751
3752 /* Get and store new value. */
3753 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3754 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3755
3756 return 0;
3757}
3758
3759__LJMP static int hlua_applet_http_get_priv(lua_State *L)
3760{
3761 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3762 struct stream *s = appctx->htxn.s;
3763 struct hlua *hlua = &s->hlua;
3764
3765 /* Push configuration index in the stack. */
3766 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3767
3768 return 1;
3769}
3770
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003771/* If expected data not yet available, it returns a yield. This function
3772 * consumes the data in the buffer. It returns a string containing the
3773 * data. This string can be empty.
3774 */
3775__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003776{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003777 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3778 struct stream_interface *si = appctx->appctx->owner;
3779 struct channel *chn = si_ic(si);
3780 int ret;
3781 char *blk1;
3782 int len1;
3783 char *blk2;
3784 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003785
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003786 /* Maybe we cant send a 100-continue ? */
3787 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3788 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3789 /* if ret == -2 or -3 the channel closed or the message si too
3790 * big for the buffers. We cant send anything. So, we ignoring
3791 * the error, considers that the 100-continue is sent, and try
3792 * to receive.
3793 * If ret is -1, we dont have room in the buffer, so we yield.
3794 */
3795 if (ret == -1) {
3796 si_applet_cant_put(si);
3797 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3798 }
3799 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3800 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003801
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003802 /* Check for the end of the data. */
3803 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3804 luaL_pushresult(&appctx->b);
3805 return 1;
3806 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003807
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003808 /* Read the maximum amount of data avalaible. */
3809 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003810
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003811 /* Data not yet avalaible. return yield. */
3812 if (ret == 0) {
3813 si_applet_cant_get(si);
3814 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3815 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003816
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003817 /* End of data: commit the total strings and return. */
3818 if (ret < 0) {
3819 luaL_pushresult(&appctx->b);
3820 return 1;
3821 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003822
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003823 /* Ensure that the block 2 length is usable. */
3824 if (ret == 1)
3825 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003826
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003827 /* Copy the fisrt block caping to the length required. */
3828 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3829 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3830 luaL_addlstring(&appctx->b, blk1, len1);
3831 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003832
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003833 /* Copy the second block. */
3834 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3835 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3836 luaL_addlstring(&appctx->b, blk2, len2);
3837 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003838
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003839 /* Consume input channel output buffer data. */
3840 bo_skip(si_oc(si), len1 + len2);
3841 luaL_pushresult(&appctx->b);
3842 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003843}
3844
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003845/* Check arguments for the fucntion "hlua_channel_get_yield". */
3846__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003847{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003848 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003849
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003850 /* Initialise the string catenation. */
3851 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003852
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003853 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003854}
3855
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003856/* If expected data not yet available, it returns a yield. This function
3857 * consumes the data in the buffer. It returns a string containing the
3858 * data. This string can be empty.
3859 */
3860__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003861{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003862 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3863 struct stream_interface *si = appctx->appctx->owner;
3864 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3865 struct channel *chn = si_ic(si);
3866 int ret;
3867 char *blk1;
3868 int len1;
3869 char *blk2;
3870 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003871
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003872 /* Maybe we cant send a 100-continue ? */
3873 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3874 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3875 /* if ret == -2 or -3 the channel closed or the message si too
3876 * big for the buffers. We cant send anything. So, we ignoring
3877 * the error, considers that the 100-continue is sent, and try
3878 * to receive.
3879 * If ret is -1, we dont have room in the buffer, so we yield.
3880 */
3881 if (ret == -1) {
3882 si_applet_cant_put(si);
3883 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3884 }
3885 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3886 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003887
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003888 /* Read the maximum amount of data avalaible. */
3889 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003890
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003891 /* Data not yet avalaible. return yield. */
3892 if (ret == 0) {
3893 si_applet_cant_get(si);
3894 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3895 }
3896
3897 /* End of data: commit the total strings and return. */
3898 if (ret < 0) {
3899 luaL_pushresult(&appctx->b);
3900 return 1;
3901 }
3902
3903 /* Ensure that the block 2 length is usable. */
3904 if (ret == 1)
3905 len2 = 0;
3906
3907 /* Copy the fisrt block caping to the length required. */
3908 if (len1 > len)
3909 len1 = len;
3910 luaL_addlstring(&appctx->b, blk1, len1);
3911 len -= len1;
3912
3913 /* Copy the second block. */
3914 if (len2 > len)
3915 len2 = len;
3916 luaL_addlstring(&appctx->b, blk2, len2);
3917 len -= len2;
3918
3919 /* Consume input channel output buffer data. */
3920 bo_skip(si_oc(si), len1 + len2);
3921 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
3922 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
3923
3924 /* If we are no other data avalaible, yield waiting for new data. */
3925 if (len > 0) {
3926 lua_pushinteger(L, len);
3927 lua_replace(L, 2);
3928 si_applet_cant_get(si);
3929 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3930 }
3931
3932 /* return the result. */
3933 luaL_pushresult(&appctx->b);
3934 return 1;
3935}
3936
3937/* Check arguments for the fucntion "hlua_channel_get_yield". */
3938__LJMP static int hlua_applet_http_recv(lua_State *L)
3939{
3940 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3941 int len = -1;
3942
3943 /* Check arguments. */
3944 if (lua_gettop(L) > 2)
3945 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3946 if (lua_gettop(L) >= 2) {
3947 len = MAY_LJMP(luaL_checkinteger(L, 2));
3948 lua_pop(L, 1);
3949 }
3950
3951 /* Check the required length */
3952 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3953 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3954 lua_pushinteger(L, len);
3955
3956 /* Initialise the string catenation. */
3957 luaL_buffinit(L, &appctx->b);
3958
3959 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
3960}
3961
3962/* Append data in the output side of the buffer. This data is immediatly
3963 * sent. The fcuntion returns the ammount of data writed. If the buffer
3964 * cannot contains the data, the function yield. The function returns -1
3965 * if the channel is closed.
3966 */
3967__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
3968{
3969 size_t len;
3970 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3971 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3972 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3973 struct stream_interface *si = appctx->appctx->owner;
3974 struct channel *chn = si_ic(si);
3975 int max;
3976
3977 /* Get the max amount of data which can write as input in the channel. */
3978 max = channel_recv_max(chn);
3979 if (max > (len - l))
3980 max = len - l;
3981
3982 /* Copy data. */
3983 bi_putblk(chn, str + l, max);
3984
3985 /* update counters. */
3986 l += max;
3987 lua_pop(L, 1);
3988 lua_pushinteger(L, l);
3989
3990 /* If some data is not send, declares the situation to the
3991 * applet, and returns a yield.
3992 */
3993 if (l < len) {
3994 si_applet_cant_put(si);
3995 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
3996 }
3997
3998 return 1;
3999}
4000
4001/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4002 * yield the LUA process, and resume it without checking the
4003 * input arguments.
4004 */
4005__LJMP static int hlua_applet_http_send(lua_State *L)
4006{
4007 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4008 size_t len;
4009 char hex[10];
4010
4011 MAY_LJMP(luaL_checklstring(L, 2, &len));
4012
4013 /* If transfer encoding chunked is selected, we surround the data
4014 * by chunk data.
4015 */
4016 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4017 snprintf(hex, 9, "%x", (unsigned int)len);
4018 lua_pushfstring(L, "%s\r\n", hex);
4019 lua_insert(L, 2); /* swap the last 2 entries. */
4020 lua_pushstring(L, "\r\n");
4021 lua_concat(L, 3);
4022 }
4023
4024 /* This interger is used for followinf the amount of data sent. */
4025 lua_pushinteger(L, 0);
4026
4027 /* We want to send some data. Headers must be sent. */
4028 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4029 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4030 WILL_LJMP(lua_error(L));
4031 }
4032
4033 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4034}
4035
4036__LJMP static int hlua_applet_http_addheader(lua_State *L)
4037{
4038 const char *name;
4039 int ret;
4040
4041 MAY_LJMP(hlua_checkapplet_http(L, 1));
4042 name = MAY_LJMP(luaL_checkstring(L, 2));
4043 MAY_LJMP(luaL_checkstring(L, 3));
4044
4045 /* Push in the stack the "response" entry. */
4046 ret = lua_getfield(L, 1, "response");
4047 if (ret != LUA_TTABLE) {
4048 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4049 "is expected as an array. %s found", lua_typename(L, ret));
4050 WILL_LJMP(lua_error(L));
4051 }
4052
4053 /* check if the header is already registered if it is not
4054 * the case, register it.
4055 */
4056 ret = lua_getfield(L, -1, name);
4057 if (ret == LUA_TNIL) {
4058
4059 /* Entry not found. */
4060 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4061
4062 /* Insert the new header name in the array in the top of the stack.
4063 * It left the new array in the top of the stack.
4064 */
4065 lua_newtable(L);
4066 lua_pushvalue(L, 2);
4067 lua_pushvalue(L, -2);
4068 lua_settable(L, -4);
4069
4070 } else if (ret != LUA_TTABLE) {
4071
4072 /* corruption error. */
4073 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4074 "is expected as an array. %s found", name, lua_typename(L, ret));
4075 WILL_LJMP(lua_error(L));
4076 }
4077
4078 /* Now the top od thestack is an array of values. We push
4079 * the header value as new entry.
4080 */
4081 lua_pushvalue(L, 3);
4082 ret = lua_rawlen(L, -2);
4083 lua_rawseti(L, -2, ret + 1);
4084 lua_pushboolean(L, 1);
4085 return 1;
4086}
4087
4088__LJMP static int hlua_applet_http_status(lua_State *L)
4089{
4090 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4091 int status = MAY_LJMP(luaL_checkinteger(L, 2));
4092
4093 if (status < 100 || status > 599) {
4094 lua_pushboolean(L, 0);
4095 return 1;
4096 }
4097
4098 appctx->appctx->ctx.hlua_apphttp.status = status;
4099 lua_pushboolean(L, 1);
4100 return 1;
4101}
4102
4103/* We will build the status line and the headers of the HTTP response.
4104 * We will try send at once if its not possible, we give back the hand
4105 * waiting for more room.
4106 */
4107__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4108{
4109 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4110 struct stream_interface *si = appctx->appctx->owner;
4111 struct channel *chn = si_ic(si);
4112 int ret;
4113 size_t len;
4114 const char *msg;
4115
4116 /* Get the message as the first argument on the stack. */
4117 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4118
4119 /* Send the message at once. */
4120 ret = bi_putblk(chn, msg, len);
4121
4122 /* if ret == -2 or -3 the channel closed or the message si too
4123 * big for the buffers.
4124 */
4125 if (ret == -2 || ret == -3) {
4126 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4127 WILL_LJMP(lua_error(L));
4128 }
4129
4130 /* If ret is -1, we dont have room in the buffer, so we yield. */
4131 if (ret == -1) {
4132 si_applet_cant_put(si);
4133 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4134 }
4135
4136 /* Headers sent, set the flag. */
4137 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4138 return 0;
4139}
4140
4141__LJMP static int hlua_applet_http_start_response(lua_State *L)
4142{
4143 struct chunk *tmp = get_trash_chunk();
4144 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004145 const char *name;
4146 const char *value;
4147 int id;
4148 int hdr_connection = 0;
4149 int hdr_contentlength = -1;
4150 int hdr_chunked = 0;
4151
4152 /* Use the same http version than the request. */
4153 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004154 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004155 appctx->appctx->ctx.hlua_apphttp.status,
4156 get_reason(appctx->appctx->ctx.hlua_apphttp.status));
4157
4158 /* Get the array associated to the field "response" in the object AppletHTTP. */
4159 lua_pushvalue(L, 0);
4160 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4161 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4162 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4163 WILL_LJMP(lua_error(L));
4164 }
4165
4166 /* Browse the list of headers. */
4167 lua_pushnil(L);
4168 while(lua_next(L, -2) != 0) {
4169
4170 /* We expect a string as -2. */
4171 if (lua_type(L, -2) != LUA_TSTRING) {
4172 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4173 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4174 lua_typename(L, lua_type(L, -2)));
4175 WILL_LJMP(lua_error(L));
4176 }
4177 name = lua_tostring(L, -2);
4178
4179 /* We expect an array as -1. */
4180 if (lua_type(L, -1) != LUA_TTABLE) {
4181 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4182 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4183 name,
4184 lua_typename(L, lua_type(L, -1)));
4185 WILL_LJMP(lua_error(L));
4186 }
4187
4188 /* Browse the table who is on the top of the stack. */
4189 lua_pushnil(L);
4190 while(lua_next(L, -2) != 0) {
4191
4192 /* We expect a number as -2. */
4193 if (lua_type(L, -2) != LUA_TNUMBER) {
4194 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4195 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4196 name,
4197 lua_typename(L, lua_type(L, -2)));
4198 WILL_LJMP(lua_error(L));
4199 }
4200 id = lua_tointeger(L, -2);
4201
4202 /* We expect a string as -2. */
4203 if (lua_type(L, -1) != LUA_TSTRING) {
4204 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4205 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4206 name, id,
4207 lua_typename(L, lua_type(L, -1)));
4208 WILL_LJMP(lua_error(L));
4209 }
4210 value = lua_tostring(L, -1);
4211
4212 /* Catenate a new header. */
4213 chunk_appendf(tmp, "%s: %s\r\n", name, value);
4214
4215 /* Protocol checks. */
4216
4217 /* Check if the header conneciton is present. */
4218 if (strcasecmp("connection", name) == 0)
4219 hdr_connection = 1;
4220
4221 /* Copy the header content length. The length conversion
4222 * is done without control. If it contains a ad value, this
4223 * is not our problem.
4224 */
4225 if (strcasecmp("content-length", name) == 0)
4226 hdr_contentlength = atoi(value);
4227
4228 /* Check if the client annouces a transfer-encoding chunked it self. */
4229 if (strcasecmp("transfer-encoding", name) == 0 &&
4230 strcasecmp("chunked", value) == 0)
4231 hdr_chunked = 1;
4232
4233 /* Remove the array from the stack, and get next element with a remaining string. */
4234 lua_pop(L, 1);
4235 }
4236
4237 /* Remove the array from the stack, and get next element with a remaining string. */
4238 lua_pop(L, 1);
4239 }
4240
4241 /* If the http protocol version is 1.1, we expect an header "connection" set
4242 * to "close" to be HAProxy/keeplive compliant. Otherwise, we expect nothing.
4243 * If the header conneciton is present, don't change it, if it is not present,
4244 * we must set.
4245 *
4246 * we set a "connection: close" header for ensuring that the keepalive will be
4247 * respected by haproxy. HAProcy considers that the application cloe the connection
4248 * and it keep the connection from the client open.
4249 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004250 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 && !hdr_connection)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004251 chunk_appendf(tmp, "Connection: close\r\n");
4252
4253 /* If we dont have a content-length set, we must announce a transfer enconding
4254 * chunked. This is required by haproxy for the keepalive compliance.
4255 * If the applet annouce a transfer-encoding chunked itslef, don't
4256 * do anything.
4257 */
4258 if (hdr_contentlength == -1 && hdr_chunked == 0) {
4259 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4260 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4261 }
4262
4263 /* Finalize headers. */
4264 chunk_appendf(tmp, "\r\n");
4265
4266 /* Remove the last entry and the array of headers */
4267 lua_pop(L, 2);
4268
4269 /* Push the headers block. */
4270 lua_pushlstring(L, tmp->str, tmp->len);
4271
4272 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4273}
4274
4275/*
4276 *
4277 *
4278 * Class HTTP
4279 *
4280 *
4281 */
4282
4283/* Returns a struct hlua_txn if the stack entry "ud" is
4284 * a class stream, otherwise it throws an error.
4285 */
4286__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4287{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004288 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004289}
4290
4291/* This function creates and push in the stack a HTTP object
4292 * according with a current TXN.
4293 */
4294static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4295{
4296 struct hlua_txn *htxn;
4297
4298 /* Check stack size. */
4299 if (!lua_checkstack(L, 3))
4300 return 0;
4301
4302 /* Create the object: obj[0] = userdata.
4303 * Note that the base of the Converters object is the
4304 * same than the TXN object.
4305 */
4306 lua_newtable(L);
4307 htxn = lua_newuserdata(L, sizeof(*htxn));
4308 lua_rawseti(L, -2, 0);
4309
4310 htxn->s = txn->s;
4311 htxn->p = txn->p;
4312
4313 /* Pop a class stream metatable and affect it to the table. */
4314 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4315 lua_setmetatable(L, -2);
4316
4317 return 1;
4318}
4319
4320/* This function creates ans returns an array of HTTP headers.
4321 * This function does not fails. It is used as wrapper with the
4322 * 2 following functions.
4323 */
4324__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4325{
4326 const char *cur_ptr, *cur_next, *p;
4327 int old_idx, cur_idx;
4328 struct hdr_idx_elem *cur_hdr;
4329 const char *hn, *hv;
4330 int hnl, hvl;
4331 int type;
4332 const char *in;
4333 char *out;
4334 int len;
4335
4336 /* Create the table. */
4337 lua_newtable(L);
4338
4339 if (!htxn->s->txn)
4340 return 1;
4341
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004342 /* Check if a valid response is parsed */
4343 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4344 return 1;
4345
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004346 /* Build array of headers. */
4347 old_idx = 0;
4348 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4349
4350 while (1) {
4351 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4352 if (!cur_idx)
4353 break;
4354 old_idx = cur_idx;
4355
4356 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4357 cur_ptr = cur_next;
4358 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4359
4360 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4361 * and the next header starts at cur_next. We'll check
4362 * this header in the list as well as against the default
4363 * rule.
4364 */
4365
4366 /* look for ': *'. */
4367 hn = cur_ptr;
4368 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4369 if (p >= cur_ptr+cur_hdr->len)
4370 continue;
4371 hnl = p - hn;
4372 p++;
4373 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4374 p++;
4375 if (p >= cur_ptr+cur_hdr->len)
4376 continue;
4377 hv = p;
4378 hvl = cur_ptr+cur_hdr->len-p;
4379
4380 /* Lowercase the key. Don't check the size of trash, it have
4381 * the size of one buffer and the input data contains in one
4382 * buffer.
4383 */
4384 out = trash.str;
4385 for (in=hn; in<hn+hnl; in++, out++)
4386 *out = tolower(*in);
4387 *out = '\0';
4388
4389 /* Check for existing entry:
4390 * assume that the table is on the top of the stack, and
4391 * push the key in the stack, the function lua_gettable()
4392 * perform the lookup.
4393 */
4394 lua_pushlstring(L, trash.str, hnl);
4395 lua_gettable(L, -2);
4396 type = lua_type(L, -1);
4397
4398 switch (type) {
4399 case LUA_TNIL:
4400 /* Table not found, create it. */
4401 lua_pop(L, 1); /* remove the nil value. */
4402 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4403 lua_newtable(L); /* create and push empty table. */
4404 lua_pushlstring(L, hv, hvl); /* push header value. */
4405 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4406 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4407 break;
4408
4409 case LUA_TTABLE:
4410 /* Entry found: push the value in the table. */
4411 len = lua_rawlen(L, -1);
4412 lua_pushlstring(L, hv, hvl); /* push header value. */
4413 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4414 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4415 break;
4416
4417 default:
4418 /* Other cases are errors. */
4419 hlua_pusherror(L, "internal error during the parsing of headers.");
4420 WILL_LJMP(lua_error(L));
4421 }
4422 }
4423
4424 return 1;
4425}
4426
4427__LJMP static int hlua_http_req_get_headers(lua_State *L)
4428{
4429 struct hlua_txn *htxn;
4430
4431 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4432 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4433
4434 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4435}
4436
4437__LJMP static int hlua_http_res_get_headers(lua_State *L)
4438{
4439 struct hlua_txn *htxn;
4440
4441 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4442 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4443
4444 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4445}
4446
4447/* This function replace full header, or just a value in
4448 * the request or in the response. It is a wrapper fir the
4449 * 4 following functions.
4450 */
4451__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4452 struct http_msg *msg, int action)
4453{
4454 size_t name_len;
4455 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4456 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4457 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4458 struct my_regex re;
4459
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004460 /* Check if a valid response is parsed */
4461 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4462 return 0;
4463
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004464 if (!regex_comp(reg, &re, 1, 1, NULL))
4465 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4466
4467 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4468 regex_free(&re);
4469 return 0;
4470}
4471
4472__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4473{
4474 struct hlua_txn *htxn;
4475
4476 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4477 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4478
4479 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4480}
4481
4482__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4483{
4484 struct hlua_txn *htxn;
4485
4486 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4487 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4488
4489 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4490}
4491
4492__LJMP static int hlua_http_req_rep_val(lua_State *L)
4493{
4494 struct hlua_txn *htxn;
4495
4496 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4497 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4498
4499 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4500}
4501
4502__LJMP static int hlua_http_res_rep_val(lua_State *L)
4503{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004504 struct hlua_txn *htxn;
4505
4506 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4507 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4508
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004509 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004510}
4511
4512/* This function deletes all the occurences of an header.
4513 * It is a wrapper for the 2 following functions.
4514 */
4515__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4516{
4517 size_t len;
4518 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4519 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004520 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004521
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004522 /* Check if a valid response is parsed */
4523 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4524 return 0;
4525
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004526 ctx.idx = 0;
4527 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4528 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4529 return 0;
4530}
4531
4532__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4533{
4534 struct hlua_txn *htxn;
4535
4536 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4537 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4538
Willy Tarreaueee5b512015-04-03 23:46:31 +02004539 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004540}
4541
4542__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4543{
4544 struct hlua_txn *htxn;
4545
4546 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4547 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4548
Willy Tarreaueee5b512015-04-03 23:46:31 +02004549 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004550}
4551
4552/* This function adds an header. It is a wrapper used by
4553 * the 2 following functions.
4554 */
4555__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4556{
4557 size_t name_len;
4558 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4559 size_t value_len;
4560 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4561 char *p;
4562
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004563 /* Check if a valid message is parsed */
4564 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4565 return 0;
4566
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004567 /* Check length. */
4568 trash.len = value_len + name_len + 2;
4569 if (trash.len > trash.size)
4570 return 0;
4571
4572 /* Creates the header string. */
4573 p = trash.str;
4574 memcpy(p, name, name_len);
4575 p += name_len;
4576 *p = ':';
4577 p++;
4578 *p = ' ';
4579 p++;
4580 memcpy(p, value, value_len);
4581
Willy Tarreaueee5b512015-04-03 23:46:31 +02004582 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004583 trash.str, trash.len) != 0);
4584
4585 return 0;
4586}
4587
4588__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4589{
4590 struct hlua_txn *htxn;
4591
4592 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4593 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4594
Willy Tarreaueee5b512015-04-03 23:46:31 +02004595 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004596}
4597
4598__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4599{
4600 struct hlua_txn *htxn;
4601
4602 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4603 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4604
Willy Tarreaueee5b512015-04-03 23:46:31 +02004605 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004606}
4607
4608static int hlua_http_req_set_hdr(lua_State *L)
4609{
4610 struct hlua_txn *htxn;
4611
4612 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4613 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4614
Willy Tarreaueee5b512015-04-03 23:46:31 +02004615 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4616 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004617}
4618
4619static int hlua_http_res_set_hdr(lua_State *L)
4620{
4621 struct hlua_txn *htxn;
4622
4623 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4624 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4625
Willy Tarreaueee5b512015-04-03 23:46:31 +02004626 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4627 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004628}
4629
4630/* This function set the method. */
4631static int hlua_http_req_set_meth(lua_State *L)
4632{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004633 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004634 size_t name_len;
4635 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004636
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004637 /* Check if a valid request is parsed */
4638 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4639 lua_pushboolean(L, 0);
4640 return 1;
4641 }
4642
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004643 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004644 return 1;
4645}
4646
4647/* This function set the method. */
4648static int hlua_http_req_set_path(lua_State *L)
4649{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004650 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004651 size_t name_len;
4652 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004653
4654 /* Check if a valid request is parsed */
4655 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4656 lua_pushboolean(L, 0);
4657 return 1;
4658 }
4659
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004660 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004661 return 1;
4662}
4663
4664/* This function set the query-string. */
4665static int hlua_http_req_set_query(lua_State *L)
4666{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004667 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004668 size_t name_len;
4669 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004670
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004671 /* Check if a valid request is parsed */
4672 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4673 lua_pushboolean(L, 0);
4674 return 1;
4675 }
4676
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004677 /* Check length. */
4678 if (name_len > trash.size - 1) {
4679 lua_pushboolean(L, 0);
4680 return 1;
4681 }
4682
4683 /* Add the mark question as prefix. */
4684 chunk_reset(&trash);
4685 trash.str[trash.len++] = '?';
4686 memcpy(trash.str + trash.len, name, name_len);
4687 trash.len += name_len;
4688
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004689 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004690 return 1;
4691}
4692
4693/* This function set the uri. */
4694static int hlua_http_req_set_uri(lua_State *L)
4695{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004696 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004697 size_t name_len;
4698 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004699
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004700 /* Check if a valid request is parsed */
4701 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4702 lua_pushboolean(L, 0);
4703 return 1;
4704 }
4705
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004706 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004707 return 1;
4708}
4709
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004710/* This function set the response code. */
4711static int hlua_http_res_set_status(lua_State *L)
4712{
4713 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4714 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
4715
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004716 /* Check if a valid response is parsed */
4717 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4718 return 0;
4719
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004720 http_set_status(code, htxn->s);
4721 return 0;
4722}
4723
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004724/*
4725 *
4726 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004727 * Class TXN
4728 *
4729 *
4730 */
4731
4732/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004733 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004734 */
4735__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4736{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004737 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004738}
4739
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004740__LJMP static int hlua_set_var(lua_State *L)
4741{
4742 struct hlua_txn *htxn;
4743 const char *name;
4744 size_t len;
4745 struct sample smp;
4746
4747 MAY_LJMP(check_args(L, 3, "set_var"));
4748
4749 /* It is useles to retrieve the stream, but this function
4750 * runs only in a stream context.
4751 */
4752 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4753 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4754
4755 /* Converts the third argument in a sample. */
4756 hlua_lua2smp(L, 3, &smp);
4757
4758 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01004759 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004760 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004761 return 0;
4762}
4763
Christopher Faulet85d79c92016-11-09 16:54:56 +01004764__LJMP static int hlua_unset_var(lua_State *L)
4765{
4766 struct hlua_txn *htxn;
4767 const char *name;
4768 size_t len;
4769 struct sample smp;
4770
4771 MAY_LJMP(check_args(L, 2, "unset_var"));
4772
4773 /* It is useles to retrieve the stream, but this function
4774 * runs only in a stream context.
4775 */
4776 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4777 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4778
4779 /* Unset the variable. */
4780 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
4781 vars_unset_by_name(name, len, &smp);
4782 return 0;
4783}
4784
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004785__LJMP static int hlua_get_var(lua_State *L)
4786{
4787 struct hlua_txn *htxn;
4788 const char *name;
4789 size_t len;
4790 struct sample smp;
4791
4792 MAY_LJMP(check_args(L, 2, "get_var"));
4793
4794 /* It is useles to retrieve the stream, but this function
4795 * runs only in a stream context.
4796 */
4797 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4798 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4799
Willy Tarreau7560dd42016-03-10 16:28:58 +01004800 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004801 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004802 lua_pushnil(L);
4803 return 1;
4804 }
4805
4806 return hlua_smp2lua(L, &smp);
4807}
4808
Willy Tarreau59551662015-03-10 14:23:13 +01004809__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004810{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004811 struct hlua *hlua;
4812
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004813 MAY_LJMP(check_args(L, 2, "set_priv"));
4814
Willy Tarreau87b09662015-04-03 00:22:06 +02004815 /* It is useles to retrieve the stream, but this function
4816 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004817 */
4818 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004819 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004820
4821 /* Remove previous value. */
4822 if (hlua->Mref != -1)
4823 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
4824
4825 /* Get and store new value. */
4826 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4827 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4828
4829 return 0;
4830}
4831
Willy Tarreau59551662015-03-10 14:23:13 +01004832__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004833{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004834 struct hlua *hlua;
4835
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004836 MAY_LJMP(check_args(L, 1, "get_priv"));
4837
Willy Tarreau87b09662015-04-03 00:22:06 +02004838 /* It is useles to retrieve the stream, but this function
4839 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004840 */
4841 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004842 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004843
4844 /* Push configuration index in the stack. */
4845 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4846
4847 return 1;
4848}
4849
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004850/* Create stack entry containing a class TXN. This function
4851 * return 0 if the stack does not contains free slots,
4852 * otherwise it returns 1.
4853 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004854static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004855{
Willy Tarreaude491382015-04-06 11:04:28 +02004856 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004857
4858 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004859 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004860 return 0;
4861
4862 /* NOTE: The allocation never fails. The failure
4863 * throw an error, and the function never returns.
4864 * if the throw is not avalaible, the process is aborted.
4865 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004866 /* Create the object: obj[0] = userdata. */
4867 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004868 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004869 lua_rawseti(L, -2, 0);
4870
Willy Tarreaude491382015-04-06 11:04:28 +02004871 htxn->s = s;
4872 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004873 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004874 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004875
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004876 /* Create the "f" field that contains a list of fetches. */
4877 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004878 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004879 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004880 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004881
4882 /* Create the "sf" field that contains a list of stringsafe fetches. */
4883 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004884 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004885 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004886 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004887
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004888 /* Create the "c" field that contains a list of converters. */
4889 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004890 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004891 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004892 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004893
4894 /* Create the "sc" field that contains a list of stringsafe converters. */
4895 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004896 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004897 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004898 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004899
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004900 /* Create the "req" field that contains the request channel object. */
4901 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004902 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004903 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004904 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004905
4906 /* Create the "res" field that contains the response channel object. */
4907 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004908 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004909 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004910 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004911
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004912 /* Creates the HTTP object is the current proxy allows http. */
4913 lua_pushstring(L, "http");
4914 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02004915 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004916 return 0;
4917 }
4918 else
4919 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004920 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004921
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004922 /* Pop a class sesison metatable and affect it to the userdata. */
4923 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
4924 lua_setmetatable(L, -2);
4925
4926 return 1;
4927}
4928
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004929__LJMP static int hlua_txn_deflog(lua_State *L)
4930{
4931 const char *msg;
4932 struct hlua_txn *htxn;
4933
4934 MAY_LJMP(check_args(L, 2, "deflog"));
4935 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4936 msg = MAY_LJMP(luaL_checkstring(L, 2));
4937
4938 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
4939 return 0;
4940}
4941
4942__LJMP static int hlua_txn_log(lua_State *L)
4943{
4944 int level;
4945 const char *msg;
4946 struct hlua_txn *htxn;
4947
4948 MAY_LJMP(check_args(L, 3, "log"));
4949 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4950 level = MAY_LJMP(luaL_checkinteger(L, 2));
4951 msg = MAY_LJMP(luaL_checkstring(L, 3));
4952
4953 if (level < 0 || level >= NB_LOG_LEVELS)
4954 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4955
4956 hlua_sendlog(htxn->s->be, level, msg);
4957 return 0;
4958}
4959
4960__LJMP static int hlua_txn_log_debug(lua_State *L)
4961{
4962 const char *msg;
4963 struct hlua_txn *htxn;
4964
4965 MAY_LJMP(check_args(L, 2, "Debug"));
4966 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4967 msg = MAY_LJMP(luaL_checkstring(L, 2));
4968 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
4969 return 0;
4970}
4971
4972__LJMP static int hlua_txn_log_info(lua_State *L)
4973{
4974 const char *msg;
4975 struct hlua_txn *htxn;
4976
4977 MAY_LJMP(check_args(L, 2, "Info"));
4978 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4979 msg = MAY_LJMP(luaL_checkstring(L, 2));
4980 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
4981 return 0;
4982}
4983
4984__LJMP static int hlua_txn_log_warning(lua_State *L)
4985{
4986 const char *msg;
4987 struct hlua_txn *htxn;
4988
4989 MAY_LJMP(check_args(L, 2, "Warning"));
4990 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4991 msg = MAY_LJMP(luaL_checkstring(L, 2));
4992 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
4993 return 0;
4994}
4995
4996__LJMP static int hlua_txn_log_alert(lua_State *L)
4997{
4998 const char *msg;
4999 struct hlua_txn *htxn;
5000
5001 MAY_LJMP(check_args(L, 2, "Alert"));
5002 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5003 msg = MAY_LJMP(luaL_checkstring(L, 2));
5004 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5005 return 0;
5006}
5007
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005008__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5009{
5010 struct hlua_txn *htxn;
5011 int ll;
5012
5013 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5014 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5015 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5016
5017 if (ll < 0 || ll > 7)
5018 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5019
5020 htxn->s->logs.level = ll;
5021 return 0;
5022}
5023
5024__LJMP static int hlua_txn_set_tos(lua_State *L)
5025{
5026 struct hlua_txn *htxn;
5027 struct connection *cli_conn;
5028 int tos;
5029
5030 MAY_LJMP(check_args(L, 2, "set_tos"));
5031 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5032 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5033
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005034 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Vincent Bernat6e615892016-05-18 16:17:44 +02005035 inet_set_tos(cli_conn->t.sock.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005036
5037 return 0;
5038}
5039
5040__LJMP static int hlua_txn_set_mark(lua_State *L)
5041{
5042#ifdef SO_MARK
5043 struct hlua_txn *htxn;
5044 struct connection *cli_conn;
5045 int mark;
5046
5047 MAY_LJMP(check_args(L, 2, "set_mark"));
5048 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5049 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5050
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005051 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02005052 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005053#endif
5054 return 0;
5055}
5056
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005057/* This function is an Lua binding that send pending data
5058 * to the client, and close the stream interface.
5059 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005060__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005061{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005062 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005063 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005064 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005065
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005066 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005067 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005068 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005069
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005070 /* If the flags NOTERM is set, we cannot terminate the http
5071 * session, so we just end the execution of the current
5072 * lua code.
5073 */
5074 if (htxn->flags & HLUA_TXN_NOTERM) {
5075 WILL_LJMP(hlua_done(L));
5076 return 0;
5077 }
5078
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005079 ic = &htxn->s->req;
5080 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005081
Willy Tarreau630ef452015-08-28 10:06:15 +02005082 if (htxn->s->txn) {
5083 /* HTTP mode, let's stay in sync with the stream */
5084 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
5085 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5086 htxn->s->txn->req.sov = 0;
5087 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5088 oc->analysers = AN_RES_HTTP_XFER_BODY;
5089 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5090 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5091
Willy Tarreau630ef452015-08-28 10:06:15 +02005092 /* Note that if we want to support keep-alive, we need
5093 * to bypass the close/shutr_now calls below, but that
5094 * may only be done if the HTTP request was already
5095 * processed and the connection header is known (ie
5096 * not during TCP rules).
5097 */
5098 }
5099
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005100 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005101 channel_abort(ic);
5102 channel_auto_close(ic);
5103 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005104
5105 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005106 channel_auto_read(oc);
5107 channel_auto_close(oc);
5108 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005109
Willy Tarreau0458b082015-08-28 09:40:04 +02005110 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005111
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005112 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005113 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005114 return 0;
5115}
5116
5117__LJMP static int hlua_log(lua_State *L)
5118{
5119 int level;
5120 const char *msg;
5121
5122 MAY_LJMP(check_args(L, 2, "log"));
5123 level = MAY_LJMP(luaL_checkinteger(L, 1));
5124 msg = MAY_LJMP(luaL_checkstring(L, 2));
5125
5126 if (level < 0 || level >= NB_LOG_LEVELS)
5127 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5128
5129 hlua_sendlog(NULL, level, msg);
5130 return 0;
5131}
5132
5133__LJMP static int hlua_log_debug(lua_State *L)
5134{
5135 const char *msg;
5136
5137 MAY_LJMP(check_args(L, 1, "debug"));
5138 msg = MAY_LJMP(luaL_checkstring(L, 1));
5139 hlua_sendlog(NULL, LOG_DEBUG, msg);
5140 return 0;
5141}
5142
5143__LJMP static int hlua_log_info(lua_State *L)
5144{
5145 const char *msg;
5146
5147 MAY_LJMP(check_args(L, 1, "info"));
5148 msg = MAY_LJMP(luaL_checkstring(L, 1));
5149 hlua_sendlog(NULL, LOG_INFO, msg);
5150 return 0;
5151}
5152
5153__LJMP static int hlua_log_warning(lua_State *L)
5154{
5155 const char *msg;
5156
5157 MAY_LJMP(check_args(L, 1, "warning"));
5158 msg = MAY_LJMP(luaL_checkstring(L, 1));
5159 hlua_sendlog(NULL, LOG_WARNING, msg);
5160 return 0;
5161}
5162
5163__LJMP static int hlua_log_alert(lua_State *L)
5164{
5165 const char *msg;
5166
5167 MAY_LJMP(check_args(L, 1, "alert"));
5168 msg = MAY_LJMP(luaL_checkstring(L, 1));
5169 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005170 return 0;
5171}
5172
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005173__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005174{
5175 int wakeup_ms = lua_tointeger(L, -1);
5176 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005177 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005178 return 0;
5179}
5180
5181__LJMP static int hlua_sleep(lua_State *L)
5182{
5183 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005184 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005185
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005186 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005187
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005188 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005189 wakeup_ms = tick_add(now_ms, delay);
5190 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005191
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005192 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5193 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005194}
5195
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005196__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005197{
5198 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005199 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005200
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005201 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005202
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005203 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005204 wakeup_ms = tick_add(now_ms, delay);
5205 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005206
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005207 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5208 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005209}
5210
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005211/* This functionis an LUA binding. it permits to give back
5212 * the hand at the HAProxy scheduler. It is used when the
5213 * LUA processing consumes a lot of time.
5214 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005215__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005216{
5217 return 0;
5218}
5219
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005220__LJMP static int hlua_yield(lua_State *L)
5221{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005222 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5223 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005224}
5225
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005226/* This function change the nice of the currently executed
5227 * task. It is used set low or high priority at the current
5228 * task.
5229 */
Willy Tarreau59551662015-03-10 14:23:13 +01005230__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005231{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005232 struct hlua *hlua;
5233 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005234
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005235 MAY_LJMP(check_args(L, 1, "set_nice"));
5236 hlua = hlua_gethlua(L);
5237 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005238
5239 /* If he task is not set, I'm in a start mode. */
5240 if (!hlua || !hlua->task)
5241 return 0;
5242
5243 if (nice < -1024)
5244 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005245 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005246 nice = 1024;
5247
5248 hlua->task->nice = nice;
5249 return 0;
5250}
5251
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005252/* This function is used as a calback of a task. It is called by the
5253 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5254 * return an E_AGAIN signal, the emmiter of this signal must set a
5255 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005256 *
5257 * Task wrapper are longjmp safe because the only one Lua code
5258 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005259 */
5260static struct task *hlua_process_task(struct task *task)
5261{
5262 struct hlua *hlua = task->context;
5263 enum hlua_exec status;
5264
5265 /* We need to remove the task from the wait queue before executing
5266 * the Lua code because we don't know if it needs to wait for
5267 * another timer or not in the case of E_AGAIN.
5268 */
5269 task_delete(task);
5270
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005271 /* If it is the first call to the task, we must initialize the
5272 * execution timeouts.
5273 */
5274 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005275 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005276
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005277 /* Execute the Lua code. */
5278 status = hlua_ctx_resume(hlua, 1);
5279
5280 switch (status) {
5281 /* finished or yield */
5282 case HLUA_E_OK:
5283 hlua_ctx_destroy(hlua);
5284 task_delete(task);
5285 task_free(task);
5286 break;
5287
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005288 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5289 if (hlua->wake_time != TICK_ETERNITY)
5290 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005291 break;
5292
5293 /* finished with error. */
5294 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005295 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005296 hlua_ctx_destroy(hlua);
5297 task_delete(task);
5298 task_free(task);
5299 break;
5300
5301 case HLUA_E_ERR:
5302 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005303 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005304 hlua_ctx_destroy(hlua);
5305 task_delete(task);
5306 task_free(task);
5307 break;
5308 }
5309 return NULL;
5310}
5311
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005312/* This function is an LUA binding that register LUA function to be
5313 * executed after the HAProxy configuration parsing and before the
5314 * HAProxy scheduler starts. This function expect only one LUA
5315 * argument that is a function. This function returns nothing, but
5316 * throws if an error is encountered.
5317 */
5318__LJMP static int hlua_register_init(lua_State *L)
5319{
5320 struct hlua_init_function *init;
5321 int ref;
5322
5323 MAY_LJMP(check_args(L, 1, "register_init"));
5324
5325 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5326
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005327 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005328 if (!init)
5329 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5330
5331 init->function_ref = ref;
5332 LIST_ADDQ(&hlua_init_functions, &init->l);
5333 return 0;
5334}
5335
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005336/* This functio is an LUA binding. It permits to register a task
5337 * executed in parallel of the main HAroxy activity. The task is
5338 * created and it is set in the HAProxy scheduler. It can be called
5339 * from the "init" section, "post init" or during the runtime.
5340 *
5341 * Lua prototype:
5342 *
5343 * <none> core.register_task(<function>)
5344 */
5345static int hlua_register_task(lua_State *L)
5346{
5347 struct hlua *hlua;
5348 struct task *task;
5349 int ref;
5350
5351 MAY_LJMP(check_args(L, 1, "register_task"));
5352
5353 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5354
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005355 hlua = calloc(1, sizeof(*hlua));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005356 if (!hlua)
5357 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5358
5359 task = task_new();
5360 task->context = hlua;
5361 task->process = hlua_process_task;
5362
5363 if (!hlua_ctx_init(hlua, task))
5364 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5365
5366 /* Restore the function in the stack. */
5367 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5368 hlua->nargs = 0;
5369
5370 /* Schedule task. */
5371 task_schedule(task, now_ms);
5372
5373 return 0;
5374}
5375
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005376/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5377 * doesn't allow "yield" functions because the HAProxy engine cannot
5378 * resume converters.
5379 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005380static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005381{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005382 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005383 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005384 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005385
Willy Tarreaube508f12016-03-10 11:47:01 +01005386 if (!stream)
5387 return 0;
5388
Willy Tarreau87b09662015-04-03 00:22:06 +02005389 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005390 * Lua context can be not initialized. This behavior
5391 * permits to save performances because a systematic
5392 * Lua initialization cause 5% performances loss.
5393 */
Willy Tarreau87b09662015-04-03 00:22:06 +02005394 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005395 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005396 return 0;
5397 }
5398
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005399 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005400 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005401
5402 /* The following Lua calls can fail. */
5403 if (!SET_SAFE_LJMP(stream->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005404 if (lua_type(stream->hlua.T, -1) == LUA_TSTRING)
5405 error = lua_tostring(stream->hlua.T, -1);
5406 else
5407 error = "critical error";
5408 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005409 return 0;
5410 }
5411
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005412 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005413 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005414 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005415 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005416 return 0;
5417 }
5418
5419 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005420 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005421
5422 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005423 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005424 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005425 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005426 return 0;
5427 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005428 hlua_smp2lua(stream->hlua.T, smp);
Thierry Fournier4a53bfd2016-05-27 16:35:01 +02005429 stream->hlua.nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005430
5431 /* push keywords in the stack. */
5432 if (arg_p) {
5433 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02005434 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005435 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005436 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005437 return 0;
5438 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005439 hlua_arg2lua(stream->hlua.T, arg_p);
5440 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005441 }
5442 }
5443
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005444 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005445 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005446
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005447 /* At this point the execution is safe. */
5448 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005449 }
5450
5451 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005452 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005453 /* finished. */
5454 case HLUA_E_OK:
5455 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005456 hlua_lua2smp(stream->hlua.T, -1, smp);
5457 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005458 return 1;
5459
5460 /* yield. */
5461 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005462 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005463 return 0;
5464
5465 /* finished with error. */
5466 case HLUA_E_ERRMSG:
5467 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005468 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
5469 fcn->name, lua_tostring(stream->hlua.T, -1));
Willy Tarreau87b09662015-04-03 00:22:06 +02005470 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005471 return 0;
5472
5473 case HLUA_E_ERR:
5474 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005475 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005476
5477 default:
5478 return 0;
5479 }
5480}
5481
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005482/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5483 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005484 * resume sample-fetches. This function will be called by the sample
5485 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005486 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005487static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5488 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005489{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005490 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005491 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005492 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005493 const struct chunk msg = { .len = 0 };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005494
Willy Tarreaube508f12016-03-10 11:47:01 +01005495 if (!stream)
5496 return 0;
5497
Willy Tarreau87b09662015-04-03 00:22:06 +02005498 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005499 * Lua context can be not initialized. This behavior
5500 * permits to save performances because a systematic
5501 * Lua initialization cause 5% performances loss.
5502 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005503 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005504 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005505 return 0;
5506 }
5507
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005508 consistency_set(stream, smp->opt, &stream->hlua.cons);
5509
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005510 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005511 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005512
5513 /* The following Lua calls can fail. */
5514 if (!SET_SAFE_LJMP(stream->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005515 if (lua_type(stream->hlua.T, -1) == LUA_TSTRING)
5516 error = lua_tostring(stream->hlua.T, -1);
5517 else
5518 error = "critical error";
5519 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005520 return 0;
5521 }
5522
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005523 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005524 if (!lua_checkstack(stream->hlua.T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005525 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005526 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005527 return 0;
5528 }
5529
5530 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005531 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005532
5533 /* push arguments in the stack. */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005534 if (!hlua_txn_new(stream->hlua.T, stream, smp->px, smp->opt & SMP_OPT_DIR,
5535 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005536 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005537 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005538 return 0;
5539 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005540 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005541
5542 /* push keywords in the stack. */
5543 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5544 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005545 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005546 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005547 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005548 return 0;
5549 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005550 hlua_arg2lua(stream->hlua.T, arg_p);
5551 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005552 }
5553
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005554 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005555 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005556
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005557 /* At this point the execution is safe. */
5558 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005559 }
5560
5561 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005562 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005563 /* finished. */
5564 case HLUA_E_OK:
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005565 if (!consistency_check(stream, smp->opt, &stream->hlua.cons)) {
5566 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005567 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005568 }
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005569 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005570 hlua_lua2smp(stream->hlua.T, -1, smp);
5571 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005572
5573 /* Set the end of execution flag. */
5574 smp->flags &= ~SMP_F_MAY_CHANGE;
5575 return 1;
5576
5577 /* yield. */
5578 case HLUA_E_AGAIN:
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005579 if (!consistency_check(stream, smp->opt, &stream->hlua.cons))
5580 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005581 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005582 return 0;
5583
5584 /* finished with error. */
5585 case HLUA_E_ERRMSG:
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005586 if (!consistency_check(stream, smp->opt, &stream->hlua.cons))
5587 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005588 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005589 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
5590 fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005591 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005592 return 0;
5593
5594 case HLUA_E_ERR:
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005595 if (!consistency_check(stream, smp->opt, &stream->hlua.cons))
5596 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005597 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005598 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005599
5600 default:
5601 return 0;
5602 }
5603}
5604
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005605/* This function is an LUA binding used for registering
5606 * "sample-conv" functions. It expects a converter name used
5607 * in the haproxy configuration file, and an LUA function.
5608 */
5609__LJMP static int hlua_register_converters(lua_State *L)
5610{
5611 struct sample_conv_kw_list *sck;
5612 const char *name;
5613 int ref;
5614 int len;
5615 struct hlua_function *fcn;
5616
5617 MAY_LJMP(check_args(L, 2, "register_converters"));
5618
5619 /* First argument : converter name. */
5620 name = MAY_LJMP(luaL_checkstring(L, 1));
5621
5622 /* Second argument : lua function. */
5623 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5624
5625 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005626 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005627 if (!sck)
5628 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005629 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005630 if (!fcn)
5631 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5632
5633 /* Fill fcn. */
5634 fcn->name = strdup(name);
5635 if (!fcn->name)
5636 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5637 fcn->function_ref = ref;
5638
5639 /* List head */
5640 sck->list.n = sck->list.p = NULL;
5641
5642 /* converter keyword. */
5643 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005644 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005645 if (!sck->kw[0].kw)
5646 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5647
5648 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5649 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005650 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 +01005651 sck->kw[0].val_args = NULL;
5652 sck->kw[0].in_type = SMP_T_STR;
5653 sck->kw[0].out_type = SMP_T_STR;
5654 sck->kw[0].private = fcn;
5655
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005656 /* Register this new converter */
5657 sample_register_convs(sck);
5658
5659 return 0;
5660}
5661
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005662/* This fucntion is an LUA binding used for registering
5663 * "sample-fetch" functions. It expects a converter name used
5664 * in the haproxy configuration file, and an LUA function.
5665 */
5666__LJMP static int hlua_register_fetches(lua_State *L)
5667{
5668 const char *name;
5669 int ref;
5670 int len;
5671 struct sample_fetch_kw_list *sfk;
5672 struct hlua_function *fcn;
5673
5674 MAY_LJMP(check_args(L, 2, "register_fetches"));
5675
5676 /* First argument : sample-fetch name. */
5677 name = MAY_LJMP(luaL_checkstring(L, 1));
5678
5679 /* Second argument : lua function. */
5680 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5681
5682 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005683 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005684 if (!sfk)
5685 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005686 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005687 if (!fcn)
5688 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5689
5690 /* Fill fcn. */
5691 fcn->name = strdup(name);
5692 if (!fcn->name)
5693 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5694 fcn->function_ref = ref;
5695
5696 /* List head */
5697 sfk->list.n = sfk->list.p = NULL;
5698
5699 /* sample-fetch keyword. */
5700 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005701 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005702 if (!sfk->kw[0].kw)
5703 return luaL_error(L, "lua out of memory error.");
5704
5705 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5706 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005707 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 +01005708 sfk->kw[0].val_args = NULL;
5709 sfk->kw[0].out_type = SMP_T_STR;
5710 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5711 sfk->kw[0].val = 0;
5712 sfk->kw[0].private = fcn;
5713
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005714 /* Register this new fetch. */
5715 sample_register_fetches(sfk);
5716
5717 return 0;
5718}
5719
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005720/* This function is a wrapper to execute each LUA function declared
5721 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005722 * return ACT_RET_CONT if the processing is finished (with or without
5723 * error) and return ACT_RET_YIELD if the function must be called again
5724 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005725 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005726static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005727 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005728{
5729 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005730 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005731 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005732 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005733 const struct chunk msg = { .len = 0 };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005734
5735 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01005736 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
5737 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
5738 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
5739 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005740 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005741 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005742 return ACT_RET_CONT;
5743 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005744
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005745 consistency_set(s, dir, &s->hlua.cons);
5746
Willy Tarreau87b09662015-04-03 00:22:06 +02005747 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005748 * Lua context can be not initialized. This behavior
5749 * permits to save performances because a systematic
5750 * Lua initialization cause 5% performances loss.
5751 */
5752 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005753 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005754 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005755 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005756 }
5757
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005758 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01005759 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005760
5761 /* The following Lua calls can fail. */
5762 if (!SET_SAFE_LJMP(s->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005763 if (lua_type(s->hlua.T, -1) == LUA_TSTRING)
5764 error = lua_tostring(s->hlua.T, -1);
5765 else
5766 error = "critical error";
5767 SEND_ERR(px, "Lua function '%s': %s.\n",
5768 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005769 return ACT_RET_CONT;
5770 }
5771
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005772 /* Check stack available size. */
5773 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005774 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005775 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005776 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005777 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005778 }
5779
5780 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005781 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005782
Willy Tarreau87b09662015-04-03 00:22:06 +02005783 /* Create and and push object stream in the stack. */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005784 if (!hlua_txn_new(s->hlua.T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005785 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005786 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005787 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005788 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005789 }
5790 s->hlua.nargs = 1;
5791
5792 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005793 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005794 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005795 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005796 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005797 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005798 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005799 }
5800 lua_pushstring(s->hlua.T, *arg);
5801 s->hlua.nargs++;
5802 }
5803
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005804 /* Now the execution is safe. */
5805 RESET_SAFE_LJMP(s->hlua.T);
5806
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005807 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005808 s->hlua.max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005809 }
5810
5811 /* Execute the function. */
Willy Tarreau528192d2015-09-27 10:48:01 +02005812 switch (hlua_ctx_resume(&s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005813 /* finished. */
5814 case HLUA_E_OK:
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005815 if (!consistency_check(s, dir, &s->hlua.cons)) {
5816 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005817 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005818 }
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005819 if (s->hlua.flags & HLUA_STOP)
5820 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005821 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005822
5823 /* yield. */
5824 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005825 /* Set timeout in the required channel. */
5826 if (s->hlua.wake_time != TICK_ETERNITY) {
5827 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005828 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005829 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005830 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005831 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005832 /* Some actions can be wake up when a "write" event
5833 * is detected on a response channel. This is useful
5834 * only for actions targetted on the requests.
5835 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01005836 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005837 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005838 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005839 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005840 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01005841 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005842 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005843 /* We can quit the fcuntion without consistency check
5844 * because HAProxy is not able to manipulate data, it
5845 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005846 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005847
5848 /* finished with error. */
5849 case HLUA_E_ERRMSG:
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005850 if (!consistency_check(s, dir, &s->hlua.cons)) {
5851 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005852 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005853 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005854 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005855 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005856 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005857 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005858 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005859
5860 case HLUA_E_ERR:
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005861 if (!consistency_check(s, dir, &s->hlua.cons)) {
5862 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005863 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005864 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005865 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005866 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005867 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005868
5869 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005870 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005871 }
5872}
5873
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005874struct task *hlua_applet_wakeup(struct task *t)
5875{
5876 struct appctx *ctx = t->context;
5877 struct stream_interface *si = ctx->owner;
5878
5879 /* If the applet is wake up without any expected work, the sheduler
5880 * remove it from the run queue. This flag indicate that the applet
5881 * is waiting for write. If the buffer is full, the main processing
5882 * will send some data and after call the applet, otherwise it call
5883 * the applet ASAP.
5884 */
5885 si_applet_cant_put(si);
5886 appctx_wakeup(ctx);
5887 return NULL;
5888}
5889
5890static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5891{
5892 struct stream_interface *si = ctx->owner;
5893 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5894 struct task *task;
5895 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005896 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005897
5898 HLUA_INIT(hlua);
5899 ctx->ctx.hlua_apptcp.flags = 0;
5900
5901 /* Create task used by signal to wakeup applets. */
5902 task = task_new();
5903 if (!task) {
5904 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5905 ctx->rule->arg.hlua_rule->fcn.name);
5906 return 0;
5907 }
5908 task->nice = 0;
5909 task->context = ctx;
5910 task->process = hlua_applet_wakeup;
5911 ctx->ctx.hlua_apptcp.task = task;
5912
5913 /* In the execution wrappers linked with a stream, the
5914 * Lua context can be not initialized. This behavior
5915 * permits to save performances because a systematic
5916 * Lua initialization cause 5% performances loss.
5917 */
5918 if (!hlua_ctx_init(hlua, task)) {
5919 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
5920 ctx->rule->arg.hlua_rule->fcn.name);
5921 return 0;
5922 }
5923
5924 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005925 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005926
5927 /* The following Lua calls can fail. */
5928 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005929 if (lua_type(hlua->T, -1) == LUA_TSTRING)
5930 error = lua_tostring(hlua->T, -1);
5931 else
5932 error = "critical error";
5933 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
5934 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005935 RESET_SAFE_LJMP(hlua->T);
5936 return 0;
5937 }
5938
5939 /* Check stack available size. */
5940 if (!lua_checkstack(hlua->T, 1)) {
5941 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5942 ctx->rule->arg.hlua_rule->fcn.name);
5943 RESET_SAFE_LJMP(hlua->T);
5944 return 0;
5945 }
5946
5947 /* Restore the function in the stack. */
5948 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5949
5950 /* Create and and push object stream in the stack. */
5951 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
5952 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5953 ctx->rule->arg.hlua_rule->fcn.name);
5954 RESET_SAFE_LJMP(hlua->T);
5955 return 0;
5956 }
5957 hlua->nargs = 1;
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 tcp '%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 ASAP. */
5974 si_applet_cant_get(si);
5975 si_applet_cant_put(si);
5976
5977 return 1;
5978}
5979
5980static void hlua_applet_tcp_fct(struct appctx *ctx)
5981{
5982 struct stream_interface *si = ctx->owner;
5983 struct stream *strm = si_strm(si);
5984 struct channel *res = si_ic(si);
5985 struct act_rule *rule = ctx->rule;
5986 struct proxy *px = strm->be;
5987 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5988
5989 /* The applet execution is already done. */
5990 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
5991 return;
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 /* Execute the function. */
5998 switch (hlua_ctx_resume(hlua, 1)) {
5999 /* finished. */
6000 case HLUA_E_OK:
6001 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6002
6003 /* log time */
6004 strm->logs.tv_request = now;
6005
6006 /* eat the whole request */
6007 bo_skip(si_oc(si), si_ob(si)->o);
6008 res->flags |= CF_READ_NULL;
6009 si_shutr(si);
6010 return;
6011
6012 /* yield. */
6013 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006014 if (hlua->wake_time != TICK_ETERNITY)
6015 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006016 return;
6017
6018 /* finished with error. */
6019 case HLUA_E_ERRMSG:
6020 /* Display log. */
6021 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6022 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6023 lua_pop(hlua->T, 1);
6024 goto error;
6025
6026 case HLUA_E_ERR:
6027 /* Display log. */
6028 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6029 rule->arg.hlua_rule->fcn.name);
6030 goto error;
6031
6032 default:
6033 goto error;
6034 }
6035
6036error:
6037
6038 /* For all other cases, just close the stream. */
6039 si_shutw(si);
6040 si_shutr(si);
6041 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6042}
6043
6044static void hlua_applet_tcp_release(struct appctx *ctx)
6045{
6046 task_free(ctx->ctx.hlua_apptcp.task);
6047 ctx->ctx.hlua_apptcp.task = NULL;
6048 hlua_ctx_destroy(&ctx->ctx.hlua_apptcp.hlua);
6049}
6050
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006051/* The function returns 1 if the initialisation is complete, 0 if
6052 * an errors occurs and -1 if more data are required for initializing
6053 * the applet.
6054 */
6055static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6056{
6057 struct stream_interface *si = ctx->owner;
6058 struct channel *req = si_oc(si);
6059 struct http_msg *msg;
6060 struct http_txn *txn;
6061 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
6062 char **arg;
6063 struct hdr_ctx hdr;
6064 struct task *task;
6065 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006066 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006067
6068 /* Wait for a full HTTP request. */
6069 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6070 if (smp.flags & SMP_F_MAY_CHANGE)
6071 return -1;
6072 return 0;
6073 }
6074 txn = strm->txn;
6075 msg = &txn->req;
6076
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006077 /* We want two things in HTTP mode :
6078 * - enforce server-close mode if we were in keep-alive, so that the
6079 * applet is released after each response ;
6080 * - enable request body transfer to the applet in order to resync
6081 * with the response body.
6082 */
6083 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6084 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006085
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006086 HLUA_INIT(hlua);
6087 ctx->ctx.hlua_apphttp.left_bytes = -1;
6088 ctx->ctx.hlua_apphttp.flags = 0;
6089
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006090 if (txn->req.flags & HTTP_MSGF_VER_11)
6091 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6092
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006093 /* Create task used by signal to wakeup applets. */
6094 task = task_new();
6095 if (!task) {
6096 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6097 ctx->rule->arg.hlua_rule->fcn.name);
6098 return 0;
6099 }
6100 task->nice = 0;
6101 task->context = ctx;
6102 task->process = hlua_applet_wakeup;
6103 ctx->ctx.hlua_apphttp.task = task;
6104
6105 /* In the execution wrappers linked with a stream, the
6106 * Lua context can be not initialized. This behavior
6107 * permits to save performances because a systematic
6108 * Lua initialization cause 5% performances loss.
6109 */
6110 if (!hlua_ctx_init(hlua, task)) {
6111 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6112 ctx->rule->arg.hlua_rule->fcn.name);
6113 return 0;
6114 }
6115
6116 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006117 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006118
6119 /* The following Lua calls can fail. */
6120 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006121 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6122 error = lua_tostring(hlua->T, -1);
6123 else
6124 error = "critical error";
6125 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6126 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006127 return 0;
6128 }
6129
6130 /* Check stack available size. */
6131 if (!lua_checkstack(hlua->T, 1)) {
6132 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6133 ctx->rule->arg.hlua_rule->fcn.name);
6134 RESET_SAFE_LJMP(hlua->T);
6135 return 0;
6136 }
6137
6138 /* Restore the function in the stack. */
6139 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6140
6141 /* Create and and push object stream in the stack. */
6142 if (!hlua_applet_http_new(hlua->T, ctx)) {
6143 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6144 ctx->rule->arg.hlua_rule->fcn.name);
6145 RESET_SAFE_LJMP(hlua->T);
6146 return 0;
6147 }
6148 hlua->nargs = 1;
6149
6150 /* Look for a 100-continue expected. */
6151 if (msg->flags & HTTP_MSGF_VER_11) {
6152 hdr.idx = 0;
6153 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
6154 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6155 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6156 }
6157
6158 /* push keywords in the stack. */
6159 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6160 if (!lua_checkstack(hlua->T, 1)) {
6161 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6162 ctx->rule->arg.hlua_rule->fcn.name);
6163 RESET_SAFE_LJMP(hlua->T);
6164 return 0;
6165 }
6166 lua_pushstring(hlua->T, *arg);
6167 hlua->nargs++;
6168 }
6169
6170 RESET_SAFE_LJMP(hlua->T);
6171
6172 /* Wakeup the applet when data is ready for read. */
6173 si_applet_cant_get(si);
6174
6175 return 1;
6176}
6177
6178static void hlua_applet_http_fct(struct appctx *ctx)
6179{
6180 struct stream_interface *si = ctx->owner;
6181 struct stream *strm = si_strm(si);
6182 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006183 struct act_rule *rule = ctx->rule;
6184 struct proxy *px = strm->be;
6185 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
6186 char *blk1;
6187 int len1;
6188 char *blk2;
6189 int len2;
6190 int ret;
6191
6192 /* If the stream is disconnect or closed, ldo nothing. */
6193 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6194 return;
6195
6196 /* Set the currently running flag. */
6197 if (!HLUA_IS_RUNNING(hlua) &&
6198 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6199
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006200 /* Wait for full HTTP analysys. */
6201 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6202 si_applet_cant_get(si);
6203 return;
6204 }
6205
6206 /* Store the max amount of bytes that we can read. */
6207 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6208
6209 /* We need to flush the request header. This left the body
6210 * for the Lua.
6211 */
6212
6213 /* Read the maximum amount of data avalaible. */
6214 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
6215 if (ret == -1)
6216 return;
6217
6218 /* No data available, ask for more data. */
6219 if (ret == 1)
6220 len2 = 0;
6221 if (ret == 0)
6222 len1 = 0;
6223 if (len1 + len2 < strm->txn->req.eoh + 2) {
6224 si_applet_cant_get(si);
6225 return;
6226 }
6227
6228 /* skip the requests bytes. */
6229 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
6230 }
6231
6232 /* Executes The applet if it is not done. */
6233 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6234
6235 /* Execute the function. */
6236 switch (hlua_ctx_resume(hlua, 1)) {
6237 /* finished. */
6238 case HLUA_E_OK:
6239 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6240 break;
6241
6242 /* yield. */
6243 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006244 if (hlua->wake_time != TICK_ETERNITY)
6245 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006246 return;
6247
6248 /* finished with error. */
6249 case HLUA_E_ERRMSG:
6250 /* Display log. */
6251 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6252 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6253 lua_pop(hlua->T, 1);
6254 goto error;
6255
6256 case HLUA_E_ERR:
6257 /* Display log. */
6258 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6259 rule->arg.hlua_rule->fcn.name);
6260 goto error;
6261
6262 default:
6263 goto error;
6264 }
6265 }
6266
6267 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6268
6269 /* We must send the final chunk. */
6270 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6271 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6272
6273 /* sent last chunk at once. */
6274 ret = bi_putblk(res, "0\r\n\r\n", 5);
6275
6276 /* critical error. */
6277 if (ret == -2 || ret == -3) {
6278 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6279 rule->arg.hlua_rule->fcn.name);
6280 goto error;
6281 }
6282
6283 /* no enough space error. */
6284 if (ret == -1) {
6285 si_applet_cant_put(si);
6286 return;
6287 }
6288
6289 /* set the last chunk sent. */
6290 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6291 }
6292
6293 /* close the connection. */
6294
6295 /* status / log */
6296 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6297 strm->logs.tv_request = now;
6298
6299 /* eat the whole request */
6300 bo_skip(si_oc(si), si_ob(si)->o);
6301 res->flags |= CF_READ_NULL;
6302 si_shutr(si);
6303
6304 return;
6305 }
6306
6307error:
6308
6309 /* If we are in HTTP mode, and we are not send any
6310 * data, return a 500 server error in best effort:
6311 * if there are no room avalaible in the buffer,
6312 * just close the connection.
6313 */
6314 bi_putblk(res, error_500, strlen(error_500));
6315 if (!(strm->flags & SF_ERR_MASK))
6316 strm->flags |= SF_ERR_RESOURCE;
6317 si_shutw(si);
6318 si_shutr(si);
6319 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6320}
6321
6322static void hlua_applet_http_release(struct appctx *ctx)
6323{
6324 task_free(ctx->ctx.hlua_apphttp.task);
6325 ctx->ctx.hlua_apphttp.task = NULL;
6326 hlua_ctx_destroy(&ctx->ctx.hlua_apphttp.hlua);
6327}
6328
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006329/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6330 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006331 *
6332 * This function can fail with an abort() due to an Lua critical error.
6333 * We are in the configuration parsing process of HAProxy, this abort() is
6334 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006335 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006336static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6337 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006338{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006339 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006340 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006341
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006342 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006343 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006344 if (!rule->arg.hlua_rule) {
6345 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006346 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006347 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006348
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006349 /* Memory for arguments. */
6350 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6351 if (!rule->arg.hlua_rule->args) {
6352 memprintf(err, "out of memory error");
6353 return ACT_RET_PRS_ERR;
6354 }
6355
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006356 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006357 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006358
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006359 /* Expect some arguments */
6360 for (i = 0; i < fcn->nargs; i++) {
6361 if (*args[i+1] == '\0') {
6362 memprintf(err, "expect %d arguments", fcn->nargs);
6363 return ACT_RET_PRS_ERR;
6364 }
6365 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6366 if (!rule->arg.hlua_rule->args[i]) {
6367 memprintf(err, "out of memory error");
6368 return ACT_RET_PRS_ERR;
6369 }
6370 (*cur_arg)++;
6371 }
6372 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006373
Thierry FOURNIER42148732015-09-02 17:17:33 +02006374 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006375 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006376 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006377}
6378
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006379static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6380 struct act_rule *rule, char **err)
6381{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006382 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006383
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006384 /* HTTP applets are forbidden in tcp-request rules.
6385 * HTTP applet request requires everything initilized by
6386 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6387 * The applet will be immediately initilized, but its before
6388 * the call of this analyzer.
6389 */
6390 if (rule->from != ACT_F_HTTP_REQ) {
6391 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6392 return ACT_RET_PRS_ERR;
6393 }
6394
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006395 /* Memory for the rule. */
6396 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6397 if (!rule->arg.hlua_rule) {
6398 memprintf(err, "out of memory error");
6399 return ACT_RET_PRS_ERR;
6400 }
6401
6402 /* Reference the Lua function and store the reference. */
6403 rule->arg.hlua_rule->fcn = *fcn;
6404
6405 /* TODO: later accept arguments. */
6406 rule->arg.hlua_rule->args = NULL;
6407
6408 /* Add applet pointer in the rule. */
6409 rule->applet.obj_type = OBJ_TYPE_APPLET;
6410 rule->applet.name = fcn->name;
6411 rule->applet.init = hlua_applet_http_init;
6412 rule->applet.fct = hlua_applet_http_fct;
6413 rule->applet.release = hlua_applet_http_release;
6414 rule->applet.timeout = hlua_timeout_applet;
6415
6416 return ACT_RET_PRS_OK;
6417}
6418
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006419/* This function is an LUA binding used for registering
6420 * "sample-conv" functions. It expects a converter name used
6421 * in the haproxy configuration file, and an LUA function.
6422 */
6423__LJMP static int hlua_register_action(lua_State *L)
6424{
6425 struct action_kw_list *akl;
6426 const char *name;
6427 int ref;
6428 int len;
6429 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006430 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006431
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006432 /* Initialise the number of expected arguments at 0. */
6433 nargs = 0;
6434
6435 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6436 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006437
6438 /* First argument : converter name. */
6439 name = MAY_LJMP(luaL_checkstring(L, 1));
6440
6441 /* Second argument : environment. */
6442 if (lua_type(L, 2) != LUA_TTABLE)
6443 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6444
6445 /* Third argument : lua function. */
6446 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6447
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006448 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6449 if (lua_gettop(L) >= 4)
6450 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6451
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006452 /* browse the second argulent as an array. */
6453 lua_pushnil(L);
6454 while (lua_next(L, 2) != 0) {
6455 if (lua_type(L, -1) != LUA_TSTRING)
6456 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6457
6458 /* Check required environment. Only accepted "http" or "tcp". */
6459 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006460 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006461 if (!akl)
6462 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006463 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006464 if (!fcn)
6465 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6466
6467 /* Fill fcn. */
6468 fcn->name = strdup(name);
6469 if (!fcn->name)
6470 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6471 fcn->function_ref = ref;
6472
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006473 /* Set the expected number od arguments. */
6474 fcn->nargs = nargs;
6475
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006476 /* List head */
6477 akl->list.n = akl->list.p = NULL;
6478
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006479 /* action keyword. */
6480 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006481 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006482 if (!akl->kw[0].kw)
6483 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6484
6485 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6486
6487 akl->kw[0].match_pfx = 0;
6488 akl->kw[0].private = fcn;
6489 akl->kw[0].parse = action_register_lua;
6490
6491 /* select the action registering point. */
6492 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6493 tcp_req_cont_keywords_register(akl);
6494 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6495 tcp_res_cont_keywords_register(akl);
6496 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6497 http_req_keywords_register(akl);
6498 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6499 http_res_keywords_register(akl);
6500 else
6501 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6502 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6503 "are expected.", lua_tostring(L, -1)));
6504
6505 /* pop the environment string. */
6506 lua_pop(L, 1);
6507 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006508 return ACT_RET_PRS_OK;
6509}
6510
6511static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6512 struct act_rule *rule, char **err)
6513{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006514 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006515
6516 /* Memory for the rule. */
6517 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6518 if (!rule->arg.hlua_rule) {
6519 memprintf(err, "out of memory error");
6520 return ACT_RET_PRS_ERR;
6521 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006522
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006523 /* Reference the Lua function and store the reference. */
6524 rule->arg.hlua_rule->fcn = *fcn;
6525
6526 /* TODO: later accept arguments. */
6527 rule->arg.hlua_rule->args = NULL;
6528
6529 /* Add applet pointer in the rule. */
6530 rule->applet.obj_type = OBJ_TYPE_APPLET;
6531 rule->applet.name = fcn->name;
6532 rule->applet.init = hlua_applet_tcp_init;
6533 rule->applet.fct = hlua_applet_tcp_fct;
6534 rule->applet.release = hlua_applet_tcp_release;
6535 rule->applet.timeout = hlua_timeout_applet;
6536
6537 return 0;
6538}
6539
6540/* This function is an LUA binding used for registering
6541 * "sample-conv" functions. It expects a converter name used
6542 * in the haproxy configuration file, and an LUA function.
6543 */
6544__LJMP static int hlua_register_service(lua_State *L)
6545{
6546 struct action_kw_list *akl;
6547 const char *name;
6548 const char *env;
6549 int ref;
6550 int len;
6551 struct hlua_function *fcn;
6552
6553 MAY_LJMP(check_args(L, 3, "register_service"));
6554
6555 /* First argument : converter name. */
6556 name = MAY_LJMP(luaL_checkstring(L, 1));
6557
6558 /* Second argument : environment. */
6559 env = MAY_LJMP(luaL_checkstring(L, 2));
6560
6561 /* Third argument : lua function. */
6562 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6563
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006564 /* Allocate and fill the sample fetch keyword struct. */
6565 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6566 if (!akl)
6567 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6568 fcn = calloc(1, sizeof(*fcn));
6569 if (!fcn)
6570 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6571
6572 /* Fill fcn. */
6573 len = strlen("<lua.>") + strlen(name) + 1;
6574 fcn->name = calloc(1, len);
6575 if (!fcn->name)
6576 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6577 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6578 fcn->function_ref = ref;
6579
6580 /* List head */
6581 akl->list.n = akl->list.p = NULL;
6582
6583 /* converter keyword. */
6584 len = strlen("lua.") + strlen(name) + 1;
6585 akl->kw[0].kw = calloc(1, len);
6586 if (!akl->kw[0].kw)
6587 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6588
6589 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6590
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01006591 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006592 if (strcmp(env, "tcp") == 0)
6593 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006594 else if (strcmp(env, "http") == 0)
6595 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006596 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006597 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6598 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006599
6600 akl->kw[0].match_pfx = 0;
6601 akl->kw[0].private = fcn;
6602
6603 /* End of array. */
6604 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6605
6606 /* Register this new converter */
6607 service_keywords_register(akl);
6608
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006609 return 0;
6610}
6611
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006612/* This function initialises Lua cli handler. It copies the
6613 * arguments in the Lua stack and create channel IO objects.
6614 */
6615static int hlua_cli_parse_fct(char **args, struct appctx *appctx, void *private)
6616{
6617 struct hlua *hlua;
6618 struct hlua_function *fcn;
6619 int i;
6620 const char *error;
6621
6622 hlua = &appctx->ctx.hlua_cli.hlua;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01006623 appctx->ctx.hlua_cli.fcn = private;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006624 fcn = private;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006625
6626 /* Create task used by signal to wakeup applets.
6627 * We use the same wakeup fonction than the Lua applet_tcp and
6628 * applet_http. It is absolutely compatible.
6629 */
6630 appctx->ctx.hlua_cli.task = task_new();
6631 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01006632 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006633 return 0;
6634 }
6635 appctx->ctx.hlua_cli.task->nice = 0;
6636 appctx->ctx.hlua_cli.task->context = appctx;
6637 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
6638
6639 /* Initialises the Lua context */
6640 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
6641 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
6642 return 1;
6643 }
6644
6645 /* The following Lua calls can fail. */
6646 if (!SET_SAFE_LJMP(hlua->T)) {
6647 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6648 error = lua_tostring(hlua->T, -1);
6649 else
6650 error = "critical error";
6651 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
6652 goto error;
6653 }
6654
6655 /* Check stack available size. */
6656 if (!lua_checkstack(hlua->T, 2)) {
6657 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6658 goto error;
6659 }
6660
6661 /* Restore the function in the stack. */
6662 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
6663
6664 /* Once the arguments parsed, the CLI is like an AppletTCP,
6665 * so push AppletTCP in the stack.
6666 * TODO: get_priv() and set_priv() are useless. Maybe we will
6667 * create a new object without these two functions.
6668 */
6669 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
6670 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6671 goto error;
6672 }
6673 hlua->nargs = 1;
6674
6675 /* push keywords in the stack. */
6676 for (i = 0; *args[i]; i++) {
6677 /* Check stack available size. */
6678 if (!lua_checkstack(hlua->T, 1)) {
6679 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6680 goto error;
6681 }
6682 lua_pushstring(hlua->T, args[i]);
6683 hlua->nargs++;
6684 }
6685
6686 /* We must initialize the execution timeouts. */
6687 hlua->max_time = hlua_timeout_session;
6688
6689 /* At this point the execution is safe. */
6690 RESET_SAFE_LJMP(hlua->T);
6691
6692 /* It's ok */
6693 return 0;
6694
6695 /* It's not ok. */
6696error:
6697 RESET_SAFE_LJMP(hlua->T);
6698 hlua_ctx_destroy(hlua);
6699 return 1;
6700}
6701
6702static int hlua_cli_io_handler_fct(struct appctx *appctx)
6703{
6704 struct hlua *hlua;
6705 struct stream_interface *si;
6706 struct hlua_function *fcn;
6707
6708 hlua = &appctx->ctx.hlua_cli.hlua;
6709 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01006710 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006711
6712 /* If the stream is disconnect or closed, ldo nothing. */
6713 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6714 return 1;
6715
6716 /* Execute the function. */
6717 switch (hlua_ctx_resume(hlua, 1)) {
6718
6719 /* finished. */
6720 case HLUA_E_OK:
6721 return 1;
6722
6723 /* yield. */
6724 case HLUA_E_AGAIN:
6725 /* We want write. */
6726 if (HLUA_IS_WAKERESWR(hlua))
6727 si_applet_cant_put(si);
6728 /* Set the timeout. */
6729 if (hlua->wake_time != TICK_ETERNITY)
6730 task_schedule(hlua->task, hlua->wake_time);
6731 return 0;
6732
6733 /* finished with error. */
6734 case HLUA_E_ERRMSG:
6735 /* Display log. */
6736 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
6737 fcn->name, lua_tostring(hlua->T, -1));
6738 lua_pop(hlua->T, 1);
6739 return 1;
6740
6741 case HLUA_E_ERR:
6742 /* Display log. */
6743 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
6744 fcn->name);
6745 return 1;
6746
6747 default:
6748 return 1;
6749 }
6750
6751 return 1;
6752}
6753
6754static void hlua_cli_io_release_fct(struct appctx *appctx)
6755{
6756 struct hlua *hlua;
6757
6758 hlua = &appctx->ctx.hlua_cli.hlua;
6759 hlua_ctx_destroy(hlua);
6760}
6761
6762/* This function is an LUA binding used for registering
6763 * new keywords in the cli. It expects a list of keywords
6764 * which are the "path". It is limited to 5 keywords. A
6765 * description of the command, a function to be executed
6766 * for the parsing and a function for io handlers.
6767 */
6768__LJMP static int hlua_register_cli(lua_State *L)
6769{
6770 struct cli_kw_list *cli_kws;
6771 const char *message;
6772 int ref_io;
6773 int len;
6774 struct hlua_function *fcn;
6775 int index;
6776 int i;
6777
6778 MAY_LJMP(check_args(L, 3, "register_cli"));
6779
6780 /* First argument : an array of maximum 5 keywords. */
6781 if (!lua_istable(L, 1))
6782 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
6783
6784 /* Second argument : string with contextual message. */
6785 message = MAY_LJMP(luaL_checkstring(L, 2));
6786
6787 /* Third and fourth argument : lua function. */
6788 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
6789
6790 /* Allocate and fill the sample fetch keyword struct. */
6791 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
6792 if (!cli_kws)
6793 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6794 fcn = calloc(1, sizeof(*fcn));
6795 if (!fcn)
6796 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6797
6798 /* Fill path. */
6799 index = 0;
6800 lua_pushnil(L);
6801 while(lua_next(L, 1) != 0) {
6802 if (index >= 5)
6803 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
6804 if (lua_type(L, -1) != LUA_TSTRING)
6805 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
6806 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
6807 if (!cli_kws->kw[0].str_kw[index])
6808 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6809 index++;
6810 lua_pop(L, 1);
6811 }
6812
6813 /* Copy help message. */
6814 cli_kws->kw[0].usage = strdup(message);
6815 if (!cli_kws->kw[0].usage)
6816 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6817
6818 /* Fill fcn io handler. */
6819 len = strlen("<lua.cli>") + 1;
6820 for (i = 0; i < index; i++)
6821 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
6822 fcn->name = calloc(1, len);
6823 if (!fcn->name)
6824 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6825 strncat((char *)fcn->name, "<lua.cli", len);
6826 for (i = 0; i < index; i++) {
6827 strncat((char *)fcn->name, ".", len);
6828 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
6829 }
6830 strncat((char *)fcn->name, ">", len);
6831 fcn->function_ref = ref_io;
6832
6833 /* Fill last entries. */
6834 cli_kws->kw[0].private = fcn;
6835 cli_kws->kw[0].parse = hlua_cli_parse_fct;
6836 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
6837 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
6838
6839 /* Register this new converter */
6840 cli_register_kw(cli_kws);
6841
6842 return 0;
6843}
6844
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006845static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
6846 struct proxy *defpx, const char *file, int line,
6847 char **err, unsigned int *timeout)
6848{
6849 const char *error;
6850
6851 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
6852 if (error && *error != '\0') {
6853 memprintf(err, "%s: invalid timeout", args[0]);
6854 return -1;
6855 }
6856 return 0;
6857}
6858
6859static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
6860 struct proxy *defpx, const char *file, int line,
6861 char **err)
6862{
6863 return hlua_read_timeout(args, section_type, curpx, defpx,
6864 file, line, err, &hlua_timeout_session);
6865}
6866
6867static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
6868 struct proxy *defpx, const char *file, int line,
6869 char **err)
6870{
6871 return hlua_read_timeout(args, section_type, curpx, defpx,
6872 file, line, err, &hlua_timeout_task);
6873}
6874
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006875static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
6876 struct proxy *defpx, const char *file, int line,
6877 char **err)
6878{
6879 return hlua_read_timeout(args, section_type, curpx, defpx,
6880 file, line, err, &hlua_timeout_applet);
6881}
6882
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006883static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
6884 struct proxy *defpx, const char *file, int line,
6885 char **err)
6886{
6887 char *error;
6888
6889 hlua_nb_instruction = strtoll(args[1], &error, 10);
6890 if (*error != '\0') {
6891 memprintf(err, "%s: invalid number", args[0]);
6892 return -1;
6893 }
6894 return 0;
6895}
6896
Willy Tarreau32f61e22015-03-18 17:54:59 +01006897static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
6898 struct proxy *defpx, const char *file, int line,
6899 char **err)
6900{
6901 char *error;
6902
6903 if (*(args[1]) == 0) {
6904 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
6905 return -1;
6906 }
6907 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
6908 if (*error != '\0') {
6909 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
6910 return -1;
6911 }
6912 return 0;
6913}
6914
6915
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006916/* This function is called by the main configuration key "lua-load". It loads and
6917 * execute an lua file during the parsing of the HAProxy configuration file. It is
6918 * the main lua entry point.
6919 *
6920 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
6921 * occured, otherwise it returns 0.
6922 *
6923 * In some error case, LUA set an error message in top of the stack. This function
6924 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006925 *
6926 * This function can fail with an abort() due to an Lua critical error.
6927 * We are in the configuration parsing process of HAProxy, this abort() is
6928 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006929 */
6930static int hlua_load(char **args, int section_type, struct proxy *curpx,
6931 struct proxy *defpx, const char *file, int line,
6932 char **err)
6933{
6934 int error;
6935
6936 /* Just load and compile the file. */
6937 error = luaL_loadfile(gL.T, args[1]);
6938 if (error) {
6939 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
6940 lua_pop(gL.T, 1);
6941 return -1;
6942 }
6943
6944 /* If no syntax error where detected, execute the code. */
6945 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
6946 switch (error) {
6947 case LUA_OK:
6948 break;
6949 case LUA_ERRRUN:
6950 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
6951 lua_pop(gL.T, 1);
6952 return -1;
6953 case LUA_ERRMEM:
6954 memprintf(err, "lua out of memory error\n");
6955 return -1;
6956 case LUA_ERRERR:
6957 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
6958 lua_pop(gL.T, 1);
6959 return -1;
6960 case LUA_ERRGCMM:
6961 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
6962 lua_pop(gL.T, 1);
6963 return -1;
6964 default:
6965 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
6966 lua_pop(gL.T, 1);
6967 return -1;
6968 }
6969
6970 return 0;
6971}
6972
6973/* configuration keywords declaration */
6974static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006975 { CFG_GLOBAL, "lua-load", hlua_load },
6976 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
6977 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02006978 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006979 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01006980 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006981 { 0, NULL, NULL },
6982}};
6983
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006984/* This function can fail with an abort() due to an Lua critical error.
6985 * We are in the initialisation process of HAProxy, this abort() is
6986 * tolerated.
6987 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006988int hlua_post_init()
6989{
6990 struct hlua_init_function *init;
6991 const char *msg;
6992 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006993 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006994
Thierry Fournier3d4a6752016-02-19 20:53:30 +01006995 /* Call post initialisation function in safe environement. */
6996 if (!SET_SAFE_LJMP(gL.T)) {
6997 if (lua_type(gL.T, -1) == LUA_TSTRING)
6998 error = lua_tostring(gL.T, -1);
6999 else
7000 error = "critical error";
7001 fprintf(stderr, "Lua post-init: %s.\n", error);
7002 exit(1);
7003 }
7004 hlua_fcn_post_init(gL.T);
7005 RESET_SAFE_LJMP(gL.T);
7006
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007007 list_for_each_entry(init, &hlua_init_functions, l) {
7008 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7009 ret = hlua_ctx_resume(&gL, 0);
7010 switch (ret) {
7011 case HLUA_E_OK:
7012 lua_pop(gL.T, -1);
7013 return 1;
7014 case HLUA_E_AGAIN:
7015 Alert("lua init: yield not allowed.\n");
7016 return 0;
7017 case HLUA_E_ERRMSG:
7018 msg = lua_tostring(gL.T, -1);
7019 Alert("lua init: %s.\n", msg);
7020 return 0;
7021 case HLUA_E_ERR:
7022 default:
7023 Alert("lua init: unknown runtime error.\n");
7024 return 0;
7025 }
7026 }
7027 return 1;
7028}
7029
Willy Tarreau32f61e22015-03-18 17:54:59 +01007030/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7031 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7032 * is the previously allocated size or the kind of object in case of a new
7033 * allocation. <nsize> is the requested new size.
7034 */
7035static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7036{
7037 struct hlua_mem_allocator *zone = ud;
7038
7039 if (nsize == 0) {
7040 /* it's a free */
7041 if (ptr)
7042 zone->allocated -= osize;
7043 free(ptr);
7044 return NULL;
7045 }
7046
7047 if (!ptr) {
7048 /* it's a new allocation */
7049 if (zone->limit && zone->allocated + nsize > zone->limit)
7050 return NULL;
7051
7052 ptr = malloc(nsize);
7053 if (ptr)
7054 zone->allocated += nsize;
7055 return ptr;
7056 }
7057
7058 /* it's a realloc */
7059 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7060 return NULL;
7061
7062 ptr = realloc(ptr, nsize);
7063 if (ptr)
7064 zone->allocated += nsize - osize;
7065 return ptr;
7066}
7067
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007068/* Ithis function can fail with an abort() due to an Lua critical error.
7069 * We are in the initialisation process of HAProxy, this abort() is
7070 * tolerated.
7071 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007072void hlua_init(void)
7073{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007074 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007075 int idx;
7076 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007077 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007078 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007079 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007080#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007081 struct srv_kw *kw;
7082 int tmp_error;
7083 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007084 char *args[] = { /* SSL client configuration. */
7085 "ssl",
7086 "verify",
7087 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007088 NULL
7089 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007090#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007091
Willy Tarreau87b09662015-04-03 00:22:06 +02007092 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007093 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
7094
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007095 /* Register configuration keywords. */
7096 cfg_register_keywords(&cfg_kws);
7097
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007098 /* Init main lua stack. */
7099 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007100 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007101 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007102 gL.T = luaL_newstate();
7103 hlua_sethlua(&gL);
7104 gL.Tref = LUA_REFNIL;
7105 gL.task = NULL;
7106
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007107 /* From this point, until the end of the initialisation fucntion,
7108 * the Lua function can fail with an abort. We are in the initialisation
7109 * process of HAProxy, this abort() is tolerated.
7110 */
7111
Willy Tarreau32f61e22015-03-18 17:54:59 +01007112 /* change the memory allocators to track memory usage */
7113 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
7114
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007115 /* Initialise lua. */
7116 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007117
Thierry Fournier75933d42016-01-21 09:30:18 +01007118 /* Set safe environment for the initialisation. */
7119 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007120 if (lua_type(gL.T, -1) == LUA_TSTRING)
7121 error_msg = lua_tostring(gL.T, -1);
7122 else
7123 error_msg = "critical error";
7124 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007125 exit(1);
7126 }
7127
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007128 /*
7129 *
7130 * Create "core" object.
7131 *
7132 */
7133
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007134 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007135 lua_newtable(gL.T);
7136
7137 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007138 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007139 hlua_class_const_int(gL.T, log_levels[i], i);
7140
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007141 /* Register special functions. */
7142 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007143 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007144 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007145 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007146 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007147 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007148 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007149 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007150 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007151 hlua_class_function(gL.T, "sleep", hlua_sleep);
7152 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007153 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7154 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7155 hlua_class_function(gL.T, "set_map", hlua_set_map);
7156 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007157 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007158 hlua_class_function(gL.T, "log", hlua_log);
7159 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7160 hlua_class_function(gL.T, "Info", hlua_log_info);
7161 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7162 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007163 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007164 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007165
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007166 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007167
7168 /*
7169 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007170 * Register class Map
7171 *
7172 */
7173
7174 /* This table entry is the object "Map" base. */
7175 lua_newtable(gL.T);
7176
7177 /* register pattern types. */
7178 for (i=0; i<PAT_MATCH_NUM; i++)
7179 hlua_class_const_int(gL.T, pat_match_names[i], i);
7180
7181 /* register constructor. */
7182 hlua_class_function(gL.T, "new", hlua_map_new);
7183
7184 /* Create and fill the metatable. */
7185 lua_newtable(gL.T);
7186
7187 /* Create and fille the __index entry. */
7188 lua_pushstring(gL.T, "__index");
7189 lua_newtable(gL.T);
7190
7191 /* Register . */
7192 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7193 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7194
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007195 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007196
Thierry Fournier45e78d72016-02-19 18:34:46 +01007197 /* Register previous table in the registry with reference and named entry.
7198 * The function hlua_register_metatable() pops the stack, so we
7199 * previously create a copy of the table.
7200 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007201 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007202 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007203
7204 /* Assign the metatable to the mai Map object. */
7205 lua_setmetatable(gL.T, -2);
7206
7207 /* Set a name to the table. */
7208 lua_setglobal(gL.T, "Map");
7209
7210 /*
7211 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007212 * Register class Channel
7213 *
7214 */
7215
7216 /* Create and fill the metatable. */
7217 lua_newtable(gL.T);
7218
7219 /* Create and fille the __index entry. */
7220 lua_pushstring(gL.T, "__index");
7221 lua_newtable(gL.T);
7222
7223 /* Register . */
7224 hlua_class_function(gL.T, "get", hlua_channel_get);
7225 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7226 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7227 hlua_class_function(gL.T, "set", hlua_channel_set);
7228 hlua_class_function(gL.T, "append", hlua_channel_append);
7229 hlua_class_function(gL.T, "send", hlua_channel_send);
7230 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7231 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7232 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007233 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007234
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007235 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007236
7237 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007238 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007239
7240 /*
7241 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007242 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007243 *
7244 */
7245
7246 /* Create and fill the metatable. */
7247 lua_newtable(gL.T);
7248
7249 /* Create and fille the __index entry. */
7250 lua_pushstring(gL.T, "__index");
7251 lua_newtable(gL.T);
7252
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007253 /* Browse existing fetches and create the associated
7254 * object method.
7255 */
7256 sf = NULL;
7257 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7258
7259 /* Dont register the keywork if the arguments check function are
7260 * not safe during the runtime.
7261 */
7262 if ((sf->val_args != NULL) &&
7263 (sf->val_args != val_payload_lv) &&
7264 (sf->val_args != val_hdr))
7265 continue;
7266
7267 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7268 * by an underscore.
7269 */
7270 strncpy(trash.str, sf->kw, trash.size);
7271 trash.str[trash.size - 1] = '\0';
7272 for (p = trash.str; *p; p++)
7273 if (*p == '.' || *p == '-' || *p == '+')
7274 *p = '_';
7275
7276 /* Register the function. */
7277 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007278 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007279 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007280 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007281 }
7282
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007283 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007284
7285 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007286 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007287
7288 /*
7289 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007290 * Register class Converters
7291 *
7292 */
7293
7294 /* Create and fill the metatable. */
7295 lua_newtable(gL.T);
7296
7297 /* Create and fill the __index entry. */
7298 lua_pushstring(gL.T, "__index");
7299 lua_newtable(gL.T);
7300
7301 /* Browse existing converters and create the associated
7302 * object method.
7303 */
7304 sc = NULL;
7305 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7306 /* Dont register the keywork if the arguments check function are
7307 * not safe during the runtime.
7308 */
7309 if (sc->val_args != NULL)
7310 continue;
7311
7312 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7313 * by an underscore.
7314 */
7315 strncpy(trash.str, sc->kw, trash.size);
7316 trash.str[trash.size - 1] = '\0';
7317 for (p = trash.str; *p; p++)
7318 if (*p == '.' || *p == '-' || *p == '+')
7319 *p = '_';
7320
7321 /* Register the function. */
7322 lua_pushstring(gL.T, trash.str);
7323 lua_pushlightuserdata(gL.T, sc);
7324 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007325 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007326 }
7327
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007328 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007329
7330 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007331 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007332
7333 /*
7334 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007335 * Register class HTTP
7336 *
7337 */
7338
7339 /* Create and fill the metatable. */
7340 lua_newtable(gL.T);
7341
7342 /* Create and fille the __index entry. */
7343 lua_pushstring(gL.T, "__index");
7344 lua_newtable(gL.T);
7345
7346 /* Register Lua functions. */
7347 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7348 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7349 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7350 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7351 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7352 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7353 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7354 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7355 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7356 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7357
7358 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7359 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7360 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7361 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7362 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7363 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007364 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007365
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007366 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007367
7368 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007369 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007370
7371 /*
7372 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007373 * Register class AppletTCP
7374 *
7375 */
7376
7377 /* Create and fill the metatable. */
7378 lua_newtable(gL.T);
7379
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007380 /* Create and fille the __index entry. */
7381 lua_pushstring(gL.T, "__index");
7382 lua_newtable(gL.T);
7383
7384 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007385 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7386 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7387 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7388 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7389 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007390 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7391 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7392 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007393
7394 lua_settable(gL.T, -3);
7395
7396 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007397 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007398
7399 /*
7400 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007401 * Register class AppletHTTP
7402 *
7403 */
7404
7405 /* Create and fill the metatable. */
7406 lua_newtable(gL.T);
7407
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007408 /* Create and fille the __index entry. */
7409 lua_pushstring(gL.T, "__index");
7410 lua_newtable(gL.T);
7411
7412 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007413 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7414 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007415 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7416 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7417 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007418 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7419 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7420 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7421 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7422 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7423 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7424
7425 lua_settable(gL.T, -3);
7426
7427 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007428 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007429
7430 /*
7431 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007432 * Register class TXN
7433 *
7434 */
7435
7436 /* Create and fill the metatable. */
7437 lua_newtable(gL.T);
7438
7439 /* Create and fille the __index entry. */
7440 lua_pushstring(gL.T, "__index");
7441 lua_newtable(gL.T);
7442
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007443 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007444 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7445 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007446 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007447 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007448 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007449 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007450 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7451 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7452 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007453 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7454 hlua_class_function(gL.T, "log", hlua_txn_log);
7455 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7456 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7457 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7458 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007459
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007460 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007461
7462 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007463 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007464
7465 /*
7466 *
7467 * Register class Socket
7468 *
7469 */
7470
7471 /* Create and fill the metatable. */
7472 lua_newtable(gL.T);
7473
7474 /* Create and fille the __index entry. */
7475 lua_pushstring(gL.T, "__index");
7476 lua_newtable(gL.T);
7477
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007478#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007479 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007480#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007481 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7482 hlua_class_function(gL.T, "send", hlua_socket_send);
7483 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7484 hlua_class_function(gL.T, "close", hlua_socket_close);
7485 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7486 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7487 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7488 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7489
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007490 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007491
7492 /* Register the garbage collector entry. */
7493 lua_pushstring(gL.T, "__gc");
7494 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007495 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007496
7497 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007498 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007499
7500 /* Proxy and server configuration initialisation. */
7501 memset(&socket_proxy, 0, sizeof(socket_proxy));
7502 init_new_proxy(&socket_proxy);
7503 socket_proxy.parent = NULL;
7504 socket_proxy.last_change = now.tv_sec;
7505 socket_proxy.id = "LUA-SOCKET";
7506 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7507 socket_proxy.maxconn = 0;
7508 socket_proxy.accept = NULL;
7509 socket_proxy.options2 |= PR_O2_INDEPSTR;
7510 socket_proxy.srv = NULL;
7511 socket_proxy.conn_retries = 0;
7512 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7513
7514 /* Init TCP server: unchanged parameters */
7515 memset(&socket_tcp, 0, sizeof(socket_tcp));
7516 socket_tcp.next = NULL;
7517 socket_tcp.proxy = &socket_proxy;
7518 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7519 LIST_INIT(&socket_tcp.actconns);
7520 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007521 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007522 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007523 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007524 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
7525 socket_tcp.last_change = 0;
7526 socket_tcp.id = "LUA-TCP-CONN";
7527 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7528 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7529 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7530
7531 /* XXX: Copy default parameter from default server,
7532 * but the default server is not initialized.
7533 */
7534 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7535 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7536 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7537 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7538 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7539 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7540 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7541 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7542 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7543 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7544
7545 socket_tcp.check.status = HCHK_STATUS_INI;
7546 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7547 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7548 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7549 socket_tcp.check.server = &socket_tcp;
7550
7551 socket_tcp.agent.status = HCHK_STATUS_INI;
7552 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7553 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7554 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7555 socket_tcp.agent.server = &socket_tcp;
7556
7557 socket_tcp.xprt = &raw_sock;
7558
7559#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007560 /* Init TCP server: unchanged parameters */
7561 memset(&socket_ssl, 0, sizeof(socket_ssl));
7562 socket_ssl.next = NULL;
7563 socket_ssl.proxy = &socket_proxy;
7564 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7565 LIST_INIT(&socket_ssl.actconns);
7566 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007567 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007568 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007569 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007570 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
7571 socket_ssl.last_change = 0;
7572 socket_ssl.id = "LUA-SSL-CONN";
7573 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7574 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7575 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7576
7577 /* XXX: Copy default parameter from default server,
7578 * but the default server is not initialized.
7579 */
7580 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7581 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7582 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7583 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7584 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7585 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7586 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7587 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7588 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7589 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7590
7591 socket_ssl.check.status = HCHK_STATUS_INI;
7592 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7593 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7594 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7595 socket_ssl.check.server = &socket_ssl;
7596
7597 socket_ssl.agent.status = HCHK_STATUS_INI;
7598 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7599 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7600 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7601 socket_ssl.agent.server = &socket_ssl;
7602
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007603 socket_ssl.use_ssl = 1;
7604 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007605
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007606 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007607 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7608 /*
7609 *
7610 * If the keyword is not known, we can search in the registered
7611 * server keywords. This is usefull to configure special SSL
7612 * features like client certificates and ssl_verify.
7613 *
7614 */
7615 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7616 if (tmp_error != 0) {
7617 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7618 abort(); /* This must be never arrives because the command line
7619 not editable by the user. */
7620 }
7621 idx += kw->skip;
7622 }
7623 }
7624
7625 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007626 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007627#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007628
7629 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007630}