blob: 5595446c093ba94ec33fd4b930d0126b42d6aab8 [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 FOURNIER258d8aa2015-02-16 20:23:40 +010047#include <proto/proto_tcp.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010048#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010049#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010050#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020051#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020052#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010053#include <proto/ssl_sock.h>
54#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010055#include <proto/task.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 FOURNIER7e7ac322015-02-16 19:27:16 +01001540 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1541 hlua_com_wake(&appctx->ctx.hlua.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)))
1547 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1548
1549 /* If we cant read, wakeup the pending read signals. */
1550 if (channel_input_closed(si_oc(si)))
1551 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1552
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. */
1563 appctx->ctx.hlua.connected = 1;
1564
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 FOURNIER7e7ac322015-02-16 19:27:16 +01001567 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1568
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 FOURNIER7e7ac322015-02-16 19:27:16 +01001571 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1572}
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. */
1581 if (appctx->ctx.hlua.socket)
1582 appctx->ctx.hlua.socket->s = NULL;
1583
1584 /* Wake all the task waiting for me. */
1585 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1586 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1587}
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;
1610 appctx->ctx.hlua.socket = NULL;
1611
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);
1632 appctx->ctx.hlua.socket = NULL;
1633 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);
1770 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1771 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) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001887 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001888 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001889 goto hlua_socket_write_yield_return;
1890 }
1891 }
1892
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001893 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001894 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001895 if (len <= 0)
1896 goto hlua_socket_write_yield_return;
1897
1898 /* send data */
1899 if (len < send_len)
1900 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001901 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001902
1903 /* "Not enough space" (-1), "Buffer too little to contain
1904 * the data" (-2) are not expected because the available length
1905 * is tested.
1906 * Other unknown error are also not expected.
1907 */
1908 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001909 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001910 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001911
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001912 MAY_LJMP(hlua_socket_close(L));
1913 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001914 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001915 return 1;
1916 }
1917
1918 /* update buffers. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001919 stream_int_notify(&socket->s->si[0]);
1920 stream_int_update_applet(&socket->s->si[0]);
1921
Willy Tarreau94aa6172015-03-13 14:19:06 +01001922 socket->s->req.rex = TICK_ETERNITY;
1923 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001924
1925 /* Update length sent. */
1926 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001927 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001928
1929 /* All the data buffer is sent ? */
1930 if (sent + len >= buf_len)
1931 return 1;
1932
1933hlua_socket_write_yield_return:
1934 appctx = objt_appctx(socket->s->si[0].end);
1935 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1936 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001937 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001938 return 0;
1939}
1940
1941/* This function initiate the send of data. It just check the input
1942 * parameters and push an integer in the Lua stack that contain the
1943 * amount of data writed in the buffer. This is used by the function
1944 * "hlua_socket_write_yield" that can yield.
1945 *
1946 * The Lua function gets between 3 and 4 parameters. The first one is
1947 * the associated object. The second is a string buffer. The third is
1948 * a facultative integer that represents where is the buffer position
1949 * of the start of the data that can send. The first byte is the
1950 * position "1". The default value is "1". The fourth argument is a
1951 * facultative integer that represents where is the buffer position
1952 * of the end of the data that can send. The default is the last byte.
1953 */
1954static int hlua_socket_send(struct lua_State *L)
1955{
1956 int i;
1957 int j;
1958 const char *buf;
1959 size_t buf_len;
1960
1961 /* Check number of arguments. */
1962 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1963 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1964
1965 /* Get the string. */
1966 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1967
1968 /* Get and check j. */
1969 if (lua_gettop(L) == 4) {
1970 j = MAY_LJMP(luaL_checkinteger(L, 4));
1971 if (j < 0)
1972 j = buf_len + j + 1;
1973 if (j > buf_len)
1974 j = buf_len + 1;
1975 lua_pop(L, 1);
1976 }
1977 else
1978 j = buf_len;
1979
1980 /* Get and check i. */
1981 if (lua_gettop(L) == 3) {
1982 i = MAY_LJMP(luaL_checkinteger(L, 3));
1983 if (i < 0)
1984 i = buf_len + i + 1;
1985 if (i > buf_len)
1986 i = buf_len + 1;
1987 lua_pop(L, 1);
1988 } else
1989 i = 1;
1990
1991 /* Check bth i and j. */
1992 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001993 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001994 return 1;
1995 }
1996 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001997 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001998 return 1;
1999 }
2000 if (i == 0)
2001 i = 1;
2002 if (j == 0)
2003 j = 1;
2004
2005 /* Pop the string. */
2006 lua_pop(L, 1);
2007
2008 /* Update the buffer length. */
2009 buf += i - 1;
2010 buf_len = j - i + 1;
2011 lua_pushlstring(L, buf, buf_len);
2012
2013 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002014 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002015
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002016 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002017}
2018
Willy Tarreau22b0a682015-06-17 19:43:49 +02002019#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002020__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2021{
2022 static char buffer[SOCKET_INFO_MAX_LEN];
2023 int ret;
2024 int len;
2025 char *p;
2026
2027 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2028 if (ret <= 0) {
2029 lua_pushnil(L);
2030 return 1;
2031 }
2032
2033 if (ret == AF_UNIX) {
2034 lua_pushstring(L, buffer+1);
2035 return 1;
2036 }
2037 else if (ret == AF_INET6) {
2038 buffer[0] = '[';
2039 len = strlen(buffer);
2040 buffer[len] = ']';
2041 len++;
2042 buffer[len] = ':';
2043 len++;
2044 p = buffer;
2045 }
2046 else if (ret == AF_INET) {
2047 p = buffer + 1;
2048 len = strlen(p);
2049 p[len] = ':';
2050 len++;
2051 }
2052 else {
2053 lua_pushnil(L);
2054 return 1;
2055 }
2056
2057 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2058 lua_pushnil(L);
2059 return 1;
2060 }
2061
2062 lua_pushstring(L, p);
2063 return 1;
2064}
2065
2066/* Returns information about the peer of the connection. */
2067__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2068{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002069 struct hlua_socket *socket;
2070 struct connection *conn;
2071
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002072 MAY_LJMP(check_args(L, 1, "getpeername"));
2073
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002074 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002075
2076 /* Check if the tcp object is avalaible. */
2077 if (!socket->s) {
2078 lua_pushnil(L);
2079 return 1;
2080 }
2081
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002082 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002083 if (!conn) {
2084 lua_pushnil(L);
2085 return 1;
2086 }
2087
Willy Tarreaua71f6422016-11-16 17:00:14 +01002088 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002089 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Willy Tarreaua71f6422016-11-16 17:00:14 +01002090 lua_pushnil(L);
2091 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002092 }
2093
2094 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2095}
2096
2097/* Returns information about my connection side. */
2098static int hlua_socket_getsockname(struct lua_State *L)
2099{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002100 struct hlua_socket *socket;
2101 struct connection *conn;
2102
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002103 MAY_LJMP(check_args(L, 1, "getsockname"));
2104
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002105 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002106
2107 /* Check if the tcp object is avalaible. */
2108 if (!socket->s) {
2109 lua_pushnil(L);
2110 return 1;
2111 }
2112
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002113 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002114 if (!conn) {
2115 lua_pushnil(L);
2116 return 1;
2117 }
2118
Willy Tarreaua71f6422016-11-16 17:00:14 +01002119 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002120 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Willy Tarreaua71f6422016-11-16 17:00:14 +01002121 lua_pushnil(L);
2122 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002123 }
2124
2125 return hlua_socket_info(L, &conn->addr.from);
2126}
2127
2128/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002129static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002130 .obj_type = OBJ_TYPE_APPLET,
2131 .name = "<LUA_TCP>",
2132 .fct = hlua_socket_handler,
2133 .release = hlua_socket_release,
2134};
2135
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002136__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002137{
2138 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2139 struct hlua *hlua = hlua_gethlua(L);
2140 struct appctx *appctx;
2141
2142 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002143 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002144 lua_pushnil(L);
2145 lua_pushstring(L, "Can't connect");
2146 return 2;
2147 }
2148
2149 appctx = objt_appctx(socket->s->si[0].end);
2150
2151 /* Check for connection established. */
2152 if (appctx->ctx.hlua.connected) {
2153 lua_pushinteger(L, 1);
2154 return 1;
2155 }
2156
2157 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2158 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002159 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002160 return 0;
2161}
2162
2163/* This function fail or initite the connection. */
2164__LJMP static int hlua_socket_connect(struct lua_State *L)
2165{
2166 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002167 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002168 const char *ip;
2169 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002170 struct hlua *hlua;
2171 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002172 int low, high;
2173 struct sockaddr_storage *addr;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002174
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002175 if (lua_gettop(L) < 2)
2176 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002177
2178 /* Get args. */
2179 socket = MAY_LJMP(hlua_checksocket(L, 1));
2180 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002181 if (lua_gettop(L) >= 3)
2182 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002183
Willy Tarreau973a5422015-08-05 21:47:23 +02002184 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002185 if (!conn)
2186 WILL_LJMP(luaL_error(L, "connect: internal error"));
2187
Willy Tarreau3adac082015-09-26 17:51:09 +02002188 /* needed for the connection not to be closed */
2189 conn->target = socket->s->target;
2190
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002191 /* Parse ip address. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002192 addr = str2sa_range(ip, &low, &high, NULL, NULL, NULL, 0);
2193 if (!addr)
2194 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
2195 if (low != high)
2196 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
2197 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002198
2199 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002200 if (low == 0) {
2201 if (conn->addr.to.ss_family == AF_INET) {
2202 if (port == -1)
2203 WILL_LJMP(luaL_error(L, "connect: port missing"));
2204 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2205 } else if (conn->addr.to.ss_family == AF_INET6) {
2206 if (port == -1)
2207 WILL_LJMP(luaL_error(L, "connect: port missing"));
2208 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2209 }
2210 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002211
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002212 hlua = hlua_gethlua(L);
2213 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002214
2215 /* inform the stream that we want to be notified whenever the
2216 * connection completes.
2217 */
2218 si_applet_cant_get(&socket->s->si[0]);
2219 si_applet_cant_put(&socket->s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002220 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002221
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002222 hlua->flags |= HLUA_MUST_GC;
2223
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002224 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2225 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002226 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002227
2228 return 0;
2229}
2230
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002231#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002232__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2233{
2234 struct hlua_socket *socket;
2235
2236 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2237 socket = MAY_LJMP(hlua_checksocket(L, 1));
2238 socket->s->target = &socket_ssl.obj_type;
2239 return MAY_LJMP(hlua_socket_connect(L));
2240}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002241#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002242
2243__LJMP static int hlua_socket_setoption(struct lua_State *L)
2244{
2245 return 0;
2246}
2247
2248__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2249{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002250 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002251 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002252
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002253 MAY_LJMP(check_args(L, 2, "settimeout"));
2254
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002255 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002256 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002257
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002258 socket->s->req.rto = tmout;
2259 socket->s->req.wto = tmout;
2260 socket->s->res.rto = tmout;
2261 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002262
2263 return 0;
2264}
2265
2266__LJMP static int hlua_socket_new(lua_State *L)
2267{
2268 struct hlua_socket *socket;
2269 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002270 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002271 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002272 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002273
2274 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002275 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002276 hlua_pusherror(L, "socket: full stack");
2277 goto out_fail_conf;
2278 }
2279
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002280 /* Create the object: obj[0] = userdata. */
2281 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002282 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002283 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002284 memset(socket, 0, sizeof(*socket));
2285
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002286 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002287 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002288 hlua_pusherror(L, "socket: uninitialized pools.");
2289 goto out_fail_conf;
2290 }
2291
Willy Tarreau87b09662015-04-03 00:22:06 +02002292 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002293 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2294 lua_setmetatable(L, -2);
2295
Willy Tarreaud420a972015-04-06 00:39:18 +02002296 /* Create the applet context */
2297 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002298 if (!appctx) {
2299 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002300 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002301 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002302
Willy Tarreaud420a972015-04-06 00:39:18 +02002303 appctx->ctx.hlua.socket = socket;
2304 appctx->ctx.hlua.connected = 0;
2305 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2306 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002307
Willy Tarreaud420a972015-04-06 00:39:18 +02002308 /* Now create a session, task and stream for this applet */
2309 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2310 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002312 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313 }
2314
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002315 task = task_new();
2316 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002317 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002318 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002319 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002320 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002322 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002323 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002324 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002325 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002326 }
2327
Willy Tarreaud420a972015-04-06 00:39:18 +02002328 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002329 socket->s = strm;
2330 strm->hlua.T = NULL;
2331 strm->hlua.Tref = LUA_REFNIL;
2332 strm->hlua.Mref = LUA_REFNIL;
2333 strm->hlua.nargs = 0;
2334 strm->hlua.flags = 0;
2335 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002336
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002337 /* Configure "right" stream interface. this "si" is used to connect
2338 * and retrieve data from the server. The connection is initialized
2339 * with the "struct server".
2340 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002341 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002342
2343 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002344 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2345 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002346
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002347 /* Update statistics counters. */
2348 socket_proxy.feconn++; /* beconn will be increased later */
2349 jobs++;
2350 totalconn++;
2351
2352 /* Return yield waiting for connection. */
2353 return 1;
2354
Willy Tarreaud420a972015-04-06 00:39:18 +02002355 out_fail_stream:
2356 task_free(task);
2357 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002358 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002359 out_fail_sess:
2360 appctx_free(appctx);
2361 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002362 WILL_LJMP(lua_error(L));
2363 return 0;
2364}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002365
2366/*
2367 *
2368 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002369 * Class Channel
2370 *
2371 *
2372 */
2373
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002374/* The state between the channel data and the HTTP parser state can be
2375 * unconsistent, so reset the parser and call it again. Warning, this
2376 * action not revalidate the request and not send a 400 if the modified
2377 * resuest is not valid.
2378 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002379 * This function never fails. The direction is set using dir, which equals
2380 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002381 */
2382static void hlua_resynchonize_proto(struct stream *stream, int dir)
2383{
2384 /* Protocol HTTP. */
2385 if (stream->be->mode == PR_MODE_HTTP) {
2386
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002387 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002388 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002389 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002390 http_txn_reset_res(stream->txn);
2391
2392 if (stream->txn->hdr_idx.v)
2393 hdr_idx_init(&stream->txn->hdr_idx);
2394
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002395 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002396 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002397 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002398 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2399 }
2400}
2401
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002402/* Check the protocole integrity after the Lua manipulations. Close the stream
2403 * and returns 0 if fails, otherwise returns 1. The direction is set using dir,
2404 * which equals either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002405 */
2406static int hlua_check_proto(struct stream *stream, int dir)
2407{
2408 const struct chunk msg = { .len = 0 };
2409
Willy Tarreau9af89f72015-09-26 11:50:08 +02002410 /* Protocol HTTP. The message parsing state must match the request or
2411 * response state. The problem that may happen is that Lua modifies
2412 * the request or response message *after* it was parsed, and corrupted
2413 * it so that it could not be processed anymore. We just need to verify
2414 * if the parser is still expected to run or not.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002415 */
2416 if (stream->be->mode == PR_MODE_HTTP) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002417 if (dir == SMP_OPT_DIR_REQ &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002418 !(stream->req.analysers & AN_REQ_WAIT_HTTP) &&
Thierry FOURNIER / OZON.IO8dc73162016-11-18 19:06:21 +01002419 stream->txn->req.msg_state < HTTP_MSG_ERROR) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002420 stream_int_retnclose(&stream->si[0], &msg);
2421 return 0;
2422 }
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002423 else if (dir == SMP_OPT_DIR_RES &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002424 !(stream->res.analysers & AN_RES_WAIT_HTTP) &&
Thierry FOURNIER / OZON.IO8dc73162016-11-18 19:06:21 +01002425 stream->txn->rsp.msg_state < HTTP_MSG_ERROR) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002426 stream_int_retnclose(&stream->si[0], &msg);
2427 return 0;
2428 }
2429 }
2430 return 1;
2431}
2432
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002433/* Returns the struct hlua_channel join to the class channel in the
2434 * stack entry "ud" or throws an argument error.
2435 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002436__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002437{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002438 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002439}
2440
Willy Tarreau47860ed2015-03-10 14:07:50 +01002441/* Pushes the channel onto the top of the stack. If the stask does not have a
2442 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002443 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002444static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002445{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002446 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002447 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002448 return 0;
2449
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002450 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002451 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002452 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002453
2454 /* Pop a class sesison metatable and affect it to the userdata. */
2455 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2456 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002457 return 1;
2458}
2459
2460/* Duplicate all the data present in the input channel and put it
2461 * in a string LUA variables. Returns -1 and push a nil value in
2462 * the stack if the channel is closed and all the data are consumed,
2463 * returns 0 if no data are available, otherwise it returns the length
2464 * of the builded string.
2465 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002466static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002467{
2468 char *blk1;
2469 char *blk2;
2470 int len1;
2471 int len2;
2472 int ret;
2473 luaL_Buffer b;
2474
Willy Tarreau47860ed2015-03-10 14:07:50 +01002475 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002476 if (unlikely(ret == 0))
2477 return 0;
2478
2479 if (unlikely(ret < 0)) {
2480 lua_pushnil(L);
2481 return -1;
2482 }
2483
2484 luaL_buffinit(L, &b);
2485 luaL_addlstring(&b, blk1, len1);
2486 if (unlikely(ret == 2))
2487 luaL_addlstring(&b, blk2, len2);
2488 luaL_pushresult(&b);
2489
2490 if (unlikely(ret == 2))
2491 return len1 + len2;
2492 return len1;
2493}
2494
2495/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2496 * a yield. This function keep the data in the buffer.
2497 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002498__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002499{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002500 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002501
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002502 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2503
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002504 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002505 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002506 return 1;
2507}
2508
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002509/* Check arguments for the function "hlua_channel_dup_yield". */
2510__LJMP static int hlua_channel_dup(lua_State *L)
2511{
2512 MAY_LJMP(check_args(L, 1, "dup"));
2513 MAY_LJMP(hlua_checkchannel(L, 1));
2514 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2515}
2516
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002517/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2518 * a yield. This function consumes the data in the buffer. It returns
2519 * a string containing the data or a nil pointer if no data are available
2520 * and the channel is closed.
2521 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002522__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002523{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002524 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002525 int ret;
2526
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002527 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002528
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002529 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002530 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002531 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002532
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002533 if (unlikely(ret == -1))
2534 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002535
Willy Tarreau47860ed2015-03-10 14:07:50 +01002536 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002537 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002538 return 1;
2539}
2540
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002541/* Check arguments for the fucntion "hlua_channel_get_yield". */
2542__LJMP static int hlua_channel_get(lua_State *L)
2543{
2544 MAY_LJMP(check_args(L, 1, "get"));
2545 MAY_LJMP(hlua_checkchannel(L, 1));
2546 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2547}
2548
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002549/* This functions consumes and returns one line. If the channel is closed,
2550 * and the last data does not contains a final '\n', the data are returned
2551 * without the final '\n'. When no more data are avalaible, it returns nil
2552 * value.
2553 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002554__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002555{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002556 char *blk1;
2557 char *blk2;
2558 int len1;
2559 int len2;
2560 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002561 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002562 int ret;
2563 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002564
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002565 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2566
Willy Tarreau47860ed2015-03-10 14:07:50 +01002567 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002568 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002569 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002570
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002571 if (ret == -1) {
2572 lua_pushnil(L);
2573 return 1;
2574 }
2575
2576 luaL_buffinit(L, &b);
2577 luaL_addlstring(&b, blk1, len1);
2578 len = len1;
2579 if (unlikely(ret == 2)) {
2580 luaL_addlstring(&b, blk2, len2);
2581 len += len2;
2582 }
2583 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002584 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002585 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002586 return 1;
2587}
2588
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002589/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2590__LJMP static int hlua_channel_getline(lua_State *L)
2591{
2592 MAY_LJMP(check_args(L, 1, "getline"));
2593 MAY_LJMP(hlua_checkchannel(L, 1));
2594 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2595}
2596
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002597/* This function takes a string as input, and append it at the
2598 * input side of channel. If the data is too big, but a space
2599 * is probably available after sending some data, the function
2600 * yield. If the data is bigger than the buffer, or if the
2601 * channel is closed, it returns -1. otherwise, it returns the
2602 * amount of data writed.
2603 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002604__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002605{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002606 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002607 size_t len;
2608 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2609 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2610 int ret;
2611 int max;
2612
Willy Tarreau47860ed2015-03-10 14:07:50 +01002613 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002614 if (max > len - l)
2615 max = len - l;
2616
Willy Tarreau47860ed2015-03-10 14:07:50 +01002617 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002618 if (ret == -2 || ret == -3) {
2619 lua_pushinteger(L, -1);
2620 return 1;
2621 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002622 if (ret == -1) {
2623 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002624 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002625 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002626 l += ret;
2627 lua_pop(L, 1);
2628 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002629 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002630
Willy Tarreau47860ed2015-03-10 14:07:50 +01002631 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2632 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002633 /* There are no space avalaible, and the output buffer is empty.
2634 * in this case, we cannot add more data, so we cannot yield,
2635 * we return the amount of copyied data.
2636 */
2637 return 1;
2638 }
2639 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002640 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002641 return 1;
2642}
2643
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002644/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002645 * of the writed string, or -1 if the channel is closed or if the
2646 * buffer size is too little for the data.
2647 */
2648__LJMP static int hlua_channel_append(lua_State *L)
2649{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002650 size_t len;
2651
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002652 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002653 MAY_LJMP(hlua_checkchannel(L, 1));
2654 MAY_LJMP(luaL_checklstring(L, 2, &len));
2655 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002656 lua_pushinteger(L, 0);
2657
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002658 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002659}
2660
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002661/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002662 * his process by cleaning the buffer. The result is a replacement
2663 * of the current data. It returns the length of the writed string,
2664 * or -1 if the channel is closed or if the buffer size is too
2665 * little for the data.
2666 */
2667__LJMP static int hlua_channel_set(lua_State *L)
2668{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002669 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002670
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002671 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002672 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002673 lua_pushinteger(L, 0);
2674
Willy Tarreau47860ed2015-03-10 14:07:50 +01002675 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002676
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002677 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002678}
2679
2680/* Append data in the output side of the buffer. This data is immediatly
2681 * sent. The fcuntion returns the ammount of data writed. If the buffer
2682 * cannot contains the data, the function yield. The function returns -1
2683 * if the channel is closed.
2684 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002685__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002686{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002687 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002688 size_t len;
2689 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2690 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2691 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002692 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002693
Willy Tarreau47860ed2015-03-10 14:07:50 +01002694 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002695 lua_pushinteger(L, -1);
2696 return 1;
2697 }
2698
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002699 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2700 * the request buffer if its not required.
2701 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002702 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002703 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002704 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002705 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002706 }
2707 }
2708
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002709 /* the writed data will be immediatly sent, so we can check
2710 * the avalaible space without taking in account the reserve.
2711 * The reserve is guaranted for the processing of incoming
2712 * data, because the buffer will be flushed.
2713 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002714 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002715
2716 /* If there are no space avalaible, and the output buffer is empty.
2717 * in this case, we cannot add more data, so we cannot yield,
2718 * we return the amount of copyied data.
2719 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002720 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002721 return 1;
2722
2723 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002724 if (max > len - l)
2725 max = len - l;
2726
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002727 /* The buffer avalaible size may be not contiguous. This test
2728 * detects a non contiguous buffer and realign it.
2729 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002730 if (bi_space_for_replace(chn->buf) < max)
2731 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002732
2733 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002734 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002735
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002736 /* buffer replace considers that the input part is filled.
2737 * so, I must forward these new data in the output part.
2738 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002739 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002740
2741 l += max;
2742 lua_pop(L, 1);
2743 lua_pushinteger(L, l);
2744
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002745 /* If there are no space avalaible, and the output buffer is empty.
2746 * in this case, we cannot add more data, so we cannot yield,
2747 * we return the amount of copyied data.
2748 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002749 max = chn->buf->size - buffer_len(chn->buf);
2750 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002751 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002752
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002753 if (l < len) {
2754 /* If we are waiting for space in the response buffer, we
2755 * must set the flag WAKERESWR. This flag required the task
2756 * wake up if any activity is detected on the response buffer.
2757 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002758 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002759 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002760 else
2761 HLUA_SET_WAKEREQWR(hlua);
2762 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002763 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002764
2765 return 1;
2766}
2767
2768/* Just a wraper of "_hlua_channel_send". This wrapper permits
2769 * yield the LUA process, and resume it without checking the
2770 * input arguments.
2771 */
2772__LJMP static int hlua_channel_send(lua_State *L)
2773{
2774 MAY_LJMP(check_args(L, 2, "send"));
2775 lua_pushinteger(L, 0);
2776
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002777 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002778}
2779
2780/* This function forward and amount of butes. The data pass from
2781 * the input side of the buffer to the output side, and can be
2782 * forwarded. This function never fails.
2783 *
2784 * The Lua function takes an amount of bytes to be forwarded in
2785 * imput. It returns the number of bytes forwarded.
2786 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002787__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002788{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002789 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002790 int len;
2791 int l;
2792 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002793 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002794
2795 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2796 len = MAY_LJMP(luaL_checkinteger(L, 2));
2797 l = MAY_LJMP(luaL_checkinteger(L, -1));
2798
2799 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002800 if (max > chn->buf->i)
2801 max = chn->buf->i;
2802 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002803 l += max;
2804
2805 lua_pop(L, 1);
2806 lua_pushinteger(L, l);
2807
2808 /* Check if it miss bytes to forward. */
2809 if (l < len) {
2810 /* The the input channel or the output channel are closed, we
2811 * must return the amount of data forwarded.
2812 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002813 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002814 return 1;
2815
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002816 /* If we are waiting for space data in the response buffer, we
2817 * must set the flag WAKERESWR. This flag required the task
2818 * wake up if any activity is detected on the response buffer.
2819 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002820 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002821 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002822 else
2823 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002824
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002825 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002826 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002827 }
2828
2829 return 1;
2830}
2831
2832/* Just check the input and prepare the stack for the previous
2833 * function "hlua_channel_forward_yield"
2834 */
2835__LJMP static int hlua_channel_forward(lua_State *L)
2836{
2837 MAY_LJMP(check_args(L, 2, "forward"));
2838 MAY_LJMP(hlua_checkchannel(L, 1));
2839 MAY_LJMP(luaL_checkinteger(L, 2));
2840
2841 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002842 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002843}
2844
2845/* Just returns the number of bytes available in the input
2846 * side of the buffer. This function never fails.
2847 */
2848__LJMP static int hlua_channel_get_in_len(lua_State *L)
2849{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002850 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002851
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002852 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002853 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002854 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002855 return 1;
2856}
2857
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01002858/* Returns true if the channel is full. */
2859__LJMP static int hlua_channel_is_full(lua_State *L)
2860{
2861 struct channel *chn;
2862 int rem;
2863
2864 MAY_LJMP(check_args(L, 1, "is_full"));
2865 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2866
2867 rem = chn->buf->size;
2868 rem -= chn->buf->o; /* Output size */
2869 rem -= chn->buf->i; /* Input size */
2870 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
2871
2872 lua_pushboolean(L, rem <= 0);
2873 return 1;
2874}
2875
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002876/* Just returns the number of bytes available in the output
2877 * side of the buffer. This function never fails.
2878 */
2879__LJMP static int hlua_channel_get_out_len(lua_State *L)
2880{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002881 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002882
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002883 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002884 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002885 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002886 return 1;
2887}
2888
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002889/*
2890 *
2891 *
2892 * Class Fetches
2893 *
2894 *
2895 */
2896
2897/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002898 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002899 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002900__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002901{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002902 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002903}
2904
2905/* This function creates and push in the stack a fetch object according
2906 * with a current TXN.
2907 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002908static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002909{
Willy Tarreau7073c472015-04-06 11:15:40 +02002910 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002911
2912 /* Check stack size. */
2913 if (!lua_checkstack(L, 3))
2914 return 0;
2915
2916 /* Create the object: obj[0] = userdata.
2917 * Note that the base of the Fetches object is the
2918 * transaction object.
2919 */
2920 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002921 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002922 lua_rawseti(L, -2, 0);
2923
Willy Tarreau7073c472015-04-06 11:15:40 +02002924 hsmp->s = txn->s;
2925 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01002926 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002927 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002928
2929 /* Pop a class sesison metatable and affect it to the userdata. */
2930 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2931 lua_setmetatable(L, -2);
2932
2933 return 1;
2934}
2935
2936/* This function is an LUA binding. It is called with each sample-fetch.
2937 * It uses closure argument to store the associated sample-fetch. It
2938 * returns only one argument or throws an error. An error is thrown
2939 * only if an error is encountered during the argument parsing. If
2940 * the "sample-fetch" function fails, nil is returned.
2941 */
2942__LJMP static int hlua_run_sample_fetch(lua_State *L)
2943{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002944 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002945 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002946 struct arg args[ARGM_NBARGS + 1];
2947 int i;
2948 struct sample smp;
2949
2950 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002951 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002952
2953 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002954 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002955
Thierry FOURNIERca988662015-12-20 18:43:03 +01002956 /* Check execution authorization. */
2957 if (f->use & SMP_USE_HTTP_ANY &&
2958 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
2959 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
2960 "is not available in Lua services", f->kw);
2961 WILL_LJMP(lua_error(L));
2962 }
2963
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002964 /* Get extra arguments. */
2965 for (i = 0; i < lua_gettop(L) - 1; i++) {
2966 if (i >= ARGM_NBARGS)
2967 break;
2968 hlua_lua2arg(L, i + 2, &args[i]);
2969 }
2970 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01002971 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002972
2973 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002974 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002975
2976 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002977 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002978 lua_pushfstring(L, "error in arguments");
2979 WILL_LJMP(lua_error(L));
2980 }
2981
2982 /* Initialise the sample. */
2983 memset(&smp, 0, sizeof(smp));
2984
2985 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01002986 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02002987 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002988 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002989 lua_pushstring(L, "");
2990 else
2991 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002992 return 1;
2993 }
2994
2995 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002996 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002997 hlua_smp2lua_str(L, &smp);
2998 else
2999 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003000 return 1;
3001}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003002
3003/*
3004 *
3005 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003006 * Class Converters
3007 *
3008 *
3009 */
3010
3011/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003012 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003013 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003014__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003015{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003016 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003017}
3018
3019/* This function creates and push in the stack a Converters object
3020 * according with a current TXN.
3021 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003022static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003023{
Willy Tarreau7073c472015-04-06 11:15:40 +02003024 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003025
3026 /* Check stack size. */
3027 if (!lua_checkstack(L, 3))
3028 return 0;
3029
3030 /* Create the object: obj[0] = userdata.
3031 * Note that the base of the Converters object is the
3032 * same than the TXN object.
3033 */
3034 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003035 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003036 lua_rawseti(L, -2, 0);
3037
Willy Tarreau7073c472015-04-06 11:15:40 +02003038 hsmp->s = txn->s;
3039 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003040 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003041 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003042
Willy Tarreau87b09662015-04-03 00:22:06 +02003043 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003044 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3045 lua_setmetatable(L, -2);
3046
3047 return 1;
3048}
3049
3050/* This function is an LUA binding. It is called with each converter.
3051 * It uses closure argument to store the associated converter. It
3052 * returns only one argument or throws an error. An error is thrown
3053 * only if an error is encountered during the argument parsing. If
3054 * the converter function function fails, nil is returned.
3055 */
3056__LJMP static int hlua_run_sample_conv(lua_State *L)
3057{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003058 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003059 struct sample_conv *conv;
3060 struct arg args[ARGM_NBARGS + 1];
3061 int i;
3062 struct sample smp;
3063
3064 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003065 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003066
3067 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003068 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003069
3070 /* Get extra arguments. */
3071 for (i = 0; i < lua_gettop(L) - 2; i++) {
3072 if (i >= ARGM_NBARGS)
3073 break;
3074 hlua_lua2arg(L, i + 3, &args[i]);
3075 }
3076 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003077 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003078
3079 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003080 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003081
3082 /* Run the special args checker. */
3083 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3084 hlua_pusherror(L, "error in arguments");
3085 WILL_LJMP(lua_error(L));
3086 }
3087
3088 /* Initialise the sample. */
3089 if (!hlua_lua2smp(L, 2, &smp)) {
3090 hlua_pusherror(L, "error in the input argument");
3091 WILL_LJMP(lua_error(L));
3092 }
3093
Willy Tarreau1777ea62016-03-10 16:15:46 +01003094 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3095
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003096 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003097 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003098 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003099 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003100 WILL_LJMP(lua_error(L));
3101 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003102 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3103 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003104 hlua_pusherror(L, "error during the input argument casting");
3105 WILL_LJMP(lua_error(L));
3106 }
3107
3108 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003109 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003110 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003111 lua_pushstring(L, "");
3112 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003113 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003114 return 1;
3115 }
3116
3117 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003118 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003119 hlua_smp2lua_str(L, &smp);
3120 else
3121 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003122 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003123}
3124
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003125/*
3126 *
3127 *
3128 * Class AppletTCP
3129 *
3130 *
3131 */
3132
3133/* Returns a struct hlua_txn if the stack entry "ud" is
3134 * a class stream, otherwise it throws an error.
3135 */
3136__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3137{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003138 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003139}
3140
3141/* This function creates and push in the stack an Applet object
3142 * according with a current TXN.
3143 */
3144static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3145{
3146 struct hlua_appctx *appctx;
3147 struct stream_interface *si = ctx->owner;
3148 struct stream *s = si_strm(si);
3149 struct proxy *p = s->be;
3150
3151 /* Check stack size. */
3152 if (!lua_checkstack(L, 3))
3153 return 0;
3154
3155 /* Create the object: obj[0] = userdata.
3156 * Note that the base of the Converters object is the
3157 * same than the TXN object.
3158 */
3159 lua_newtable(L);
3160 appctx = lua_newuserdata(L, sizeof(*appctx));
3161 lua_rawseti(L, -2, 0);
3162 appctx->appctx = ctx;
3163 appctx->htxn.s = s;
3164 appctx->htxn.p = p;
3165
3166 /* Create the "f" field that contains a list of fetches. */
3167 lua_pushstring(L, "f");
3168 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3169 return 0;
3170 lua_settable(L, -3);
3171
3172 /* Create the "sf" field that contains a list of stringsafe fetches. */
3173 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003174 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003175 return 0;
3176 lua_settable(L, -3);
3177
3178 /* Create the "c" field that contains a list of converters. */
3179 lua_pushstring(L, "c");
3180 if (!hlua_converters_new(L, &appctx->htxn, 0))
3181 return 0;
3182 lua_settable(L, -3);
3183
3184 /* Create the "sc" field that contains a list of stringsafe converters. */
3185 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003186 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003187 return 0;
3188 lua_settable(L, -3);
3189
3190 /* Pop a class stream metatable and affect it to the table. */
3191 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3192 lua_setmetatable(L, -2);
3193
3194 return 1;
3195}
3196
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003197__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3198{
3199 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3200 struct stream *s = appctx->htxn.s;
3201 struct hlua *hlua = &s->hlua;
3202
3203 MAY_LJMP(check_args(L, 2, "set_priv"));
3204
3205 /* Remove previous value. */
3206 if (hlua->Mref != -1)
3207 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3208
3209 /* Get and store new value. */
3210 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3211 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3212
3213 return 0;
3214}
3215
3216__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3217{
3218 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3219 struct stream *s = appctx->htxn.s;
3220 struct hlua *hlua = &s->hlua;
3221
3222 /* Push configuration index in the stack. */
3223 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3224
3225 return 1;
3226}
3227
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003228/* If expected data not yet available, it returns a yield. This function
3229 * consumes the data in the buffer. It returns a string containing the
3230 * data. This string can be empty.
3231 */
3232__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3233{
3234 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3235 struct stream_interface *si = appctx->appctx->owner;
3236 int ret;
3237 char *blk1;
3238 int len1;
3239 char *blk2;
3240 int len2;
3241
3242 /* Read the maximum amount of data avalaible. */
3243 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3244
3245 /* Data not yet avalaible. return yield. */
3246 if (ret == 0) {
3247 si_applet_cant_get(si);
3248 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3249 }
3250
3251 /* End of data: commit the total strings and return. */
3252 if (ret < 0) {
3253 luaL_pushresult(&appctx->b);
3254 return 1;
3255 }
3256
3257 /* Ensure that the block 2 length is usable. */
3258 if (ret == 1)
3259 len2 = 0;
3260
3261 /* dont check the max length read and dont check. */
3262 luaL_addlstring(&appctx->b, blk1, len1);
3263 luaL_addlstring(&appctx->b, blk2, len2);
3264
3265 /* Consume input channel output buffer data. */
3266 bo_skip(si_oc(si), len1 + len2);
3267 luaL_pushresult(&appctx->b);
3268 return 1;
3269}
3270
3271/* Check arguments for the fucntion "hlua_channel_get_yield". */
3272__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3273{
3274 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3275
3276 /* Initialise the string catenation. */
3277 luaL_buffinit(L, &appctx->b);
3278
3279 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3280}
3281
3282/* If expected data not yet available, it returns a yield. This function
3283 * consumes the data in the buffer. It returns a string containing the
3284 * data. This string can be empty.
3285 */
3286__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3287{
3288 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3289 struct stream_interface *si = appctx->appctx->owner;
3290 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3291 int ret;
3292 char *blk1;
3293 int len1;
3294 char *blk2;
3295 int len2;
3296
3297 /* Read the maximum amount of data avalaible. */
3298 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3299
3300 /* Data not yet avalaible. return yield. */
3301 if (ret == 0) {
3302 si_applet_cant_get(si);
3303 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3304 }
3305
3306 /* End of data: commit the total strings and return. */
3307 if (ret < 0) {
3308 luaL_pushresult(&appctx->b);
3309 return 1;
3310 }
3311
3312 /* Ensure that the block 2 length is usable. */
3313 if (ret == 1)
3314 len2 = 0;
3315
3316 if (len == -1) {
3317
3318 /* If len == -1, catenate all the data avalaile and
3319 * yield because we want to get all the data until
3320 * the end of data stream.
3321 */
3322 luaL_addlstring(&appctx->b, blk1, len1);
3323 luaL_addlstring(&appctx->b, blk2, len2);
3324 bo_skip(si_oc(si), len1 + len2);
3325 si_applet_cant_get(si);
3326 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3327
3328 } else {
3329
3330 /* Copy the fisrt block caping to the length required. */
3331 if (len1 > len)
3332 len1 = len;
3333 luaL_addlstring(&appctx->b, blk1, len1);
3334 len -= len1;
3335
3336 /* Copy the second block. */
3337 if (len2 > len)
3338 len2 = len;
3339 luaL_addlstring(&appctx->b, blk2, len2);
3340 len -= len2;
3341
3342 /* Consume input channel output buffer data. */
3343 bo_skip(si_oc(si), len1 + len2);
3344
3345 /* If we are no other data avalaible, yield waiting for new data. */
3346 if (len > 0) {
3347 lua_pushinteger(L, len);
3348 lua_replace(L, 2);
3349 si_applet_cant_get(si);
3350 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3351 }
3352
3353 /* return the result. */
3354 luaL_pushresult(&appctx->b);
3355 return 1;
3356 }
3357
3358 /* we never executes this */
3359 hlua_pusherror(L, "Lua: internal error");
3360 WILL_LJMP(lua_error(L));
3361 return 0;
3362}
3363
3364/* Check arguments for the fucntion "hlua_channel_get_yield". */
3365__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3366{
3367 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3368 int len = -1;
3369
3370 if (lua_gettop(L) > 2)
3371 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3372 if (lua_gettop(L) >= 2) {
3373 len = MAY_LJMP(luaL_checkinteger(L, 2));
3374 lua_pop(L, 1);
3375 }
3376
3377 /* Confirm or set the required length */
3378 lua_pushinteger(L, len);
3379
3380 /* Initialise the string catenation. */
3381 luaL_buffinit(L, &appctx->b);
3382
3383 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3384}
3385
3386/* Append data in the output side of the buffer. This data is immediatly
3387 * sent. The fcuntion returns the ammount of data writed. If the buffer
3388 * cannot contains the data, the function yield. The function returns -1
3389 * if the channel is closed.
3390 */
3391__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3392{
3393 size_t len;
3394 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3395 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3396 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3397 struct stream_interface *si = appctx->appctx->owner;
3398 struct channel *chn = si_ic(si);
3399 int max;
3400
3401 /* Get the max amount of data which can write as input in the channel. */
3402 max = channel_recv_max(chn);
3403 if (max > (len - l))
3404 max = len - l;
3405
3406 /* Copy data. */
3407 bi_putblk(chn, str + l, max);
3408
3409 /* update counters. */
3410 l += max;
3411 lua_pop(L, 1);
3412 lua_pushinteger(L, l);
3413
3414 /* If some data is not send, declares the situation to the
3415 * applet, and returns a yield.
3416 */
3417 if (l < len) {
3418 si_applet_cant_put(si);
3419 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3420 }
3421
3422 return 1;
3423}
3424
3425/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3426 * yield the LUA process, and resume it without checking the
3427 * input arguments.
3428 */
3429__LJMP static int hlua_applet_tcp_send(lua_State *L)
3430{
3431 MAY_LJMP(check_args(L, 2, "send"));
3432 lua_pushinteger(L, 0);
3433
3434 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3435}
3436
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003437/*
3438 *
3439 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003440 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003441 *
3442 *
3443 */
3444
3445/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003446 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003447 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003448__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003449{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003450 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003451}
3452
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003453/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003454 * according with a current TXN.
3455 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003456static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003457{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003458 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003459 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003460 struct stream_interface *si = ctx->owner;
3461 struct stream *s = si_strm(si);
3462 struct proxy *px = s->be;
3463 struct http_txn *txn = s->txn;
3464 const char *path;
3465 const char *end;
3466 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003467
3468 /* Check stack size. */
3469 if (!lua_checkstack(L, 3))
3470 return 0;
3471
3472 /* Create the object: obj[0] = userdata.
3473 * Note that the base of the Converters object is the
3474 * same than the TXN object.
3475 */
3476 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003477 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003478 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003479 appctx->appctx = ctx;
3480 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
3481 appctx->htxn.s = s;
3482 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003483
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003484 /* Create the "f" field that contains a list of fetches. */
3485 lua_pushstring(L, "f");
3486 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3487 return 0;
3488 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003489
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003490 /* Create the "sf" field that contains a list of stringsafe fetches. */
3491 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003492 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003493 return 0;
3494 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003495
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003496 /* Create the "c" field that contains a list of converters. */
3497 lua_pushstring(L, "c");
3498 if (!hlua_converters_new(L, &appctx->htxn, 0))
3499 return 0;
3500 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003501
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003502 /* Create the "sc" field that contains a list of stringsafe converters. */
3503 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003504 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003505 return 0;
3506 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003507
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003508 /* Stores the request method. */
3509 lua_pushstring(L, "method");
3510 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3511 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003512
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003513 /* Stores the http version. */
3514 lua_pushstring(L, "version");
3515 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3516 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003517
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003518 /* creates an array of headers. hlua_http_get_headers() crates and push
3519 * the array on the top of the stack.
3520 */
3521 lua_pushstring(L, "headers");
3522 htxn.s = s;
3523 htxn.p = px;
3524 htxn.dir = SMP_OPT_DIR_REQ;
3525 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3526 return 0;
3527 lua_settable(L, -3);
3528
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003529 /* Get path and qs */
3530 path = http_get_path(txn);
3531 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3532 p = path;
3533 while (p < end && *p != '?')
3534 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003535
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003536 /* Stores the request path. */
3537 lua_pushstring(L, "path");
3538 lua_pushlstring(L, path, p - path);
3539 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003540
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003541 /* Stores the query string. */
3542 lua_pushstring(L, "qs");
3543 if (*p == '?')
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003544 p++;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003545 lua_pushlstring(L, p, end - p);
3546 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003547
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003548 /* Stores the request path. */
3549 lua_pushstring(L, "length");
3550 lua_pushinteger(L, txn->req.body_len);
3551 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003552
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003553 /* Create an array of HTTP request headers. */
3554 lua_pushstring(L, "headers");
3555 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3556 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003557
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003558 /* Create an empty array of HTTP request headers. */
3559 lua_pushstring(L, "response");
3560 lua_newtable(L);
3561 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003562
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003563 /* Pop a class stream metatable and affect it to the table. */
3564 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3565 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003566
3567 return 1;
3568}
3569
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003570__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3571{
3572 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3573 struct stream *s = appctx->htxn.s;
3574 struct hlua *hlua = &s->hlua;
3575
3576 MAY_LJMP(check_args(L, 2, "set_priv"));
3577
3578 /* Remove previous value. */
3579 if (hlua->Mref != -1)
3580 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3581
3582 /* Get and store new value. */
3583 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3584 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3585
3586 return 0;
3587}
3588
3589__LJMP static int hlua_applet_http_get_priv(lua_State *L)
3590{
3591 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3592 struct stream *s = appctx->htxn.s;
3593 struct hlua *hlua = &s->hlua;
3594
3595 /* Push configuration index in the stack. */
3596 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3597
3598 return 1;
3599}
3600
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003601/* If expected data not yet available, it returns a yield. This function
3602 * consumes the data in the buffer. It returns a string containing the
3603 * data. This string can be empty.
3604 */
3605__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003606{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003607 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3608 struct stream_interface *si = appctx->appctx->owner;
3609 struct channel *chn = si_ic(si);
3610 int ret;
3611 char *blk1;
3612 int len1;
3613 char *blk2;
3614 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003615
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003616 /* Maybe we cant send a 100-continue ? */
3617 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3618 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3619 /* if ret == -2 or -3 the channel closed or the message si too
3620 * big for the buffers. We cant send anything. So, we ignoring
3621 * the error, considers that the 100-continue is sent, and try
3622 * to receive.
3623 * If ret is -1, we dont have room in the buffer, so we yield.
3624 */
3625 if (ret == -1) {
3626 si_applet_cant_put(si);
3627 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3628 }
3629 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3630 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003631
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003632 /* Check for the end of the data. */
3633 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3634 luaL_pushresult(&appctx->b);
3635 return 1;
3636 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003637
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003638 /* Read the maximum amount of data avalaible. */
3639 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003640
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003641 /* Data not yet avalaible. return yield. */
3642 if (ret == 0) {
3643 si_applet_cant_get(si);
3644 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3645 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003646
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003647 /* End of data: commit the total strings and return. */
3648 if (ret < 0) {
3649 luaL_pushresult(&appctx->b);
3650 return 1;
3651 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003652
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003653 /* Ensure that the block 2 length is usable. */
3654 if (ret == 1)
3655 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003656
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003657 /* Copy the fisrt block caping to the length required. */
3658 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3659 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3660 luaL_addlstring(&appctx->b, blk1, len1);
3661 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003662
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003663 /* Copy the second block. */
3664 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3665 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3666 luaL_addlstring(&appctx->b, blk2, len2);
3667 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003668
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003669 /* Consume input channel output buffer data. */
3670 bo_skip(si_oc(si), len1 + len2);
3671 luaL_pushresult(&appctx->b);
3672 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003673}
3674
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003675/* Check arguments for the fucntion "hlua_channel_get_yield". */
3676__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003677{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003678 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003679
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003680 /* Initialise the string catenation. */
3681 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003682
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003683 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003684}
3685
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003686/* If expected data not yet available, it returns a yield. This function
3687 * consumes the data in the buffer. It returns a string containing the
3688 * data. This string can be empty.
3689 */
3690__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003691{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003692 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3693 struct stream_interface *si = appctx->appctx->owner;
3694 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3695 struct channel *chn = si_ic(si);
3696 int ret;
3697 char *blk1;
3698 int len1;
3699 char *blk2;
3700 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003701
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003702 /* Maybe we cant send a 100-continue ? */
3703 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3704 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3705 /* if ret == -2 or -3 the channel closed or the message si too
3706 * big for the buffers. We cant send anything. So, we ignoring
3707 * the error, considers that the 100-continue is sent, and try
3708 * to receive.
3709 * If ret is -1, we dont have room in the buffer, so we yield.
3710 */
3711 if (ret == -1) {
3712 si_applet_cant_put(si);
3713 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3714 }
3715 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3716 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003717
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003718 /* Read the maximum amount of data avalaible. */
3719 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003720
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003721 /* Data not yet avalaible. return yield. */
3722 if (ret == 0) {
3723 si_applet_cant_get(si);
3724 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3725 }
3726
3727 /* End of data: commit the total strings and return. */
3728 if (ret < 0) {
3729 luaL_pushresult(&appctx->b);
3730 return 1;
3731 }
3732
3733 /* Ensure that the block 2 length is usable. */
3734 if (ret == 1)
3735 len2 = 0;
3736
3737 /* Copy the fisrt block caping to the length required. */
3738 if (len1 > len)
3739 len1 = len;
3740 luaL_addlstring(&appctx->b, blk1, len1);
3741 len -= len1;
3742
3743 /* Copy the second block. */
3744 if (len2 > len)
3745 len2 = len;
3746 luaL_addlstring(&appctx->b, blk2, len2);
3747 len -= len2;
3748
3749 /* Consume input channel output buffer data. */
3750 bo_skip(si_oc(si), len1 + len2);
3751 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
3752 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
3753
3754 /* If we are no other data avalaible, yield waiting for new data. */
3755 if (len > 0) {
3756 lua_pushinteger(L, len);
3757 lua_replace(L, 2);
3758 si_applet_cant_get(si);
3759 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3760 }
3761
3762 /* return the result. */
3763 luaL_pushresult(&appctx->b);
3764 return 1;
3765}
3766
3767/* Check arguments for the fucntion "hlua_channel_get_yield". */
3768__LJMP static int hlua_applet_http_recv(lua_State *L)
3769{
3770 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3771 int len = -1;
3772
3773 /* Check arguments. */
3774 if (lua_gettop(L) > 2)
3775 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3776 if (lua_gettop(L) >= 2) {
3777 len = MAY_LJMP(luaL_checkinteger(L, 2));
3778 lua_pop(L, 1);
3779 }
3780
3781 /* Check the required length */
3782 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3783 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3784 lua_pushinteger(L, len);
3785
3786 /* Initialise the string catenation. */
3787 luaL_buffinit(L, &appctx->b);
3788
3789 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
3790}
3791
3792/* Append data in the output side of the buffer. This data is immediatly
3793 * sent. The fcuntion returns the ammount of data writed. If the buffer
3794 * cannot contains the data, the function yield. The function returns -1
3795 * if the channel is closed.
3796 */
3797__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
3798{
3799 size_t len;
3800 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3801 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3802 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3803 struct stream_interface *si = appctx->appctx->owner;
3804 struct channel *chn = si_ic(si);
3805 int max;
3806
3807 /* Get the max amount of data which can write as input in the channel. */
3808 max = channel_recv_max(chn);
3809 if (max > (len - l))
3810 max = len - l;
3811
3812 /* Copy data. */
3813 bi_putblk(chn, str + l, max);
3814
3815 /* update counters. */
3816 l += max;
3817 lua_pop(L, 1);
3818 lua_pushinteger(L, l);
3819
3820 /* If some data is not send, declares the situation to the
3821 * applet, and returns a yield.
3822 */
3823 if (l < len) {
3824 si_applet_cant_put(si);
3825 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
3826 }
3827
3828 return 1;
3829}
3830
3831/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
3832 * yield the LUA process, and resume it without checking the
3833 * input arguments.
3834 */
3835__LJMP static int hlua_applet_http_send(lua_State *L)
3836{
3837 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3838 size_t len;
3839 char hex[10];
3840
3841 MAY_LJMP(luaL_checklstring(L, 2, &len));
3842
3843 /* If transfer encoding chunked is selected, we surround the data
3844 * by chunk data.
3845 */
3846 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
3847 snprintf(hex, 9, "%x", (unsigned int)len);
3848 lua_pushfstring(L, "%s\r\n", hex);
3849 lua_insert(L, 2); /* swap the last 2 entries. */
3850 lua_pushstring(L, "\r\n");
3851 lua_concat(L, 3);
3852 }
3853
3854 /* This interger is used for followinf the amount of data sent. */
3855 lua_pushinteger(L, 0);
3856
3857 /* We want to send some data. Headers must be sent. */
3858 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
3859 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
3860 WILL_LJMP(lua_error(L));
3861 }
3862
3863 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
3864}
3865
3866__LJMP static int hlua_applet_http_addheader(lua_State *L)
3867{
3868 const char *name;
3869 int ret;
3870
3871 MAY_LJMP(hlua_checkapplet_http(L, 1));
3872 name = MAY_LJMP(luaL_checkstring(L, 2));
3873 MAY_LJMP(luaL_checkstring(L, 3));
3874
3875 /* Push in the stack the "response" entry. */
3876 ret = lua_getfield(L, 1, "response");
3877 if (ret != LUA_TTABLE) {
3878 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
3879 "is expected as an array. %s found", lua_typename(L, ret));
3880 WILL_LJMP(lua_error(L));
3881 }
3882
3883 /* check if the header is already registered if it is not
3884 * the case, register it.
3885 */
3886 ret = lua_getfield(L, -1, name);
3887 if (ret == LUA_TNIL) {
3888
3889 /* Entry not found. */
3890 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
3891
3892 /* Insert the new header name in the array in the top of the stack.
3893 * It left the new array in the top of the stack.
3894 */
3895 lua_newtable(L);
3896 lua_pushvalue(L, 2);
3897 lua_pushvalue(L, -2);
3898 lua_settable(L, -4);
3899
3900 } else if (ret != LUA_TTABLE) {
3901
3902 /* corruption error. */
3903 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
3904 "is expected as an array. %s found", name, lua_typename(L, ret));
3905 WILL_LJMP(lua_error(L));
3906 }
3907
3908 /* Now the top od thestack is an array of values. We push
3909 * the header value as new entry.
3910 */
3911 lua_pushvalue(L, 3);
3912 ret = lua_rawlen(L, -2);
3913 lua_rawseti(L, -2, ret + 1);
3914 lua_pushboolean(L, 1);
3915 return 1;
3916}
3917
3918__LJMP static int hlua_applet_http_status(lua_State *L)
3919{
3920 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3921 int status = MAY_LJMP(luaL_checkinteger(L, 2));
3922
3923 if (status < 100 || status > 599) {
3924 lua_pushboolean(L, 0);
3925 return 1;
3926 }
3927
3928 appctx->appctx->ctx.hlua_apphttp.status = status;
3929 lua_pushboolean(L, 1);
3930 return 1;
3931}
3932
3933/* We will build the status line and the headers of the HTTP response.
3934 * We will try send at once if its not possible, we give back the hand
3935 * waiting for more room.
3936 */
3937__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
3938{
3939 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3940 struct stream_interface *si = appctx->appctx->owner;
3941 struct channel *chn = si_ic(si);
3942 int ret;
3943 size_t len;
3944 const char *msg;
3945
3946 /* Get the message as the first argument on the stack. */
3947 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
3948
3949 /* Send the message at once. */
3950 ret = bi_putblk(chn, msg, len);
3951
3952 /* if ret == -2 or -3 the channel closed or the message si too
3953 * big for the buffers.
3954 */
3955 if (ret == -2 || ret == -3) {
3956 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
3957 WILL_LJMP(lua_error(L));
3958 }
3959
3960 /* If ret is -1, we dont have room in the buffer, so we yield. */
3961 if (ret == -1) {
3962 si_applet_cant_put(si);
3963 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
3964 }
3965
3966 /* Headers sent, set the flag. */
3967 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
3968 return 0;
3969}
3970
3971__LJMP static int hlua_applet_http_start_response(lua_State *L)
3972{
3973 struct chunk *tmp = get_trash_chunk();
3974 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003975 const char *name;
3976 const char *value;
3977 int id;
3978 int hdr_connection = 0;
3979 int hdr_contentlength = -1;
3980 int hdr_chunked = 0;
3981
3982 /* Use the same http version than the request. */
3983 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01003984 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003985 appctx->appctx->ctx.hlua_apphttp.status,
3986 get_reason(appctx->appctx->ctx.hlua_apphttp.status));
3987
3988 /* Get the array associated to the field "response" in the object AppletHTTP. */
3989 lua_pushvalue(L, 0);
3990 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
3991 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
3992 appctx->appctx->rule->arg.hlua_rule->fcn.name);
3993 WILL_LJMP(lua_error(L));
3994 }
3995
3996 /* Browse the list of headers. */
3997 lua_pushnil(L);
3998 while(lua_next(L, -2) != 0) {
3999
4000 /* We expect a string as -2. */
4001 if (lua_type(L, -2) != LUA_TSTRING) {
4002 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4003 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4004 lua_typename(L, lua_type(L, -2)));
4005 WILL_LJMP(lua_error(L));
4006 }
4007 name = lua_tostring(L, -2);
4008
4009 /* We expect an array as -1. */
4010 if (lua_type(L, -1) != LUA_TTABLE) {
4011 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4012 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4013 name,
4014 lua_typename(L, lua_type(L, -1)));
4015 WILL_LJMP(lua_error(L));
4016 }
4017
4018 /* Browse the table who is on the top of the stack. */
4019 lua_pushnil(L);
4020 while(lua_next(L, -2) != 0) {
4021
4022 /* We expect a number as -2. */
4023 if (lua_type(L, -2) != LUA_TNUMBER) {
4024 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4025 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4026 name,
4027 lua_typename(L, lua_type(L, -2)));
4028 WILL_LJMP(lua_error(L));
4029 }
4030 id = lua_tointeger(L, -2);
4031
4032 /* We expect a string as -2. */
4033 if (lua_type(L, -1) != LUA_TSTRING) {
4034 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4035 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4036 name, id,
4037 lua_typename(L, lua_type(L, -1)));
4038 WILL_LJMP(lua_error(L));
4039 }
4040 value = lua_tostring(L, -1);
4041
4042 /* Catenate a new header. */
4043 chunk_appendf(tmp, "%s: %s\r\n", name, value);
4044
4045 /* Protocol checks. */
4046
4047 /* Check if the header conneciton is present. */
4048 if (strcasecmp("connection", name) == 0)
4049 hdr_connection = 1;
4050
4051 /* Copy the header content length. The length conversion
4052 * is done without control. If it contains a ad value, this
4053 * is not our problem.
4054 */
4055 if (strcasecmp("content-length", name) == 0)
4056 hdr_contentlength = atoi(value);
4057
4058 /* Check if the client annouces a transfer-encoding chunked it self. */
4059 if (strcasecmp("transfer-encoding", name) == 0 &&
4060 strcasecmp("chunked", value) == 0)
4061 hdr_chunked = 1;
4062
4063 /* Remove the array from the stack, and get next element with a remaining string. */
4064 lua_pop(L, 1);
4065 }
4066
4067 /* Remove the array from the stack, and get next element with a remaining string. */
4068 lua_pop(L, 1);
4069 }
4070
4071 /* If the http protocol version is 1.1, we expect an header "connection" set
4072 * to "close" to be HAProxy/keeplive compliant. Otherwise, we expect nothing.
4073 * If the header conneciton is present, don't change it, if it is not present,
4074 * we must set.
4075 *
4076 * we set a "connection: close" header for ensuring that the keepalive will be
4077 * respected by haproxy. HAProcy considers that the application cloe the connection
4078 * and it keep the connection from the client open.
4079 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004080 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 && !hdr_connection)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004081 chunk_appendf(tmp, "Connection: close\r\n");
4082
4083 /* If we dont have a content-length set, we must announce a transfer enconding
4084 * chunked. This is required by haproxy for the keepalive compliance.
4085 * If the applet annouce a transfer-encoding chunked itslef, don't
4086 * do anything.
4087 */
4088 if (hdr_contentlength == -1 && hdr_chunked == 0) {
4089 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4090 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4091 }
4092
4093 /* Finalize headers. */
4094 chunk_appendf(tmp, "\r\n");
4095
4096 /* Remove the last entry and the array of headers */
4097 lua_pop(L, 2);
4098
4099 /* Push the headers block. */
4100 lua_pushlstring(L, tmp->str, tmp->len);
4101
4102 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4103}
4104
4105/*
4106 *
4107 *
4108 * Class HTTP
4109 *
4110 *
4111 */
4112
4113/* Returns a struct hlua_txn if the stack entry "ud" is
4114 * a class stream, otherwise it throws an error.
4115 */
4116__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4117{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004118 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004119}
4120
4121/* This function creates and push in the stack a HTTP object
4122 * according with a current TXN.
4123 */
4124static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4125{
4126 struct hlua_txn *htxn;
4127
4128 /* Check stack size. */
4129 if (!lua_checkstack(L, 3))
4130 return 0;
4131
4132 /* Create the object: obj[0] = userdata.
4133 * Note that the base of the Converters object is the
4134 * same than the TXN object.
4135 */
4136 lua_newtable(L);
4137 htxn = lua_newuserdata(L, sizeof(*htxn));
4138 lua_rawseti(L, -2, 0);
4139
4140 htxn->s = txn->s;
4141 htxn->p = txn->p;
4142
4143 /* Pop a class stream metatable and affect it to the table. */
4144 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4145 lua_setmetatable(L, -2);
4146
4147 return 1;
4148}
4149
4150/* This function creates ans returns an array of HTTP headers.
4151 * This function does not fails. It is used as wrapper with the
4152 * 2 following functions.
4153 */
4154__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4155{
4156 const char *cur_ptr, *cur_next, *p;
4157 int old_idx, cur_idx;
4158 struct hdr_idx_elem *cur_hdr;
4159 const char *hn, *hv;
4160 int hnl, hvl;
4161 int type;
4162 const char *in;
4163 char *out;
4164 int len;
4165
4166 /* Create the table. */
4167 lua_newtable(L);
4168
4169 if (!htxn->s->txn)
4170 return 1;
4171
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004172 /* Check if a valid response is parsed */
4173 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4174 return 1;
4175
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004176 /* Build array of headers. */
4177 old_idx = 0;
4178 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4179
4180 while (1) {
4181 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4182 if (!cur_idx)
4183 break;
4184 old_idx = cur_idx;
4185
4186 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4187 cur_ptr = cur_next;
4188 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4189
4190 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4191 * and the next header starts at cur_next. We'll check
4192 * this header in the list as well as against the default
4193 * rule.
4194 */
4195
4196 /* look for ': *'. */
4197 hn = cur_ptr;
4198 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4199 if (p >= cur_ptr+cur_hdr->len)
4200 continue;
4201 hnl = p - hn;
4202 p++;
4203 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4204 p++;
4205 if (p >= cur_ptr+cur_hdr->len)
4206 continue;
4207 hv = p;
4208 hvl = cur_ptr+cur_hdr->len-p;
4209
4210 /* Lowercase the key. Don't check the size of trash, it have
4211 * the size of one buffer and the input data contains in one
4212 * buffer.
4213 */
4214 out = trash.str;
4215 for (in=hn; in<hn+hnl; in++, out++)
4216 *out = tolower(*in);
4217 *out = '\0';
4218
4219 /* Check for existing entry:
4220 * assume that the table is on the top of the stack, and
4221 * push the key in the stack, the function lua_gettable()
4222 * perform the lookup.
4223 */
4224 lua_pushlstring(L, trash.str, hnl);
4225 lua_gettable(L, -2);
4226 type = lua_type(L, -1);
4227
4228 switch (type) {
4229 case LUA_TNIL:
4230 /* Table not found, create it. */
4231 lua_pop(L, 1); /* remove the nil value. */
4232 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4233 lua_newtable(L); /* create and push empty table. */
4234 lua_pushlstring(L, hv, hvl); /* push header value. */
4235 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4236 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4237 break;
4238
4239 case LUA_TTABLE:
4240 /* Entry found: push the value in the table. */
4241 len = lua_rawlen(L, -1);
4242 lua_pushlstring(L, hv, hvl); /* push header value. */
4243 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4244 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4245 break;
4246
4247 default:
4248 /* Other cases are errors. */
4249 hlua_pusherror(L, "internal error during the parsing of headers.");
4250 WILL_LJMP(lua_error(L));
4251 }
4252 }
4253
4254 return 1;
4255}
4256
4257__LJMP static int hlua_http_req_get_headers(lua_State *L)
4258{
4259 struct hlua_txn *htxn;
4260
4261 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4262 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4263
4264 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4265}
4266
4267__LJMP static int hlua_http_res_get_headers(lua_State *L)
4268{
4269 struct hlua_txn *htxn;
4270
4271 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4272 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4273
4274 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4275}
4276
4277/* This function replace full header, or just a value in
4278 * the request or in the response. It is a wrapper fir the
4279 * 4 following functions.
4280 */
4281__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4282 struct http_msg *msg, int action)
4283{
4284 size_t name_len;
4285 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4286 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4287 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4288 struct my_regex re;
4289
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004290 /* Check if a valid response is parsed */
4291 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4292 return 0;
4293
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004294 if (!regex_comp(reg, &re, 1, 1, NULL))
4295 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4296
4297 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4298 regex_free(&re);
4299 return 0;
4300}
4301
4302__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4303{
4304 struct hlua_txn *htxn;
4305
4306 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4307 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4308
4309 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4310}
4311
4312__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4313{
4314 struct hlua_txn *htxn;
4315
4316 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4317 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4318
4319 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4320}
4321
4322__LJMP static int hlua_http_req_rep_val(lua_State *L)
4323{
4324 struct hlua_txn *htxn;
4325
4326 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4327 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4328
4329 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4330}
4331
4332__LJMP static int hlua_http_res_rep_val(lua_State *L)
4333{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004334 struct hlua_txn *htxn;
4335
4336 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4337 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4338
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004339 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004340}
4341
4342/* This function deletes all the occurences of an header.
4343 * It is a wrapper for the 2 following functions.
4344 */
4345__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4346{
4347 size_t len;
4348 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4349 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004350 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004351
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004352 /* Check if a valid response is parsed */
4353 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4354 return 0;
4355
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004356 ctx.idx = 0;
4357 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4358 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4359 return 0;
4360}
4361
4362__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4363{
4364 struct hlua_txn *htxn;
4365
4366 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4367 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4368
Willy Tarreaueee5b512015-04-03 23:46:31 +02004369 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004370}
4371
4372__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4373{
4374 struct hlua_txn *htxn;
4375
4376 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4377 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4378
Willy Tarreaueee5b512015-04-03 23:46:31 +02004379 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004380}
4381
4382/* This function adds an header. It is a wrapper used by
4383 * the 2 following functions.
4384 */
4385__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4386{
4387 size_t name_len;
4388 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4389 size_t value_len;
4390 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4391 char *p;
4392
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004393 /* Check if a valid message is parsed */
4394 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4395 return 0;
4396
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004397 /* Check length. */
4398 trash.len = value_len + name_len + 2;
4399 if (trash.len > trash.size)
4400 return 0;
4401
4402 /* Creates the header string. */
4403 p = trash.str;
4404 memcpy(p, name, name_len);
4405 p += name_len;
4406 *p = ':';
4407 p++;
4408 *p = ' ';
4409 p++;
4410 memcpy(p, value, value_len);
4411
Willy Tarreaueee5b512015-04-03 23:46:31 +02004412 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004413 trash.str, trash.len) != 0);
4414
4415 return 0;
4416}
4417
4418__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4419{
4420 struct hlua_txn *htxn;
4421
4422 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4423 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4424
Willy Tarreaueee5b512015-04-03 23:46:31 +02004425 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004426}
4427
4428__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4429{
4430 struct hlua_txn *htxn;
4431
4432 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4433 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4434
Willy Tarreaueee5b512015-04-03 23:46:31 +02004435 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004436}
4437
4438static int hlua_http_req_set_hdr(lua_State *L)
4439{
4440 struct hlua_txn *htxn;
4441
4442 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4443 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4444
Willy Tarreaueee5b512015-04-03 23:46:31 +02004445 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4446 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004447}
4448
4449static int hlua_http_res_set_hdr(lua_State *L)
4450{
4451 struct hlua_txn *htxn;
4452
4453 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4454 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4455
Willy Tarreaueee5b512015-04-03 23:46:31 +02004456 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4457 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004458}
4459
4460/* This function set the method. */
4461static int hlua_http_req_set_meth(lua_State *L)
4462{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004463 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004464 size_t name_len;
4465 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004466
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004467 /* Check if a valid request is parsed */
4468 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4469 lua_pushboolean(L, 0);
4470 return 1;
4471 }
4472
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004473 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004474 return 1;
4475}
4476
4477/* This function set the method. */
4478static int hlua_http_req_set_path(lua_State *L)
4479{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004480 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004481 size_t name_len;
4482 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004483
4484 /* Check if a valid request is parsed */
4485 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4486 lua_pushboolean(L, 0);
4487 return 1;
4488 }
4489
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004490 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004491 return 1;
4492}
4493
4494/* This function set the query-string. */
4495static int hlua_http_req_set_query(lua_State *L)
4496{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004497 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004498 size_t name_len;
4499 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004500
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004501 /* Check if a valid request is parsed */
4502 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4503 lua_pushboolean(L, 0);
4504 return 1;
4505 }
4506
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004507 /* Check length. */
4508 if (name_len > trash.size - 1) {
4509 lua_pushboolean(L, 0);
4510 return 1;
4511 }
4512
4513 /* Add the mark question as prefix. */
4514 chunk_reset(&trash);
4515 trash.str[trash.len++] = '?';
4516 memcpy(trash.str + trash.len, name, name_len);
4517 trash.len += name_len;
4518
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004519 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004520 return 1;
4521}
4522
4523/* This function set the uri. */
4524static int hlua_http_req_set_uri(lua_State *L)
4525{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004526 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004527 size_t name_len;
4528 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004529
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004530 /* Check if a valid request is parsed */
4531 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4532 lua_pushboolean(L, 0);
4533 return 1;
4534 }
4535
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004536 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004537 return 1;
4538}
4539
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004540/* This function set the response code. */
4541static int hlua_http_res_set_status(lua_State *L)
4542{
4543 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4544 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
4545
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004546 /* Check if a valid response is parsed */
4547 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4548 return 0;
4549
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004550 http_set_status(code, htxn->s);
4551 return 0;
4552}
4553
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004554/*
4555 *
4556 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004557 * Class TXN
4558 *
4559 *
4560 */
4561
4562/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004563 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004564 */
4565__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4566{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004567 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004568}
4569
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004570__LJMP static int hlua_set_var(lua_State *L)
4571{
4572 struct hlua_txn *htxn;
4573 const char *name;
4574 size_t len;
4575 struct sample smp;
4576
4577 MAY_LJMP(check_args(L, 3, "set_var"));
4578
4579 /* It is useles to retrieve the stream, but this function
4580 * runs only in a stream context.
4581 */
4582 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4583 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4584
4585 /* Converts the third argument in a sample. */
4586 hlua_lua2smp(L, 3, &smp);
4587
4588 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01004589 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004590 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004591 return 0;
4592}
4593
Christopher Faulet85d79c92016-11-09 16:54:56 +01004594__LJMP static int hlua_unset_var(lua_State *L)
4595{
4596 struct hlua_txn *htxn;
4597 const char *name;
4598 size_t len;
4599 struct sample smp;
4600
4601 MAY_LJMP(check_args(L, 2, "unset_var"));
4602
4603 /* It is useles to retrieve the stream, but this function
4604 * runs only in a stream context.
4605 */
4606 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4607 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4608
4609 /* Unset the variable. */
4610 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
4611 vars_unset_by_name(name, len, &smp);
4612 return 0;
4613}
4614
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004615__LJMP static int hlua_get_var(lua_State *L)
4616{
4617 struct hlua_txn *htxn;
4618 const char *name;
4619 size_t len;
4620 struct sample smp;
4621
4622 MAY_LJMP(check_args(L, 2, "get_var"));
4623
4624 /* It is useles to retrieve the stream, but this function
4625 * runs only in a stream context.
4626 */
4627 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4628 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4629
Willy Tarreau7560dd42016-03-10 16:28:58 +01004630 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004631 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004632 lua_pushnil(L);
4633 return 1;
4634 }
4635
4636 return hlua_smp2lua(L, &smp);
4637}
4638
Willy Tarreau59551662015-03-10 14:23:13 +01004639__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004640{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004641 struct hlua *hlua;
4642
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004643 MAY_LJMP(check_args(L, 2, "set_priv"));
4644
Willy Tarreau87b09662015-04-03 00:22:06 +02004645 /* It is useles to retrieve the stream, but this function
4646 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004647 */
4648 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004649 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004650
4651 /* Remove previous value. */
4652 if (hlua->Mref != -1)
4653 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
4654
4655 /* Get and store new value. */
4656 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4657 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4658
4659 return 0;
4660}
4661
Willy Tarreau59551662015-03-10 14:23:13 +01004662__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004663{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004664 struct hlua *hlua;
4665
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004666 MAY_LJMP(check_args(L, 1, "get_priv"));
4667
Willy Tarreau87b09662015-04-03 00:22:06 +02004668 /* It is useles to retrieve the stream, but this function
4669 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004670 */
4671 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004672 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004673
4674 /* Push configuration index in the stack. */
4675 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4676
4677 return 1;
4678}
4679
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004680/* Create stack entry containing a class TXN. This function
4681 * return 0 if the stack does not contains free slots,
4682 * otherwise it returns 1.
4683 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004684static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004685{
Willy Tarreaude491382015-04-06 11:04:28 +02004686 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004687
4688 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004689 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004690 return 0;
4691
4692 /* NOTE: The allocation never fails. The failure
4693 * throw an error, and the function never returns.
4694 * if the throw is not avalaible, the process is aborted.
4695 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004696 /* Create the object: obj[0] = userdata. */
4697 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004698 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004699 lua_rawseti(L, -2, 0);
4700
Willy Tarreaude491382015-04-06 11:04:28 +02004701 htxn->s = s;
4702 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004703 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004704 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004705
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004706 /* Create the "f" field that contains a list of fetches. */
4707 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004708 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004709 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004710 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004711
4712 /* Create the "sf" field that contains a list of stringsafe fetches. */
4713 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004714 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004715 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004716 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004717
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004718 /* Create the "c" field that contains a list of converters. */
4719 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004720 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004721 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004722 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004723
4724 /* Create the "sc" field that contains a list of stringsafe converters. */
4725 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004726 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004727 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004728 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004729
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004730 /* Create the "req" field that contains the request channel object. */
4731 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004732 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004733 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004734 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004735
4736 /* Create the "res" field that contains the response channel object. */
4737 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004738 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004739 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004740 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004741
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004742 /* Creates the HTTP object is the current proxy allows http. */
4743 lua_pushstring(L, "http");
4744 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02004745 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004746 return 0;
4747 }
4748 else
4749 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004750 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004751
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004752 /* Pop a class sesison metatable and affect it to the userdata. */
4753 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
4754 lua_setmetatable(L, -2);
4755
4756 return 1;
4757}
4758
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004759__LJMP static int hlua_txn_deflog(lua_State *L)
4760{
4761 const char *msg;
4762 struct hlua_txn *htxn;
4763
4764 MAY_LJMP(check_args(L, 2, "deflog"));
4765 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4766 msg = MAY_LJMP(luaL_checkstring(L, 2));
4767
4768 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
4769 return 0;
4770}
4771
4772__LJMP static int hlua_txn_log(lua_State *L)
4773{
4774 int level;
4775 const char *msg;
4776 struct hlua_txn *htxn;
4777
4778 MAY_LJMP(check_args(L, 3, "log"));
4779 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4780 level = MAY_LJMP(luaL_checkinteger(L, 2));
4781 msg = MAY_LJMP(luaL_checkstring(L, 3));
4782
4783 if (level < 0 || level >= NB_LOG_LEVELS)
4784 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4785
4786 hlua_sendlog(htxn->s->be, level, msg);
4787 return 0;
4788}
4789
4790__LJMP static int hlua_txn_log_debug(lua_State *L)
4791{
4792 const char *msg;
4793 struct hlua_txn *htxn;
4794
4795 MAY_LJMP(check_args(L, 2, "Debug"));
4796 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4797 msg = MAY_LJMP(luaL_checkstring(L, 2));
4798 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
4799 return 0;
4800}
4801
4802__LJMP static int hlua_txn_log_info(lua_State *L)
4803{
4804 const char *msg;
4805 struct hlua_txn *htxn;
4806
4807 MAY_LJMP(check_args(L, 2, "Info"));
4808 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4809 msg = MAY_LJMP(luaL_checkstring(L, 2));
4810 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
4811 return 0;
4812}
4813
4814__LJMP static int hlua_txn_log_warning(lua_State *L)
4815{
4816 const char *msg;
4817 struct hlua_txn *htxn;
4818
4819 MAY_LJMP(check_args(L, 2, "Warning"));
4820 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4821 msg = MAY_LJMP(luaL_checkstring(L, 2));
4822 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
4823 return 0;
4824}
4825
4826__LJMP static int hlua_txn_log_alert(lua_State *L)
4827{
4828 const char *msg;
4829 struct hlua_txn *htxn;
4830
4831 MAY_LJMP(check_args(L, 2, "Alert"));
4832 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4833 msg = MAY_LJMP(luaL_checkstring(L, 2));
4834 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
4835 return 0;
4836}
4837
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004838__LJMP static int hlua_txn_set_loglevel(lua_State *L)
4839{
4840 struct hlua_txn *htxn;
4841 int ll;
4842
4843 MAY_LJMP(check_args(L, 2, "set_loglevel"));
4844 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4845 ll = MAY_LJMP(luaL_checkinteger(L, 2));
4846
4847 if (ll < 0 || ll > 7)
4848 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
4849
4850 htxn->s->logs.level = ll;
4851 return 0;
4852}
4853
4854__LJMP static int hlua_txn_set_tos(lua_State *L)
4855{
4856 struct hlua_txn *htxn;
4857 struct connection *cli_conn;
4858 int tos;
4859
4860 MAY_LJMP(check_args(L, 2, "set_tos"));
4861 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4862 tos = MAY_LJMP(luaL_checkinteger(L, 2));
4863
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004864 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Vincent Bernat6e615892016-05-18 16:17:44 +02004865 inet_set_tos(cli_conn->t.sock.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004866
4867 return 0;
4868}
4869
4870__LJMP static int hlua_txn_set_mark(lua_State *L)
4871{
4872#ifdef SO_MARK
4873 struct hlua_txn *htxn;
4874 struct connection *cli_conn;
4875 int mark;
4876
4877 MAY_LJMP(check_args(L, 2, "set_mark"));
4878 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4879 mark = MAY_LJMP(luaL_checkinteger(L, 2));
4880
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004881 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02004882 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004883#endif
4884 return 0;
4885}
4886
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004887/* This function is an Lua binding that send pending data
4888 * to the client, and close the stream interface.
4889 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004890__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004891{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004892 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02004893 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01004894 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004895
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004896 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004897 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02004898 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004899
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004900 /* If the flags NOTERM is set, we cannot terminate the http
4901 * session, so we just end the execution of the current
4902 * lua code.
4903 */
4904 if (htxn->flags & HLUA_TXN_NOTERM) {
4905 WILL_LJMP(hlua_done(L));
4906 return 0;
4907 }
4908
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004909 ic = &htxn->s->req;
4910 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01004911
Willy Tarreau630ef452015-08-28 10:06:15 +02004912 if (htxn->s->txn) {
4913 /* HTTP mode, let's stay in sync with the stream */
4914 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
4915 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
4916 htxn->s->txn->req.sov = 0;
4917 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
4918 oc->analysers = AN_RES_HTTP_XFER_BODY;
4919 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
4920 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
4921
Willy Tarreau630ef452015-08-28 10:06:15 +02004922 /* Note that if we want to support keep-alive, we need
4923 * to bypass the close/shutr_now calls below, but that
4924 * may only be done if the HTTP request was already
4925 * processed and the connection header is known (ie
4926 * not during TCP rules).
4927 */
4928 }
4929
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004930 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01004931 channel_abort(ic);
4932 channel_auto_close(ic);
4933 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004934
4935 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01004936 channel_auto_read(oc);
4937 channel_auto_close(oc);
4938 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004939
Willy Tarreau0458b082015-08-28 09:40:04 +02004940 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004941
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02004942 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004943 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004944 return 0;
4945}
4946
4947__LJMP static int hlua_log(lua_State *L)
4948{
4949 int level;
4950 const char *msg;
4951
4952 MAY_LJMP(check_args(L, 2, "log"));
4953 level = MAY_LJMP(luaL_checkinteger(L, 1));
4954 msg = MAY_LJMP(luaL_checkstring(L, 2));
4955
4956 if (level < 0 || level >= NB_LOG_LEVELS)
4957 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4958
4959 hlua_sendlog(NULL, level, msg);
4960 return 0;
4961}
4962
4963__LJMP static int hlua_log_debug(lua_State *L)
4964{
4965 const char *msg;
4966
4967 MAY_LJMP(check_args(L, 1, "debug"));
4968 msg = MAY_LJMP(luaL_checkstring(L, 1));
4969 hlua_sendlog(NULL, LOG_DEBUG, msg);
4970 return 0;
4971}
4972
4973__LJMP static int hlua_log_info(lua_State *L)
4974{
4975 const char *msg;
4976
4977 MAY_LJMP(check_args(L, 1, "info"));
4978 msg = MAY_LJMP(luaL_checkstring(L, 1));
4979 hlua_sendlog(NULL, LOG_INFO, msg);
4980 return 0;
4981}
4982
4983__LJMP static int hlua_log_warning(lua_State *L)
4984{
4985 const char *msg;
4986
4987 MAY_LJMP(check_args(L, 1, "warning"));
4988 msg = MAY_LJMP(luaL_checkstring(L, 1));
4989 hlua_sendlog(NULL, LOG_WARNING, msg);
4990 return 0;
4991}
4992
4993__LJMP static int hlua_log_alert(lua_State *L)
4994{
4995 const char *msg;
4996
4997 MAY_LJMP(check_args(L, 1, "alert"));
4998 msg = MAY_LJMP(luaL_checkstring(L, 1));
4999 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005000 return 0;
5001}
5002
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005003__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005004{
5005 int wakeup_ms = lua_tointeger(L, -1);
5006 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005007 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005008 return 0;
5009}
5010
5011__LJMP static int hlua_sleep(lua_State *L)
5012{
5013 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005014 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005015
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005016 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005017
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005018 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005019 wakeup_ms = tick_add(now_ms, delay);
5020 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005021
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005022 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5023 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005024}
5025
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005026__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005027{
5028 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005029 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005030
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005031 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005032
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005033 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005034 wakeup_ms = tick_add(now_ms, delay);
5035 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005036
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005037 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5038 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005039}
5040
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005041/* This functionis an LUA binding. it permits to give back
5042 * the hand at the HAProxy scheduler. It is used when the
5043 * LUA processing consumes a lot of time.
5044 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005045__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005046{
5047 return 0;
5048}
5049
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005050__LJMP static int hlua_yield(lua_State *L)
5051{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005052 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5053 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005054}
5055
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005056/* This function change the nice of the currently executed
5057 * task. It is used set low or high priority at the current
5058 * task.
5059 */
Willy Tarreau59551662015-03-10 14:23:13 +01005060__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005061{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005062 struct hlua *hlua;
5063 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005064
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005065 MAY_LJMP(check_args(L, 1, "set_nice"));
5066 hlua = hlua_gethlua(L);
5067 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005068
5069 /* If he task is not set, I'm in a start mode. */
5070 if (!hlua || !hlua->task)
5071 return 0;
5072
5073 if (nice < -1024)
5074 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005075 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005076 nice = 1024;
5077
5078 hlua->task->nice = nice;
5079 return 0;
5080}
5081
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005082/* This function is used as a calback of a task. It is called by the
5083 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5084 * return an E_AGAIN signal, the emmiter of this signal must set a
5085 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005086 *
5087 * Task wrapper are longjmp safe because the only one Lua code
5088 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005089 */
5090static struct task *hlua_process_task(struct task *task)
5091{
5092 struct hlua *hlua = task->context;
5093 enum hlua_exec status;
5094
5095 /* We need to remove the task from the wait queue before executing
5096 * the Lua code because we don't know if it needs to wait for
5097 * another timer or not in the case of E_AGAIN.
5098 */
5099 task_delete(task);
5100
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005101 /* If it is the first call to the task, we must initialize the
5102 * execution timeouts.
5103 */
5104 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005105 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005106
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005107 /* Execute the Lua code. */
5108 status = hlua_ctx_resume(hlua, 1);
5109
5110 switch (status) {
5111 /* finished or yield */
5112 case HLUA_E_OK:
5113 hlua_ctx_destroy(hlua);
5114 task_delete(task);
5115 task_free(task);
5116 break;
5117
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005118 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5119 if (hlua->wake_time != TICK_ETERNITY)
5120 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005121 break;
5122
5123 /* finished with error. */
5124 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005125 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005126 hlua_ctx_destroy(hlua);
5127 task_delete(task);
5128 task_free(task);
5129 break;
5130
5131 case HLUA_E_ERR:
5132 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005133 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005134 hlua_ctx_destroy(hlua);
5135 task_delete(task);
5136 task_free(task);
5137 break;
5138 }
5139 return NULL;
5140}
5141
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005142/* This function is an LUA binding that register LUA function to be
5143 * executed after the HAProxy configuration parsing and before the
5144 * HAProxy scheduler starts. This function expect only one LUA
5145 * argument that is a function. This function returns nothing, but
5146 * throws if an error is encountered.
5147 */
5148__LJMP static int hlua_register_init(lua_State *L)
5149{
5150 struct hlua_init_function *init;
5151 int ref;
5152
5153 MAY_LJMP(check_args(L, 1, "register_init"));
5154
5155 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5156
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005157 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005158 if (!init)
5159 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5160
5161 init->function_ref = ref;
5162 LIST_ADDQ(&hlua_init_functions, &init->l);
5163 return 0;
5164}
5165
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005166/* This functio is an LUA binding. It permits to register a task
5167 * executed in parallel of the main HAroxy activity. The task is
5168 * created and it is set in the HAProxy scheduler. It can be called
5169 * from the "init" section, "post init" or during the runtime.
5170 *
5171 * Lua prototype:
5172 *
5173 * <none> core.register_task(<function>)
5174 */
5175static int hlua_register_task(lua_State *L)
5176{
5177 struct hlua *hlua;
5178 struct task *task;
5179 int ref;
5180
5181 MAY_LJMP(check_args(L, 1, "register_task"));
5182
5183 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5184
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005185 hlua = calloc(1, sizeof(*hlua));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005186 if (!hlua)
5187 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5188
5189 task = task_new();
5190 task->context = hlua;
5191 task->process = hlua_process_task;
5192
5193 if (!hlua_ctx_init(hlua, task))
5194 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5195
5196 /* Restore the function in the stack. */
5197 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5198 hlua->nargs = 0;
5199
5200 /* Schedule task. */
5201 task_schedule(task, now_ms);
5202
5203 return 0;
5204}
5205
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005206/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5207 * doesn't allow "yield" functions because the HAProxy engine cannot
5208 * resume converters.
5209 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005210static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005211{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005212 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005213 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005214 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005215
Willy Tarreaube508f12016-03-10 11:47:01 +01005216 if (!stream)
5217 return 0;
5218
Willy Tarreau87b09662015-04-03 00:22:06 +02005219 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005220 * Lua context can be not initialized. This behavior
5221 * permits to save performances because a systematic
5222 * Lua initialization cause 5% performances loss.
5223 */
Willy Tarreau87b09662015-04-03 00:22:06 +02005224 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005225 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005226 return 0;
5227 }
5228
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005229 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005230 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005231
5232 /* The following Lua calls can fail. */
5233 if (!SET_SAFE_LJMP(stream->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005234 if (lua_type(stream->hlua.T, -1) == LUA_TSTRING)
5235 error = lua_tostring(stream->hlua.T, -1);
5236 else
5237 error = "critical error";
5238 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005239 return 0;
5240 }
5241
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005242 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005243 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005244 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005245 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005246 return 0;
5247 }
5248
5249 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005250 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005251
5252 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005253 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005254 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005255 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005256 return 0;
5257 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005258 hlua_smp2lua(stream->hlua.T, smp);
Thierry Fournier4a53bfd2016-05-27 16:35:01 +02005259 stream->hlua.nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005260
5261 /* push keywords in the stack. */
5262 if (arg_p) {
5263 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02005264 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005265 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005266 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005267 return 0;
5268 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005269 hlua_arg2lua(stream->hlua.T, arg_p);
5270 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005271 }
5272 }
5273
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005274 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005275 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005276
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005277 /* At this point the execution is safe. */
5278 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005279 }
5280
5281 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005282 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005283 /* finished. */
5284 case HLUA_E_OK:
5285 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005286 hlua_lua2smp(stream->hlua.T, -1, smp);
5287 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005288 return 1;
5289
5290 /* yield. */
5291 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005292 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005293 return 0;
5294
5295 /* finished with error. */
5296 case HLUA_E_ERRMSG:
5297 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005298 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
5299 fcn->name, lua_tostring(stream->hlua.T, -1));
Willy Tarreau87b09662015-04-03 00:22:06 +02005300 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005301 return 0;
5302
5303 case HLUA_E_ERR:
5304 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005305 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005306
5307 default:
5308 return 0;
5309 }
5310}
5311
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005312/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5313 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005314 * resume sample-fetches. This function will be called by the sample
5315 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005316 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005317static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5318 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005319{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005320 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005321 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005322 const char *error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005323
Willy Tarreaube508f12016-03-10 11:47:01 +01005324 if (!stream)
5325 return 0;
5326
Willy Tarreau87b09662015-04-03 00:22:06 +02005327 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005328 * Lua context can be not initialized. This behavior
5329 * permits to save performances because a systematic
5330 * Lua initialization cause 5% performances loss.
5331 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005332 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005333 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005334 return 0;
5335 }
5336
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005337 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005338 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005339
5340 /* The following Lua calls can fail. */
5341 if (!SET_SAFE_LJMP(stream->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005342 if (lua_type(stream->hlua.T, -1) == LUA_TSTRING)
5343 error = lua_tostring(stream->hlua.T, -1);
5344 else
5345 error = "critical error";
5346 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005347 return 0;
5348 }
5349
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005350 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005351 if (!lua_checkstack(stream->hlua.T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005352 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005353 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005354 return 0;
5355 }
5356
5357 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005358 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005359
5360 /* push arguments in the stack. */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005361 if (!hlua_txn_new(stream->hlua.T, stream, smp->px, smp->opt & SMP_OPT_DIR,
5362 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005363 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005364 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005365 return 0;
5366 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005367 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005368
5369 /* push keywords in the stack. */
5370 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5371 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005372 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005373 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005374 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005375 return 0;
5376 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005377 hlua_arg2lua(stream->hlua.T, arg_p);
5378 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005379 }
5380
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005381 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005382 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005383
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005384 /* At this point the execution is safe. */
5385 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005386 }
5387
5388 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005389 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005390 /* finished. */
5391 case HLUA_E_OK:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005392 if (!hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005393 return 0;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005394 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005395 hlua_lua2smp(stream->hlua.T, -1, smp);
5396 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005397
5398 /* Set the end of execution flag. */
5399 smp->flags &= ~SMP_F_MAY_CHANGE;
5400 return 1;
5401
5402 /* yield. */
5403 case HLUA_E_AGAIN:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005404 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005405 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005406 return 0;
5407
5408 /* finished with error. */
5409 case HLUA_E_ERRMSG:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005410 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005411 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005412 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
5413 fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005414 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005415 return 0;
5416
5417 case HLUA_E_ERR:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005418 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005419 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005420 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005421
5422 default:
5423 return 0;
5424 }
5425}
5426
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005427/* This function is an LUA binding used for registering
5428 * "sample-conv" functions. It expects a converter name used
5429 * in the haproxy configuration file, and an LUA function.
5430 */
5431__LJMP static int hlua_register_converters(lua_State *L)
5432{
5433 struct sample_conv_kw_list *sck;
5434 const char *name;
5435 int ref;
5436 int len;
5437 struct hlua_function *fcn;
5438
5439 MAY_LJMP(check_args(L, 2, "register_converters"));
5440
5441 /* First argument : converter name. */
5442 name = MAY_LJMP(luaL_checkstring(L, 1));
5443
5444 /* Second argument : lua function. */
5445 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5446
5447 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005448 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005449 if (!sck)
5450 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005451 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005452 if (!fcn)
5453 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5454
5455 /* Fill fcn. */
5456 fcn->name = strdup(name);
5457 if (!fcn->name)
5458 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5459 fcn->function_ref = ref;
5460
5461 /* List head */
5462 sck->list.n = sck->list.p = NULL;
5463
5464 /* converter keyword. */
5465 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005466 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005467 if (!sck->kw[0].kw)
5468 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5469
5470 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5471 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005472 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 +01005473 sck->kw[0].val_args = NULL;
5474 sck->kw[0].in_type = SMP_T_STR;
5475 sck->kw[0].out_type = SMP_T_STR;
5476 sck->kw[0].private = fcn;
5477
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005478 /* Register this new converter */
5479 sample_register_convs(sck);
5480
5481 return 0;
5482}
5483
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005484/* This fucntion is an LUA binding used for registering
5485 * "sample-fetch" functions. It expects a converter name used
5486 * in the haproxy configuration file, and an LUA function.
5487 */
5488__LJMP static int hlua_register_fetches(lua_State *L)
5489{
5490 const char *name;
5491 int ref;
5492 int len;
5493 struct sample_fetch_kw_list *sfk;
5494 struct hlua_function *fcn;
5495
5496 MAY_LJMP(check_args(L, 2, "register_fetches"));
5497
5498 /* First argument : sample-fetch name. */
5499 name = MAY_LJMP(luaL_checkstring(L, 1));
5500
5501 /* Second argument : lua function. */
5502 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5503
5504 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005505 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005506 if (!sfk)
5507 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005508 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005509 if (!fcn)
5510 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5511
5512 /* Fill fcn. */
5513 fcn->name = strdup(name);
5514 if (!fcn->name)
5515 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5516 fcn->function_ref = ref;
5517
5518 /* List head */
5519 sfk->list.n = sfk->list.p = NULL;
5520
5521 /* sample-fetch keyword. */
5522 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005523 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005524 if (!sfk->kw[0].kw)
5525 return luaL_error(L, "lua out of memory error.");
5526
5527 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5528 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005529 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 +01005530 sfk->kw[0].val_args = NULL;
5531 sfk->kw[0].out_type = SMP_T_STR;
5532 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5533 sfk->kw[0].val = 0;
5534 sfk->kw[0].private = fcn;
5535
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005536 /* Register this new fetch. */
5537 sample_register_fetches(sfk);
5538
5539 return 0;
5540}
5541
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005542/* This function is a wrapper to execute each LUA function declared
5543 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005544 * return ACT_RET_CONT if the processing is finished (with or without
5545 * error) and return ACT_RET_YIELD if the function must be called again
5546 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005547 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005548static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005549 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005550{
5551 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005552 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005553 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005554 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005555
5556 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01005557 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
5558 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
5559 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
5560 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005561 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005562 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005563 return ACT_RET_CONT;
5564 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005565
Willy Tarreau87b09662015-04-03 00:22:06 +02005566 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005567 * Lua context can be not initialized. This behavior
5568 * permits to save performances because a systematic
5569 * Lua initialization cause 5% performances loss.
5570 */
5571 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005572 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005573 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005574 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005575 }
5576
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005577 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01005578 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005579
5580 /* The following Lua calls can fail. */
5581 if (!SET_SAFE_LJMP(s->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005582 if (lua_type(s->hlua.T, -1) == LUA_TSTRING)
5583 error = lua_tostring(s->hlua.T, -1);
5584 else
5585 error = "critical error";
5586 SEND_ERR(px, "Lua function '%s': %s.\n",
5587 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005588 return ACT_RET_CONT;
5589 }
5590
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005591 /* Check stack available size. */
5592 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005593 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005594 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005595 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005596 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005597 }
5598
5599 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005600 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005601
Willy Tarreau87b09662015-04-03 00:22:06 +02005602 /* Create and and push object stream in the stack. */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005603 if (!hlua_txn_new(s->hlua.T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005604 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005605 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005606 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005607 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005608 }
5609 s->hlua.nargs = 1;
5610
5611 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005612 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005613 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005614 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005615 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005616 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005617 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005618 }
5619 lua_pushstring(s->hlua.T, *arg);
5620 s->hlua.nargs++;
5621 }
5622
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005623 /* Now the execution is safe. */
5624 RESET_SAFE_LJMP(s->hlua.T);
5625
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005626 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005627 s->hlua.max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005628 }
5629
5630 /* Execute the function. */
Willy Tarreau528192d2015-09-27 10:48:01 +02005631 switch (hlua_ctx_resume(&s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005632 /* finished. */
5633 case HLUA_E_OK:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005634 if (!hlua_check_proto(s, dir))
5635 return ACT_RET_ERR;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005636 if (s->hlua.flags & HLUA_STOP)
5637 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005638 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005639
5640 /* yield. */
5641 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005642 /* Set timeout in the required channel. */
5643 if (s->hlua.wake_time != TICK_ETERNITY) {
5644 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005645 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005646 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005647 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005648 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005649 /* Some actions can be wake up when a "write" event
5650 * is detected on a response channel. This is useful
5651 * only for actions targetted on the requests.
5652 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01005653 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005654 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005655 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005656 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005657 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01005658 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005659 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005660 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005661
5662 /* finished with error. */
5663 case HLUA_E_ERRMSG:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005664 if (!hlua_check_proto(s, dir))
5665 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005666 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005667 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005668 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005669 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005670 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005671
5672 case HLUA_E_ERR:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005673 if (!hlua_check_proto(s, dir))
5674 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005675 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005676 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005677 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005678
5679 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005680 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005681 }
5682}
5683
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005684struct task *hlua_applet_wakeup(struct task *t)
5685{
5686 struct appctx *ctx = t->context;
5687 struct stream_interface *si = ctx->owner;
5688
5689 /* If the applet is wake up without any expected work, the sheduler
5690 * remove it from the run queue. This flag indicate that the applet
5691 * is waiting for write. If the buffer is full, the main processing
5692 * will send some data and after call the applet, otherwise it call
5693 * the applet ASAP.
5694 */
5695 si_applet_cant_put(si);
5696 appctx_wakeup(ctx);
5697 return NULL;
5698}
5699
5700static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5701{
5702 struct stream_interface *si = ctx->owner;
5703 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5704 struct task *task;
5705 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005706 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005707
5708 HLUA_INIT(hlua);
5709 ctx->ctx.hlua_apptcp.flags = 0;
5710
5711 /* Create task used by signal to wakeup applets. */
5712 task = task_new();
5713 if (!task) {
5714 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5715 ctx->rule->arg.hlua_rule->fcn.name);
5716 return 0;
5717 }
5718 task->nice = 0;
5719 task->context = ctx;
5720 task->process = hlua_applet_wakeup;
5721 ctx->ctx.hlua_apptcp.task = task;
5722
5723 /* In the execution wrappers linked with a stream, the
5724 * Lua context can be not initialized. This behavior
5725 * permits to save performances because a systematic
5726 * Lua initialization cause 5% performances loss.
5727 */
5728 if (!hlua_ctx_init(hlua, task)) {
5729 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
5730 ctx->rule->arg.hlua_rule->fcn.name);
5731 return 0;
5732 }
5733
5734 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005735 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005736
5737 /* The following Lua calls can fail. */
5738 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005739 if (lua_type(hlua->T, -1) == LUA_TSTRING)
5740 error = lua_tostring(hlua->T, -1);
5741 else
5742 error = "critical error";
5743 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
5744 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005745 RESET_SAFE_LJMP(hlua->T);
5746 return 0;
5747 }
5748
5749 /* Check stack available size. */
5750 if (!lua_checkstack(hlua->T, 1)) {
5751 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5752 ctx->rule->arg.hlua_rule->fcn.name);
5753 RESET_SAFE_LJMP(hlua->T);
5754 return 0;
5755 }
5756
5757 /* Restore the function in the stack. */
5758 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5759
5760 /* Create and and push object stream in the stack. */
5761 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
5762 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5763 ctx->rule->arg.hlua_rule->fcn.name);
5764 RESET_SAFE_LJMP(hlua->T);
5765 return 0;
5766 }
5767 hlua->nargs = 1;
5768
5769 /* push keywords in the stack. */
5770 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5771 if (!lua_checkstack(hlua->T, 1)) {
5772 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5773 ctx->rule->arg.hlua_rule->fcn.name);
5774 RESET_SAFE_LJMP(hlua->T);
5775 return 0;
5776 }
5777 lua_pushstring(hlua->T, *arg);
5778 hlua->nargs++;
5779 }
5780
5781 RESET_SAFE_LJMP(hlua->T);
5782
5783 /* Wakeup the applet ASAP. */
5784 si_applet_cant_get(si);
5785 si_applet_cant_put(si);
5786
5787 return 1;
5788}
5789
5790static void hlua_applet_tcp_fct(struct appctx *ctx)
5791{
5792 struct stream_interface *si = ctx->owner;
5793 struct stream *strm = si_strm(si);
5794 struct channel *res = si_ic(si);
5795 struct act_rule *rule = ctx->rule;
5796 struct proxy *px = strm->be;
5797 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5798
5799 /* The applet execution is already done. */
5800 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
5801 return;
5802
5803 /* If the stream is disconnect or closed, ldo nothing. */
5804 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5805 return;
5806
5807 /* Execute the function. */
5808 switch (hlua_ctx_resume(hlua, 1)) {
5809 /* finished. */
5810 case HLUA_E_OK:
5811 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5812
5813 /* log time */
5814 strm->logs.tv_request = now;
5815
5816 /* eat the whole request */
5817 bo_skip(si_oc(si), si_ob(si)->o);
5818 res->flags |= CF_READ_NULL;
5819 si_shutr(si);
5820 return;
5821
5822 /* yield. */
5823 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01005824 if (hlua->wake_time != TICK_ETERNITY)
5825 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005826 return;
5827
5828 /* finished with error. */
5829 case HLUA_E_ERRMSG:
5830 /* Display log. */
5831 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
5832 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
5833 lua_pop(hlua->T, 1);
5834 goto error;
5835
5836 case HLUA_E_ERR:
5837 /* Display log. */
5838 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
5839 rule->arg.hlua_rule->fcn.name);
5840 goto error;
5841
5842 default:
5843 goto error;
5844 }
5845
5846error:
5847
5848 /* For all other cases, just close the stream. */
5849 si_shutw(si);
5850 si_shutr(si);
5851 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5852}
5853
5854static void hlua_applet_tcp_release(struct appctx *ctx)
5855{
5856 task_free(ctx->ctx.hlua_apptcp.task);
5857 ctx->ctx.hlua_apptcp.task = NULL;
5858 hlua_ctx_destroy(&ctx->ctx.hlua_apptcp.hlua);
5859}
5860
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005861/* The function returns 1 if the initialisation is complete, 0 if
5862 * an errors occurs and -1 if more data are required for initializing
5863 * the applet.
5864 */
5865static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5866{
5867 struct stream_interface *si = ctx->owner;
5868 struct channel *req = si_oc(si);
5869 struct http_msg *msg;
5870 struct http_txn *txn;
5871 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5872 char **arg;
5873 struct hdr_ctx hdr;
5874 struct task *task;
5875 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01005876 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005877
5878 /* Wait for a full HTTP request. */
5879 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
5880 if (smp.flags & SMP_F_MAY_CHANGE)
5881 return -1;
5882 return 0;
5883 }
5884 txn = strm->txn;
5885 msg = &txn->req;
5886
Willy Tarreau0078bfc2015-10-07 20:20:28 +02005887 /* We want two things in HTTP mode :
5888 * - enforce server-close mode if we were in keep-alive, so that the
5889 * applet is released after each response ;
5890 * - enable request body transfer to the applet in order to resync
5891 * with the response body.
5892 */
5893 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
5894 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02005895
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005896 HLUA_INIT(hlua);
5897 ctx->ctx.hlua_apphttp.left_bytes = -1;
5898 ctx->ctx.hlua_apphttp.flags = 0;
5899
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01005900 if (txn->req.flags & HTTP_MSGF_VER_11)
5901 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
5902
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005903 /* Create task used by signal to wakeup applets. */
5904 task = task_new();
5905 if (!task) {
5906 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
5907 ctx->rule->arg.hlua_rule->fcn.name);
5908 return 0;
5909 }
5910 task->nice = 0;
5911 task->context = ctx;
5912 task->process = hlua_applet_wakeup;
5913 ctx->ctx.hlua_apphttp.task = task;
5914
5915 /* In the execution wrappers linked with a stream, the
5916 * Lua context can be not initialized. This behavior
5917 * permits to save performances because a systematic
5918 * Lua initialization cause 5% performances loss.
5919 */
5920 if (!hlua_ctx_init(hlua, task)) {
5921 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
5922 ctx->rule->arg.hlua_rule->fcn.name);
5923 return 0;
5924 }
5925
5926 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005927 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005928
5929 /* The following Lua calls can fail. */
5930 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005931 if (lua_type(hlua->T, -1) == LUA_TSTRING)
5932 error = lua_tostring(hlua->T, -1);
5933 else
5934 error = "critical error";
5935 SEND_ERR(px, "Lua applet http '%s': %s.\n",
5936 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005937 return 0;
5938 }
5939
5940 /* Check stack available size. */
5941 if (!lua_checkstack(hlua->T, 1)) {
5942 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5943 ctx->rule->arg.hlua_rule->fcn.name);
5944 RESET_SAFE_LJMP(hlua->T);
5945 return 0;
5946 }
5947
5948 /* Restore the function in the stack. */
5949 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5950
5951 /* Create and and push object stream in the stack. */
5952 if (!hlua_applet_http_new(hlua->T, ctx)) {
5953 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5954 ctx->rule->arg.hlua_rule->fcn.name);
5955 RESET_SAFE_LJMP(hlua->T);
5956 return 0;
5957 }
5958 hlua->nargs = 1;
5959
5960 /* Look for a 100-continue expected. */
5961 if (msg->flags & HTTP_MSGF_VER_11) {
5962 hdr.idx = 0;
5963 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
5964 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
5965 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
5966 }
5967
5968 /* push keywords in the stack. */
5969 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5970 if (!lua_checkstack(hlua->T, 1)) {
5971 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5972 ctx->rule->arg.hlua_rule->fcn.name);
5973 RESET_SAFE_LJMP(hlua->T);
5974 return 0;
5975 }
5976 lua_pushstring(hlua->T, *arg);
5977 hlua->nargs++;
5978 }
5979
5980 RESET_SAFE_LJMP(hlua->T);
5981
5982 /* Wakeup the applet when data is ready for read. */
5983 si_applet_cant_get(si);
5984
5985 return 1;
5986}
5987
5988static void hlua_applet_http_fct(struct appctx *ctx)
5989{
5990 struct stream_interface *si = ctx->owner;
5991 struct stream *strm = si_strm(si);
5992 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005993 struct act_rule *rule = ctx->rule;
5994 struct proxy *px = strm->be;
5995 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5996 char *blk1;
5997 int len1;
5998 char *blk2;
5999 int len2;
6000 int ret;
6001
6002 /* If the stream is disconnect or closed, ldo nothing. */
6003 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6004 return;
6005
6006 /* Set the currently running flag. */
6007 if (!HLUA_IS_RUNNING(hlua) &&
6008 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6009
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006010 /* Wait for full HTTP analysys. */
6011 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6012 si_applet_cant_get(si);
6013 return;
6014 }
6015
6016 /* Store the max amount of bytes that we can read. */
6017 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6018
6019 /* We need to flush the request header. This left the body
6020 * for the Lua.
6021 */
6022
6023 /* Read the maximum amount of data avalaible. */
6024 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
6025 if (ret == -1)
6026 return;
6027
6028 /* No data available, ask for more data. */
6029 if (ret == 1)
6030 len2 = 0;
6031 if (ret == 0)
6032 len1 = 0;
6033 if (len1 + len2 < strm->txn->req.eoh + 2) {
6034 si_applet_cant_get(si);
6035 return;
6036 }
6037
6038 /* skip the requests bytes. */
6039 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
6040 }
6041
6042 /* Executes The applet if it is not done. */
6043 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6044
6045 /* Execute the function. */
6046 switch (hlua_ctx_resume(hlua, 1)) {
6047 /* finished. */
6048 case HLUA_E_OK:
6049 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6050 break;
6051
6052 /* yield. */
6053 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006054 if (hlua->wake_time != TICK_ETERNITY)
6055 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006056 return;
6057
6058 /* finished with error. */
6059 case HLUA_E_ERRMSG:
6060 /* Display log. */
6061 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6062 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6063 lua_pop(hlua->T, 1);
6064 goto error;
6065
6066 case HLUA_E_ERR:
6067 /* Display log. */
6068 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6069 rule->arg.hlua_rule->fcn.name);
6070 goto error;
6071
6072 default:
6073 goto error;
6074 }
6075 }
6076
6077 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6078
6079 /* We must send the final chunk. */
6080 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6081 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6082
6083 /* sent last chunk at once. */
6084 ret = bi_putblk(res, "0\r\n\r\n", 5);
6085
6086 /* critical error. */
6087 if (ret == -2 || ret == -3) {
6088 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6089 rule->arg.hlua_rule->fcn.name);
6090 goto error;
6091 }
6092
6093 /* no enough space error. */
6094 if (ret == -1) {
6095 si_applet_cant_put(si);
6096 return;
6097 }
6098
6099 /* set the last chunk sent. */
6100 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6101 }
6102
6103 /* close the connection. */
6104
6105 /* status / log */
6106 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6107 strm->logs.tv_request = now;
6108
6109 /* eat the whole request */
6110 bo_skip(si_oc(si), si_ob(si)->o);
6111 res->flags |= CF_READ_NULL;
6112 si_shutr(si);
6113
6114 return;
6115 }
6116
6117error:
6118
6119 /* If we are in HTTP mode, and we are not send any
6120 * data, return a 500 server error in best effort:
6121 * if there are no room avalaible in the buffer,
6122 * just close the connection.
6123 */
6124 bi_putblk(res, error_500, strlen(error_500));
6125 if (!(strm->flags & SF_ERR_MASK))
6126 strm->flags |= SF_ERR_RESOURCE;
6127 si_shutw(si);
6128 si_shutr(si);
6129 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6130}
6131
6132static void hlua_applet_http_release(struct appctx *ctx)
6133{
6134 task_free(ctx->ctx.hlua_apphttp.task);
6135 ctx->ctx.hlua_apphttp.task = NULL;
6136 hlua_ctx_destroy(&ctx->ctx.hlua_apphttp.hlua);
6137}
6138
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006139/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6140 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006141 *
6142 * This function can fail with an abort() due to an Lua critical error.
6143 * We are in the configuration parsing process of HAProxy, this abort() is
6144 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006145 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006146static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6147 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006148{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006149 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006150
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006151 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006152 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006153 if (!rule->arg.hlua_rule) {
6154 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006155 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006156 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006157
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006158 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006159 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006160
6161 /* TODO: later accept arguments. */
6162 rule->arg.hlua_rule->args = NULL;
6163
Thierry FOURNIER42148732015-09-02 17:17:33 +02006164 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006165 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006166 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006167}
6168
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006169static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6170 struct act_rule *rule, char **err)
6171{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006172 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006173
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006174 /* HTTP applets are forbidden in tcp-request rules.
6175 * HTTP applet request requires everything initilized by
6176 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6177 * The applet will be immediately initilized, but its before
6178 * the call of this analyzer.
6179 */
6180 if (rule->from != ACT_F_HTTP_REQ) {
6181 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6182 return ACT_RET_PRS_ERR;
6183 }
6184
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006185 /* Memory for the rule. */
6186 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6187 if (!rule->arg.hlua_rule) {
6188 memprintf(err, "out of memory error");
6189 return ACT_RET_PRS_ERR;
6190 }
6191
6192 /* Reference the Lua function and store the reference. */
6193 rule->arg.hlua_rule->fcn = *fcn;
6194
6195 /* TODO: later accept arguments. */
6196 rule->arg.hlua_rule->args = NULL;
6197
6198 /* Add applet pointer in the rule. */
6199 rule->applet.obj_type = OBJ_TYPE_APPLET;
6200 rule->applet.name = fcn->name;
6201 rule->applet.init = hlua_applet_http_init;
6202 rule->applet.fct = hlua_applet_http_fct;
6203 rule->applet.release = hlua_applet_http_release;
6204 rule->applet.timeout = hlua_timeout_applet;
6205
6206 return ACT_RET_PRS_OK;
6207}
6208
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006209/* This function is an LUA binding used for registering
6210 * "sample-conv" functions. It expects a converter name used
6211 * in the haproxy configuration file, and an LUA function.
6212 */
6213__LJMP static int hlua_register_action(lua_State *L)
6214{
6215 struct action_kw_list *akl;
6216 const char *name;
6217 int ref;
6218 int len;
6219 struct hlua_function *fcn;
6220
Thierry FOURNIERed0bdaa2015-12-20 19:51:06 +01006221 MAY_LJMP(check_args(L, 3, "register_action"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006222
6223 /* First argument : converter name. */
6224 name = MAY_LJMP(luaL_checkstring(L, 1));
6225
6226 /* Second argument : environment. */
6227 if (lua_type(L, 2) != LUA_TTABLE)
6228 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6229
6230 /* Third argument : lua function. */
6231 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6232
6233 /* browse the second argulent as an array. */
6234 lua_pushnil(L);
6235 while (lua_next(L, 2) != 0) {
6236 if (lua_type(L, -1) != LUA_TSTRING)
6237 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6238
6239 /* Check required environment. Only accepted "http" or "tcp". */
6240 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006241 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006242 if (!akl)
6243 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006244 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006245 if (!fcn)
6246 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6247
6248 /* Fill fcn. */
6249 fcn->name = strdup(name);
6250 if (!fcn->name)
6251 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6252 fcn->function_ref = ref;
6253
6254 /* List head */
6255 akl->list.n = akl->list.p = NULL;
6256
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006257 /* action keyword. */
6258 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006259 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006260 if (!akl->kw[0].kw)
6261 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6262
6263 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6264
6265 akl->kw[0].match_pfx = 0;
6266 akl->kw[0].private = fcn;
6267 akl->kw[0].parse = action_register_lua;
6268
6269 /* select the action registering point. */
6270 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6271 tcp_req_cont_keywords_register(akl);
6272 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6273 tcp_res_cont_keywords_register(akl);
6274 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6275 http_req_keywords_register(akl);
6276 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6277 http_res_keywords_register(akl);
6278 else
6279 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6280 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6281 "are expected.", lua_tostring(L, -1)));
6282
6283 /* pop the environment string. */
6284 lua_pop(L, 1);
6285 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006286 return ACT_RET_PRS_OK;
6287}
6288
6289static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6290 struct act_rule *rule, char **err)
6291{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006292 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006293
6294 /* Memory for the rule. */
6295 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6296 if (!rule->arg.hlua_rule) {
6297 memprintf(err, "out of memory error");
6298 return ACT_RET_PRS_ERR;
6299 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006300
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006301 /* Reference the Lua function and store the reference. */
6302 rule->arg.hlua_rule->fcn = *fcn;
6303
6304 /* TODO: later accept arguments. */
6305 rule->arg.hlua_rule->args = NULL;
6306
6307 /* Add applet pointer in the rule. */
6308 rule->applet.obj_type = OBJ_TYPE_APPLET;
6309 rule->applet.name = fcn->name;
6310 rule->applet.init = hlua_applet_tcp_init;
6311 rule->applet.fct = hlua_applet_tcp_fct;
6312 rule->applet.release = hlua_applet_tcp_release;
6313 rule->applet.timeout = hlua_timeout_applet;
6314
6315 return 0;
6316}
6317
6318/* This function is an LUA binding used for registering
6319 * "sample-conv" functions. It expects a converter name used
6320 * in the haproxy configuration file, and an LUA function.
6321 */
6322__LJMP static int hlua_register_service(lua_State *L)
6323{
6324 struct action_kw_list *akl;
6325 const char *name;
6326 const char *env;
6327 int ref;
6328 int len;
6329 struct hlua_function *fcn;
6330
6331 MAY_LJMP(check_args(L, 3, "register_service"));
6332
6333 /* First argument : converter name. */
6334 name = MAY_LJMP(luaL_checkstring(L, 1));
6335
6336 /* Second argument : environment. */
6337 env = MAY_LJMP(luaL_checkstring(L, 2));
6338
6339 /* Third argument : lua function. */
6340 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6341
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006342 /* Allocate and fill the sample fetch keyword struct. */
6343 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6344 if (!akl)
6345 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6346 fcn = calloc(1, sizeof(*fcn));
6347 if (!fcn)
6348 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6349
6350 /* Fill fcn. */
6351 len = strlen("<lua.>") + strlen(name) + 1;
6352 fcn->name = calloc(1, len);
6353 if (!fcn->name)
6354 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6355 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6356 fcn->function_ref = ref;
6357
6358 /* List head */
6359 akl->list.n = akl->list.p = NULL;
6360
6361 /* converter keyword. */
6362 len = strlen("lua.") + strlen(name) + 1;
6363 akl->kw[0].kw = calloc(1, len);
6364 if (!akl->kw[0].kw)
6365 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6366
6367 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6368
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01006369 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006370 if (strcmp(env, "tcp") == 0)
6371 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006372 else if (strcmp(env, "http") == 0)
6373 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006374 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006375 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6376 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006377
6378 akl->kw[0].match_pfx = 0;
6379 akl->kw[0].private = fcn;
6380
6381 /* End of array. */
6382 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6383
6384 /* Register this new converter */
6385 service_keywords_register(akl);
6386
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006387 return 0;
6388}
6389
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006390/* This function initialises Lua cli handler. It copies the
6391 * arguments in the Lua stack and create channel IO objects.
6392 */
6393static int hlua_cli_parse_fct(char **args, struct appctx *appctx, void *private)
6394{
6395 struct hlua *hlua;
6396 struct hlua_function *fcn;
6397 int i;
6398 const char *error;
6399
6400 hlua = &appctx->ctx.hlua_cli.hlua;
6401 fcn = private;
6402 appctx->private = private;
6403
6404 /* Create task used by signal to wakeup applets.
6405 * We use the same wakeup fonction than the Lua applet_tcp and
6406 * applet_http. It is absolutely compatible.
6407 */
6408 appctx->ctx.hlua_cli.task = task_new();
6409 if (!appctx->ctx.hlua_cli.task) {
6410 SEND_ERR(NULL, "Lua applet tcp '%s': out of memory.\n", fcn->name);
6411 return 0;
6412 }
6413 appctx->ctx.hlua_cli.task->nice = 0;
6414 appctx->ctx.hlua_cli.task->context = appctx;
6415 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
6416
6417 /* Initialises the Lua context */
6418 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
6419 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
6420 return 1;
6421 }
6422
6423 /* The following Lua calls can fail. */
6424 if (!SET_SAFE_LJMP(hlua->T)) {
6425 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6426 error = lua_tostring(hlua->T, -1);
6427 else
6428 error = "critical error";
6429 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
6430 goto error;
6431 }
6432
6433 /* Check stack available size. */
6434 if (!lua_checkstack(hlua->T, 2)) {
6435 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6436 goto error;
6437 }
6438
6439 /* Restore the function in the stack. */
6440 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
6441
6442 /* Once the arguments parsed, the CLI is like an AppletTCP,
6443 * so push AppletTCP in the stack.
6444 * TODO: get_priv() and set_priv() are useless. Maybe we will
6445 * create a new object without these two functions.
6446 */
6447 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
6448 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6449 goto error;
6450 }
6451 hlua->nargs = 1;
6452
6453 /* push keywords in the stack. */
6454 for (i = 0; *args[i]; i++) {
6455 /* Check stack available size. */
6456 if (!lua_checkstack(hlua->T, 1)) {
6457 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6458 goto error;
6459 }
6460 lua_pushstring(hlua->T, args[i]);
6461 hlua->nargs++;
6462 }
6463
6464 /* We must initialize the execution timeouts. */
6465 hlua->max_time = hlua_timeout_session;
6466
6467 /* At this point the execution is safe. */
6468 RESET_SAFE_LJMP(hlua->T);
6469
6470 /* It's ok */
6471 return 0;
6472
6473 /* It's not ok. */
6474error:
6475 RESET_SAFE_LJMP(hlua->T);
6476 hlua_ctx_destroy(hlua);
6477 return 1;
6478}
6479
6480static int hlua_cli_io_handler_fct(struct appctx *appctx)
6481{
6482 struct hlua *hlua;
6483 struct stream_interface *si;
6484 struct hlua_function *fcn;
6485
6486 hlua = &appctx->ctx.hlua_cli.hlua;
6487 si = appctx->owner;
6488 fcn = appctx->private;
6489
6490 /* If the stream is disconnect or closed, ldo nothing. */
6491 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6492 return 1;
6493
6494 /* Execute the function. */
6495 switch (hlua_ctx_resume(hlua, 1)) {
6496
6497 /* finished. */
6498 case HLUA_E_OK:
6499 return 1;
6500
6501 /* yield. */
6502 case HLUA_E_AGAIN:
6503 /* We want write. */
6504 if (HLUA_IS_WAKERESWR(hlua))
6505 si_applet_cant_put(si);
6506 /* Set the timeout. */
6507 if (hlua->wake_time != TICK_ETERNITY)
6508 task_schedule(hlua->task, hlua->wake_time);
6509 return 0;
6510
6511 /* finished with error. */
6512 case HLUA_E_ERRMSG:
6513 /* Display log. */
6514 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
6515 fcn->name, lua_tostring(hlua->T, -1));
6516 lua_pop(hlua->T, 1);
6517 return 1;
6518
6519 case HLUA_E_ERR:
6520 /* Display log. */
6521 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
6522 fcn->name);
6523 return 1;
6524
6525 default:
6526 return 1;
6527 }
6528
6529 return 1;
6530}
6531
6532static void hlua_cli_io_release_fct(struct appctx *appctx)
6533{
6534 struct hlua *hlua;
6535
6536 hlua = &appctx->ctx.hlua_cli.hlua;
6537 hlua_ctx_destroy(hlua);
6538}
6539
6540/* This function is an LUA binding used for registering
6541 * new keywords in the cli. It expects a list of keywords
6542 * which are the "path". It is limited to 5 keywords. A
6543 * description of the command, a function to be executed
6544 * for the parsing and a function for io handlers.
6545 */
6546__LJMP static int hlua_register_cli(lua_State *L)
6547{
6548 struct cli_kw_list *cli_kws;
6549 const char *message;
6550 int ref_io;
6551 int len;
6552 struct hlua_function *fcn;
6553 int index;
6554 int i;
6555
6556 MAY_LJMP(check_args(L, 3, "register_cli"));
6557
6558 /* First argument : an array of maximum 5 keywords. */
6559 if (!lua_istable(L, 1))
6560 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
6561
6562 /* Second argument : string with contextual message. */
6563 message = MAY_LJMP(luaL_checkstring(L, 2));
6564
6565 /* Third and fourth argument : lua function. */
6566 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
6567
6568 /* Allocate and fill the sample fetch keyword struct. */
6569 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
6570 if (!cli_kws)
6571 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6572 fcn = calloc(1, sizeof(*fcn));
6573 if (!fcn)
6574 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6575
6576 /* Fill path. */
6577 index = 0;
6578 lua_pushnil(L);
6579 while(lua_next(L, 1) != 0) {
6580 if (index >= 5)
6581 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
6582 if (lua_type(L, -1) != LUA_TSTRING)
6583 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
6584 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
6585 if (!cli_kws->kw[0].str_kw[index])
6586 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6587 index++;
6588 lua_pop(L, 1);
6589 }
6590
6591 /* Copy help message. */
6592 cli_kws->kw[0].usage = strdup(message);
6593 if (!cli_kws->kw[0].usage)
6594 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6595
6596 /* Fill fcn io handler. */
6597 len = strlen("<lua.cli>") + 1;
6598 for (i = 0; i < index; i++)
6599 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
6600 fcn->name = calloc(1, len);
6601 if (!fcn->name)
6602 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6603 strncat((char *)fcn->name, "<lua.cli", len);
6604 for (i = 0; i < index; i++) {
6605 strncat((char *)fcn->name, ".", len);
6606 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
6607 }
6608 strncat((char *)fcn->name, ">", len);
6609 fcn->function_ref = ref_io;
6610
6611 /* Fill last entries. */
6612 cli_kws->kw[0].private = fcn;
6613 cli_kws->kw[0].parse = hlua_cli_parse_fct;
6614 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
6615 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
6616
6617 /* Register this new converter */
6618 cli_register_kw(cli_kws);
6619
6620 return 0;
6621}
6622
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006623static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
6624 struct proxy *defpx, const char *file, int line,
6625 char **err, unsigned int *timeout)
6626{
6627 const char *error;
6628
6629 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
6630 if (error && *error != '\0') {
6631 memprintf(err, "%s: invalid timeout", args[0]);
6632 return -1;
6633 }
6634 return 0;
6635}
6636
6637static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
6638 struct proxy *defpx, const char *file, int line,
6639 char **err)
6640{
6641 return hlua_read_timeout(args, section_type, curpx, defpx,
6642 file, line, err, &hlua_timeout_session);
6643}
6644
6645static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
6646 struct proxy *defpx, const char *file, int line,
6647 char **err)
6648{
6649 return hlua_read_timeout(args, section_type, curpx, defpx,
6650 file, line, err, &hlua_timeout_task);
6651}
6652
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006653static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
6654 struct proxy *defpx, const char *file, int line,
6655 char **err)
6656{
6657 return hlua_read_timeout(args, section_type, curpx, defpx,
6658 file, line, err, &hlua_timeout_applet);
6659}
6660
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006661static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
6662 struct proxy *defpx, const char *file, int line,
6663 char **err)
6664{
6665 char *error;
6666
6667 hlua_nb_instruction = strtoll(args[1], &error, 10);
6668 if (*error != '\0') {
6669 memprintf(err, "%s: invalid number", args[0]);
6670 return -1;
6671 }
6672 return 0;
6673}
6674
Willy Tarreau32f61e22015-03-18 17:54:59 +01006675static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
6676 struct proxy *defpx, const char *file, int line,
6677 char **err)
6678{
6679 char *error;
6680
6681 if (*(args[1]) == 0) {
6682 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
6683 return -1;
6684 }
6685 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
6686 if (*error != '\0') {
6687 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
6688 return -1;
6689 }
6690 return 0;
6691}
6692
6693
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006694/* This function is called by the main configuration key "lua-load". It loads and
6695 * execute an lua file during the parsing of the HAProxy configuration file. It is
6696 * the main lua entry point.
6697 *
6698 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
6699 * occured, otherwise it returns 0.
6700 *
6701 * In some error case, LUA set an error message in top of the stack. This function
6702 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006703 *
6704 * This function can fail with an abort() due to an Lua critical error.
6705 * We are in the configuration parsing process of HAProxy, this abort() is
6706 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006707 */
6708static int hlua_load(char **args, int section_type, struct proxy *curpx,
6709 struct proxy *defpx, const char *file, int line,
6710 char **err)
6711{
6712 int error;
6713
6714 /* Just load and compile the file. */
6715 error = luaL_loadfile(gL.T, args[1]);
6716 if (error) {
6717 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
6718 lua_pop(gL.T, 1);
6719 return -1;
6720 }
6721
6722 /* If no syntax error where detected, execute the code. */
6723 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
6724 switch (error) {
6725 case LUA_OK:
6726 break;
6727 case LUA_ERRRUN:
6728 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
6729 lua_pop(gL.T, 1);
6730 return -1;
6731 case LUA_ERRMEM:
6732 memprintf(err, "lua out of memory error\n");
6733 return -1;
6734 case LUA_ERRERR:
6735 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
6736 lua_pop(gL.T, 1);
6737 return -1;
6738 case LUA_ERRGCMM:
6739 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
6740 lua_pop(gL.T, 1);
6741 return -1;
6742 default:
6743 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
6744 lua_pop(gL.T, 1);
6745 return -1;
6746 }
6747
6748 return 0;
6749}
6750
6751/* configuration keywords declaration */
6752static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006753 { CFG_GLOBAL, "lua-load", hlua_load },
6754 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
6755 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02006756 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006757 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01006758 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006759 { 0, NULL, NULL },
6760}};
6761
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006762/* This function can fail with an abort() due to an Lua critical error.
6763 * We are in the initialisation process of HAProxy, this abort() is
6764 * tolerated.
6765 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006766int hlua_post_init()
6767{
6768 struct hlua_init_function *init;
6769 const char *msg;
6770 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006771 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006772
Thierry Fournier3d4a6752016-02-19 20:53:30 +01006773 /* Call post initialisation function in safe environement. */
6774 if (!SET_SAFE_LJMP(gL.T)) {
6775 if (lua_type(gL.T, -1) == LUA_TSTRING)
6776 error = lua_tostring(gL.T, -1);
6777 else
6778 error = "critical error";
6779 fprintf(stderr, "Lua post-init: %s.\n", error);
6780 exit(1);
6781 }
6782 hlua_fcn_post_init(gL.T);
6783 RESET_SAFE_LJMP(gL.T);
6784
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006785 list_for_each_entry(init, &hlua_init_functions, l) {
6786 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
6787 ret = hlua_ctx_resume(&gL, 0);
6788 switch (ret) {
6789 case HLUA_E_OK:
6790 lua_pop(gL.T, -1);
6791 return 1;
6792 case HLUA_E_AGAIN:
6793 Alert("lua init: yield not allowed.\n");
6794 return 0;
6795 case HLUA_E_ERRMSG:
6796 msg = lua_tostring(gL.T, -1);
6797 Alert("lua init: %s.\n", msg);
6798 return 0;
6799 case HLUA_E_ERR:
6800 default:
6801 Alert("lua init: unknown runtime error.\n");
6802 return 0;
6803 }
6804 }
6805 return 1;
6806}
6807
Willy Tarreau32f61e22015-03-18 17:54:59 +01006808/* The memory allocator used by the Lua stack. <ud> is a pointer to the
6809 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
6810 * is the previously allocated size or the kind of object in case of a new
6811 * allocation. <nsize> is the requested new size.
6812 */
6813static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
6814{
6815 struct hlua_mem_allocator *zone = ud;
6816
6817 if (nsize == 0) {
6818 /* it's a free */
6819 if (ptr)
6820 zone->allocated -= osize;
6821 free(ptr);
6822 return NULL;
6823 }
6824
6825 if (!ptr) {
6826 /* it's a new allocation */
6827 if (zone->limit && zone->allocated + nsize > zone->limit)
6828 return NULL;
6829
6830 ptr = malloc(nsize);
6831 if (ptr)
6832 zone->allocated += nsize;
6833 return ptr;
6834 }
6835
6836 /* it's a realloc */
6837 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
6838 return NULL;
6839
6840 ptr = realloc(ptr, nsize);
6841 if (ptr)
6842 zone->allocated += nsize - osize;
6843 return ptr;
6844}
6845
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006846/* Ithis function can fail with an abort() due to an Lua critical error.
6847 * We are in the initialisation process of HAProxy, this abort() is
6848 * tolerated.
6849 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01006850void hlua_init(void)
6851{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006852 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006853 int idx;
6854 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006855 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006856 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006857 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006858#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006859 struct srv_kw *kw;
6860 int tmp_error;
6861 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01006862 char *args[] = { /* SSL client configuration. */
6863 "ssl",
6864 "verify",
6865 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01006866 NULL
6867 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006868#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006869
Willy Tarreau87b09662015-04-03 00:22:06 +02006870 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006871 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
6872
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006873 /* Register configuration keywords. */
6874 cfg_register_keywords(&cfg_kws);
6875
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006876 /* Init main lua stack. */
6877 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01006878 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006879 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006880 gL.T = luaL_newstate();
6881 hlua_sethlua(&gL);
6882 gL.Tref = LUA_REFNIL;
6883 gL.task = NULL;
6884
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006885 /* From this point, until the end of the initialisation fucntion,
6886 * the Lua function can fail with an abort. We are in the initialisation
6887 * process of HAProxy, this abort() is tolerated.
6888 */
6889
Willy Tarreau32f61e22015-03-18 17:54:59 +01006890 /* change the memory allocators to track memory usage */
6891 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
6892
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006893 /* Initialise lua. */
6894 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006895
Thierry Fournier75933d42016-01-21 09:30:18 +01006896 /* Set safe environment for the initialisation. */
6897 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006898 if (lua_type(gL.T, -1) == LUA_TSTRING)
6899 error_msg = lua_tostring(gL.T, -1);
6900 else
6901 error_msg = "critical error";
6902 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01006903 exit(1);
6904 }
6905
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006906 /*
6907 *
6908 * Create "core" object.
6909 *
6910 */
6911
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01006912 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006913 lua_newtable(gL.T);
6914
6915 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006916 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006917 hlua_class_const_int(gL.T, log_levels[i], i);
6918
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006919 /* Register special functions. */
6920 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006921 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006922 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006923 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006924 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006925 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006926 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006927 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01006928 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006929 hlua_class_function(gL.T, "sleep", hlua_sleep);
6930 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01006931 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
6932 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
6933 hlua_class_function(gL.T, "set_map", hlua_set_map);
6934 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006935 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006936 hlua_class_function(gL.T, "log", hlua_log);
6937 hlua_class_function(gL.T, "Debug", hlua_log_debug);
6938 hlua_class_function(gL.T, "Info", hlua_log_info);
6939 hlua_class_function(gL.T, "Warning", hlua_log_warning);
6940 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02006941 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01006942 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006943
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006944 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006945
6946 /*
6947 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006948 * Register class Map
6949 *
6950 */
6951
6952 /* This table entry is the object "Map" base. */
6953 lua_newtable(gL.T);
6954
6955 /* register pattern types. */
6956 for (i=0; i<PAT_MATCH_NUM; i++)
6957 hlua_class_const_int(gL.T, pat_match_names[i], i);
6958
6959 /* register constructor. */
6960 hlua_class_function(gL.T, "new", hlua_map_new);
6961
6962 /* Create and fill the metatable. */
6963 lua_newtable(gL.T);
6964
6965 /* Create and fille the __index entry. */
6966 lua_pushstring(gL.T, "__index");
6967 lua_newtable(gL.T);
6968
6969 /* Register . */
6970 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
6971 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
6972
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006973 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006974
Thierry Fournier45e78d72016-02-19 18:34:46 +01006975 /* Register previous table in the registry with reference and named entry.
6976 * The function hlua_register_metatable() pops the stack, so we
6977 * previously create a copy of the table.
6978 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006979 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01006980 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006981
6982 /* Assign the metatable to the mai Map object. */
6983 lua_setmetatable(gL.T, -2);
6984
6985 /* Set a name to the table. */
6986 lua_setglobal(gL.T, "Map");
6987
6988 /*
6989 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006990 * Register class Channel
6991 *
6992 */
6993
6994 /* Create and fill the metatable. */
6995 lua_newtable(gL.T);
6996
6997 /* Create and fille the __index entry. */
6998 lua_pushstring(gL.T, "__index");
6999 lua_newtable(gL.T);
7000
7001 /* Register . */
7002 hlua_class_function(gL.T, "get", hlua_channel_get);
7003 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7004 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7005 hlua_class_function(gL.T, "set", hlua_channel_set);
7006 hlua_class_function(gL.T, "append", hlua_channel_append);
7007 hlua_class_function(gL.T, "send", hlua_channel_send);
7008 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7009 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7010 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007011 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007012
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007013 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007014
7015 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007016 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007017
7018 /*
7019 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007020 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007021 *
7022 */
7023
7024 /* Create and fill the metatable. */
7025 lua_newtable(gL.T);
7026
7027 /* Create and fille the __index entry. */
7028 lua_pushstring(gL.T, "__index");
7029 lua_newtable(gL.T);
7030
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007031 /* Browse existing fetches and create the associated
7032 * object method.
7033 */
7034 sf = NULL;
7035 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7036
7037 /* Dont register the keywork if the arguments check function are
7038 * not safe during the runtime.
7039 */
7040 if ((sf->val_args != NULL) &&
7041 (sf->val_args != val_payload_lv) &&
7042 (sf->val_args != val_hdr))
7043 continue;
7044
7045 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7046 * by an underscore.
7047 */
7048 strncpy(trash.str, sf->kw, trash.size);
7049 trash.str[trash.size - 1] = '\0';
7050 for (p = trash.str; *p; p++)
7051 if (*p == '.' || *p == '-' || *p == '+')
7052 *p = '_';
7053
7054 /* Register the function. */
7055 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007056 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007057 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007058 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007059 }
7060
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007061 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007062
7063 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007064 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007065
7066 /*
7067 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007068 * Register class Converters
7069 *
7070 */
7071
7072 /* Create and fill the metatable. */
7073 lua_newtable(gL.T);
7074
7075 /* Create and fill the __index entry. */
7076 lua_pushstring(gL.T, "__index");
7077 lua_newtable(gL.T);
7078
7079 /* Browse existing converters and create the associated
7080 * object method.
7081 */
7082 sc = NULL;
7083 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7084 /* Dont register the keywork if the arguments check function are
7085 * not safe during the runtime.
7086 */
7087 if (sc->val_args != NULL)
7088 continue;
7089
7090 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7091 * by an underscore.
7092 */
7093 strncpy(trash.str, sc->kw, trash.size);
7094 trash.str[trash.size - 1] = '\0';
7095 for (p = trash.str; *p; p++)
7096 if (*p == '.' || *p == '-' || *p == '+')
7097 *p = '_';
7098
7099 /* Register the function. */
7100 lua_pushstring(gL.T, trash.str);
7101 lua_pushlightuserdata(gL.T, sc);
7102 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007103 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007104 }
7105
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007106 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007107
7108 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007109 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007110
7111 /*
7112 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007113 * Register class HTTP
7114 *
7115 */
7116
7117 /* Create and fill the metatable. */
7118 lua_newtable(gL.T);
7119
7120 /* Create and fille the __index entry. */
7121 lua_pushstring(gL.T, "__index");
7122 lua_newtable(gL.T);
7123
7124 /* Register Lua functions. */
7125 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7126 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7127 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7128 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7129 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7130 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7131 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7132 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7133 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7134 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7135
7136 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7137 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7138 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7139 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7140 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7141 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007142 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007143
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007144 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007145
7146 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007147 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007148
7149 /*
7150 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007151 * Register class AppletTCP
7152 *
7153 */
7154
7155 /* Create and fill the metatable. */
7156 lua_newtable(gL.T);
7157
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007158 /* Create and fille the __index entry. */
7159 lua_pushstring(gL.T, "__index");
7160 lua_newtable(gL.T);
7161
7162 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007163 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7164 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7165 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7166 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7167 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007168
7169 lua_settable(gL.T, -3);
7170
7171 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007172 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007173
7174 /*
7175 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007176 * Register class AppletHTTP
7177 *
7178 */
7179
7180 /* Create and fill the metatable. */
7181 lua_newtable(gL.T);
7182
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007183 /* Create and fille the __index entry. */
7184 lua_pushstring(gL.T, "__index");
7185 lua_newtable(gL.T);
7186
7187 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007188 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7189 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007190 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7191 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7192 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7193 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7194 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7195 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7196
7197 lua_settable(gL.T, -3);
7198
7199 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007200 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007201
7202 /*
7203 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007204 * Register class TXN
7205 *
7206 */
7207
7208 /* Create and fill the metatable. */
7209 lua_newtable(gL.T);
7210
7211 /* Create and fille the __index entry. */
7212 lua_pushstring(gL.T, "__index");
7213 lua_newtable(gL.T);
7214
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007215 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007216 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7217 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007218 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007219 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007220 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007221 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007222 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7223 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7224 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007225 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7226 hlua_class_function(gL.T, "log", hlua_txn_log);
7227 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7228 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7229 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7230 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007231
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007232 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007233
7234 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007235 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007236
7237 /*
7238 *
7239 * Register class Socket
7240 *
7241 */
7242
7243 /* Create and fill the metatable. */
7244 lua_newtable(gL.T);
7245
7246 /* Create and fille the __index entry. */
7247 lua_pushstring(gL.T, "__index");
7248 lua_newtable(gL.T);
7249
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007250#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007251 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007252#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007253 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7254 hlua_class_function(gL.T, "send", hlua_socket_send);
7255 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7256 hlua_class_function(gL.T, "close", hlua_socket_close);
7257 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7258 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7259 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7260 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7261
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007262 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007263
7264 /* Register the garbage collector entry. */
7265 lua_pushstring(gL.T, "__gc");
7266 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007267 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007268
7269 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007270 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007271
7272 /* Proxy and server configuration initialisation. */
7273 memset(&socket_proxy, 0, sizeof(socket_proxy));
7274 init_new_proxy(&socket_proxy);
7275 socket_proxy.parent = NULL;
7276 socket_proxy.last_change = now.tv_sec;
7277 socket_proxy.id = "LUA-SOCKET";
7278 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7279 socket_proxy.maxconn = 0;
7280 socket_proxy.accept = NULL;
7281 socket_proxy.options2 |= PR_O2_INDEPSTR;
7282 socket_proxy.srv = NULL;
7283 socket_proxy.conn_retries = 0;
7284 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7285
7286 /* Init TCP server: unchanged parameters */
7287 memset(&socket_tcp, 0, sizeof(socket_tcp));
7288 socket_tcp.next = NULL;
7289 socket_tcp.proxy = &socket_proxy;
7290 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7291 LIST_INIT(&socket_tcp.actconns);
7292 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007293 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007294 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007295 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007296 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
7297 socket_tcp.last_change = 0;
7298 socket_tcp.id = "LUA-TCP-CONN";
7299 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7300 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7301 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7302
7303 /* XXX: Copy default parameter from default server,
7304 * but the default server is not initialized.
7305 */
7306 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7307 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7308 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7309 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7310 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7311 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7312 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7313 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7314 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7315 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7316
7317 socket_tcp.check.status = HCHK_STATUS_INI;
7318 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7319 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7320 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7321 socket_tcp.check.server = &socket_tcp;
7322
7323 socket_tcp.agent.status = HCHK_STATUS_INI;
7324 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7325 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7326 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7327 socket_tcp.agent.server = &socket_tcp;
7328
7329 socket_tcp.xprt = &raw_sock;
7330
7331#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007332 /* Init TCP server: unchanged parameters */
7333 memset(&socket_ssl, 0, sizeof(socket_ssl));
7334 socket_ssl.next = NULL;
7335 socket_ssl.proxy = &socket_proxy;
7336 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7337 LIST_INIT(&socket_ssl.actconns);
7338 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007339 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007340 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007341 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007342 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
7343 socket_ssl.last_change = 0;
7344 socket_ssl.id = "LUA-SSL-CONN";
7345 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7346 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7347 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7348
7349 /* XXX: Copy default parameter from default server,
7350 * but the default server is not initialized.
7351 */
7352 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7353 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7354 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7355 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7356 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7357 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7358 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7359 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7360 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7361 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7362
7363 socket_ssl.check.status = HCHK_STATUS_INI;
7364 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7365 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7366 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7367 socket_ssl.check.server = &socket_ssl;
7368
7369 socket_ssl.agent.status = HCHK_STATUS_INI;
7370 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7371 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7372 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7373 socket_ssl.agent.server = &socket_ssl;
7374
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007375 socket_ssl.use_ssl = 1;
7376 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007377
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007378 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007379 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7380 /*
7381 *
7382 * If the keyword is not known, we can search in the registered
7383 * server keywords. This is usefull to configure special SSL
7384 * features like client certificates and ssl_verify.
7385 *
7386 */
7387 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7388 if (tmp_error != 0) {
7389 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7390 abort(); /* This must be never arrives because the command line
7391 not editable by the user. */
7392 }
7393 idx += kw->skip;
7394 }
7395 }
7396
7397 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007398 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007399#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007400
7401 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007402}