blob: 5594484042123a584302dc40bcea4ab7367a757b [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
28#include <types/hlua.h>
29#include <types/proxy.h>
30
Thierry FOURNIER55da1652015-01-23 11:36:30 +010031#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020032#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010033#include <proto/channel.h>
Willy Tarreaua71f6422016-11-16 17:00:14 +010034#include <proto/connection.h>
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +010035#include <proto/dumpstats.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010036#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010037#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010038#include <proto/hlua_fcn.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020039#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010040#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010041#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010042#include <proto/payload.h>
43#include <proto/proto_http.h>
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010044#include <proto/proto_tcp.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010045#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010046#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010047#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020048#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020049#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010050#include <proto/ssl_sock.h>
51#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010052#include <proto/task.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020053#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010054
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010055/* Lua uses longjmp to perform yield or throwing errors. This
56 * macro is used only for identifying the function that can
57 * not return because a longjmp is executed.
58 * __LJMP marks a prototype of hlua file that can use longjmp.
59 * WILL_LJMP() marks an lua function that will use longjmp.
60 * MAY_LJMP() marks an lua function that may use longjmp.
61 */
62#define __LJMP
63#define WILL_LJMP(func) func
64#define MAY_LJMP(func) func
65
Thierry FOURNIERbabae282015-09-17 11:36:37 +020066/* This couple of function executes securely some Lua calls outside of
67 * the lua runtime environment. Each Lua call can return a longjmp
68 * if it encounter a memory error.
69 *
70 * Lua documentation extract:
71 *
72 * If an error happens outside any protected environment, Lua calls
73 * a panic function (see lua_atpanic) and then calls abort, thus
74 * exiting the host application. Your panic function can avoid this
75 * exit by never returning (e.g., doing a long jump to your own
76 * recovery point outside Lua).
77 *
78 * The panic function runs as if it were a message handler (see
79 * §2.3); in particular, the error message is at the top of the
80 * stack. However, there is no guarantee about stack space. To push
81 * anything on the stack, the panic function must first check the
82 * available space (see §4.2).
83 *
84 * We must check all the Lua entry point. This includes:
85 * - The include/proto/hlua.h exported functions
86 * - the task wrapper function
87 * - The action wrapper function
88 * - The converters wrapper function
89 * - The sample-fetch wrapper functions
90 *
91 * It is tolerated that the initilisation function returns an abort.
92 * Before each Lua abort, an error message is writed on stderr.
93 *
94 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
95 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
96 * because they must be exists in the program stack when the longjmp
97 * is called.
98 */
99jmp_buf safe_ljmp_env;
100static int hlua_panic_safe(lua_State *L) { return 0; }
101static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
102
103#define SET_SAFE_LJMP(__L) \
104 ({ \
105 int ret; \
106 if (setjmp(safe_ljmp_env) != 0) { \
107 lua_atpanic(__L, hlua_panic_safe); \
108 ret = 0; \
109 } else { \
110 lua_atpanic(__L, hlua_panic_ljmp); \
111 ret = 1; \
112 } \
113 ret; \
114 })
115
116/* If we are the last function catching Lua errors, we
117 * must reset the panic function.
118 */
119#define RESET_SAFE_LJMP(__L) \
120 do { \
121 lua_atpanic(__L, hlua_panic_safe); \
122 } while(0)
123
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200124/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200125#define APPLET_DONE 0x01 /* applet processing is done. */
126#define APPLET_100C 0x02 /* 100 continue expected. */
127#define APPLET_HDR_SENT 0x04 /* Response header sent. */
128#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
129#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100130#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200131
132#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200133
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100134/* The main Lua execution context. */
135struct hlua gL;
136
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100137/* This is the memory pool containing all the signal structs. These
138 * struct are used to store each requiered signal between two tasks.
139 */
140struct pool_head *pool2_hlua_com;
141
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100142/* Used for Socket connection. */
143static struct proxy socket_proxy;
144static struct server socket_tcp;
145#ifdef USE_OPENSSL
146static struct server socket_ssl;
147#endif
148
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100149/* List head of the function called at the initialisation time. */
150struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
151
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100152/* The following variables contains the reference of the different
153 * Lua classes. These references are useful for identify metadata
154 * associated with an object.
155 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100156static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100157static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100158static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100159static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100160static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100161static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200162static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200163static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200164static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100165
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100166/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200167 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100168 * short timeout. Lua linked with tasks doesn't have a timeout
169 * because a task may remain alive during all the haproxy execution.
170 */
171static unsigned int hlua_timeout_session = 4000; /* session timeout. */
172static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200173static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100174
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100175/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
176 * it is used for preventing infinite loops.
177 *
178 * I test the scheer with an infinite loop containing one incrementation
179 * and one test. I run this loop between 10 seconds, I raise a ceil of
180 * 710M loops from one interrupt each 9000 instructions, so I fix the value
181 * to one interrupt each 10 000 instructions.
182 *
183 * configured | Number of
184 * instructions | loops executed
185 * between two | in milions
186 * forced yields |
187 * ---------------+---------------
188 * 10 | 160
189 * 500 | 670
190 * 1000 | 680
191 * 5000 | 700
192 * 7000 | 700
193 * 8000 | 700
194 * 9000 | 710 <- ceil
195 * 10000 | 710
196 * 100000 | 710
197 * 1000000 | 710
198 *
199 */
200static unsigned int hlua_nb_instruction = 10000;
201
Willy Tarreau32f61e22015-03-18 17:54:59 +0100202/* Descriptor for the memory allocation state. If limit is not null, it will
203 * be enforced on any memory allocation.
204 */
205struct hlua_mem_allocator {
206 size_t allocated;
207 size_t limit;
208};
209
210static struct hlua_mem_allocator hlua_global_allocator;
211
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200212static const char error_500[] =
213 "HTTP/1.0 500 Server Error\r\n"
214 "Cache-Control: no-cache\r\n"
215 "Connection: close\r\n"
216 "Content-Type: text/html\r\n"
217 "\r\n"
218 "<html><body><h1>500 Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
219
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100220/* These functions converts types between HAProxy internal args or
221 * sample and LUA types. Another function permits to check if the
222 * LUA stack contains arguments according with an required ARG_T
223 * format.
224 */
225static int hlua_arg2lua(lua_State *L, const struct arg *arg);
226static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100227__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100228 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100229static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100230static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100231static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
232
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200233__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
234
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200235#define SEND_ERR(__be, __fmt, __args...) \
236 do { \
237 send_log(__be, LOG_ERR, __fmt, ## __args); \
238 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
239 Alert(__fmt, ## __args); \
240 } while (0)
241
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100242/* Used to check an Lua function type in the stack. It creates and
243 * returns a reference of the function. This function throws an
244 * error if the rgument is not a "function".
245 */
246__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
247{
248 if (!lua_isfunction(L, argno)) {
249 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
250 WILL_LJMP(luaL_argerror(L, argno, msg));
251 }
252 lua_pushvalue(L, argno);
253 return luaL_ref(L, LUA_REGISTRYINDEX);
254}
255
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200256/* Return the string that is of the top of the stack. */
257const char *hlua_get_top_error_string(lua_State *L)
258{
259 if (lua_gettop(L) < 1)
260 return "unknown error";
261 if (lua_type(L, -1) != LUA_TSTRING)
262 return "unknown error";
263 return lua_tostring(L, -1);
264}
265
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100266/* This function check the number of arguments available in the
267 * stack. If the number of arguments available is not the same
268 * then <nb> an error is throwed.
269 */
270__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
271{
272 if (lua_gettop(L) == nb)
273 return;
274 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
275}
276
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100277/* This fucntion push an error string prefixed by the file name
278 * and the line number where the error is encountered.
279 */
280static int hlua_pusherror(lua_State *L, const char *fmt, ...)
281{
282 va_list argp;
283 va_start(argp, fmt);
284 luaL_where(L, 1);
285 lua_pushvfstring(L, fmt, argp);
286 va_end(argp);
287 lua_concat(L, 2);
288 return 1;
289}
290
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100291/* This function register a new signal. "lua" is the current lua
292 * execution context. It contains a pointer to the associated task.
293 * "link" is a list head attached to an other task that must be wake
294 * the lua task if an event occurs. This is useful with external
295 * events like TCP I/O or sleep functions. This funcion allocate
296 * memory for the signal.
297 */
298static int hlua_com_new(struct hlua *lua, struct list *link)
299{
300 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
301 if (!com)
302 return 0;
303 LIST_ADDQ(&lua->com, &com->purge_me);
304 LIST_ADDQ(link, &com->wake_me);
305 com->task = lua->task;
306 return 1;
307}
308
309/* This function purge all the pending signals when the LUA execution
310 * is finished. This prevent than a coprocess try to wake a deleted
311 * task. This function remove the memory associated to the signal.
312 */
313static void hlua_com_purge(struct hlua *lua)
314{
315 struct hlua_com *com, *back;
316
317 /* Delete all pending communication signals. */
318 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
319 LIST_DEL(&com->purge_me);
320 LIST_DEL(&com->wake_me);
321 pool_free2(pool2_hlua_com, com);
322 }
323}
324
325/* This function sends signals. It wakes all the tasks attached
326 * to a list head, and remove the signal, and free the used
327 * memory.
328 */
329static void hlua_com_wake(struct list *wake)
330{
331 struct hlua_com *com, *back;
332
333 /* Wake task and delete all pending communication signals. */
334 list_for_each_entry_safe(com, back, wake, wake_me) {
335 LIST_DEL(&com->purge_me);
336 LIST_DEL(&com->wake_me);
337 task_wakeup(com->task, TASK_WOKEN_MSG);
338 pool_free2(pool2_hlua_com, com);
339 }
340}
341
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100342/* This functions is used with sample fetch and converters. It
343 * converts the HAProxy configuration argument in a lua stack
344 * values.
345 *
346 * It takes an array of "arg", and each entry of the array is
347 * converted and pushed in the LUA stack.
348 */
349static int hlua_arg2lua(lua_State *L, const struct arg *arg)
350{
351 switch (arg->type) {
352 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100353 case ARGT_TIME:
354 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100355 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100356 break;
357
358 case ARGT_STR:
359 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
360 break;
361
362 case ARGT_IPV4:
363 case ARGT_IPV6:
364 case ARGT_MSK4:
365 case ARGT_MSK6:
366 case ARGT_FE:
367 case ARGT_BE:
368 case ARGT_TAB:
369 case ARGT_SRV:
370 case ARGT_USR:
371 case ARGT_MAP:
372 default:
373 lua_pushnil(L);
374 break;
375 }
376 return 1;
377}
378
379/* This function take one entrie in an LUA stack at the index "ud",
380 * and try to convert it in an HAProxy argument entry. This is useful
381 * with sample fetch wrappers. The input arguments are gived to the
382 * lua wrapper and converted as arg list by thi function.
383 */
384static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
385{
386 switch (lua_type(L, ud)) {
387
388 case LUA_TNUMBER:
389 case LUA_TBOOLEAN:
390 arg->type = ARGT_SINT;
391 arg->data.sint = lua_tointeger(L, ud);
392 break;
393
394 case LUA_TSTRING:
395 arg->type = ARGT_STR;
396 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
397 break;
398
399 case LUA_TUSERDATA:
400 case LUA_TNIL:
401 case LUA_TTABLE:
402 case LUA_TFUNCTION:
403 case LUA_TTHREAD:
404 case LUA_TLIGHTUSERDATA:
405 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200406 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100407 break;
408 }
409 return 1;
410}
411
412/* the following functions are used to convert a struct sample
413 * in Lua type. This useful to convert the return of the
414 * fetchs or converters.
415 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100416static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100417{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200418 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100419 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100420 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200421 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100422 break;
423
424 case SMP_T_BIN:
425 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200426 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100427 break;
428
429 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200430 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100431 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
432 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
433 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
434 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
435 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
436 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
437 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
438 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
439 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200440 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100441 break;
442 default:
443 lua_pushnil(L);
444 break;
445 }
446 break;
447
448 case SMP_T_IPV4:
449 case SMP_T_IPV6:
450 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200451 if (sample_casts[smp->data.type][SMP_T_STR] &&
452 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200453 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100454 else
455 lua_pushnil(L);
456 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100457 default:
458 lua_pushnil(L);
459 break;
460 }
461 return 1;
462}
463
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100464/* the following functions are used to convert a struct sample
465 * in Lua strings. This is useful to convert the return of the
466 * fetchs or converters.
467 */
468static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
469{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200470 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100471
472 case SMP_T_BIN:
473 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200474 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100475 break;
476
477 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200478 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100479 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
480 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
481 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
482 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
483 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
484 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
485 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
486 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
487 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200488 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100489 break;
490 default:
491 lua_pushstring(L, "");
492 break;
493 }
494 break;
495
496 case SMP_T_SINT:
497 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100498 case SMP_T_IPV4:
499 case SMP_T_IPV6:
500 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200501 if (sample_casts[smp->data.type][SMP_T_STR] &&
502 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200503 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100504 else
505 lua_pushstring(L, "");
506 break;
507 default:
508 lua_pushstring(L, "");
509 break;
510 }
511 return 1;
512}
513
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100514/* the following functions are used to convert an Lua type in a
515 * struct sample. This is useful to provide data from a converter
516 * to the LUA code.
517 */
518static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
519{
520 switch (lua_type(L, ud)) {
521
522 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200523 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200524 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100525 break;
526
527
528 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200529 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200530 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100531 break;
532
533 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200534 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100535 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200536 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100537 break;
538
539 case LUA_TUSERDATA:
540 case LUA_TNIL:
541 case LUA_TTABLE:
542 case LUA_TFUNCTION:
543 case LUA_TTHREAD:
544 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200545 case LUA_TNONE:
546 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200547 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200548 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100549 break;
550 }
551 return 1;
552}
553
554/* This function check the "argp" builded by another conversion function
555 * is in accord with the expected argp defined by the "mask". The fucntion
556 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100557 *
558 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
559 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100560 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100561__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100562 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100563{
564 int min_arg;
565 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100566 struct proxy *px;
567 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100568
569 idx = 0;
570 min_arg = ARGM(mask);
571 mask >>= ARGM_BITS;
572
573 while (1) {
574
575 /* Check oversize. */
576 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100577 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100578 }
579
580 /* Check for mandatory arguments. */
581 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100582 if (idx < min_arg) {
583
584 /* If miss other argument than the first one, we return an error. */
585 if (idx > 0)
586 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
587
588 /* If first argument have a certain type, some default values
589 * may be used. See the function smp_resolve_args().
590 */
591 switch (mask & ARGT_MASK) {
592
593 case ARGT_FE:
594 if (!(p->cap & PR_CAP_FE))
595 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
596 argp[idx].data.prx = p;
597 argp[idx].type = ARGT_FE;
598 argp[idx+1].type = ARGT_STOP;
599 break;
600
601 case ARGT_BE:
602 if (!(p->cap & PR_CAP_BE))
603 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
604 argp[idx].data.prx = p;
605 argp[idx].type = ARGT_BE;
606 argp[idx+1].type = ARGT_STOP;
607 break;
608
609 case ARGT_TAB:
610 argp[idx].data.prx = p;
611 argp[idx].type = ARGT_TAB;
612 argp[idx+1].type = ARGT_STOP;
613 break;
614
615 default:
616 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
617 break;
618 }
619 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100620 return 0;
621 }
622
623 /* Check for exceed the number of requiered argument. */
624 if ((mask & ARGT_MASK) == ARGT_STOP &&
625 argp[idx].type != ARGT_STOP) {
626 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
627 }
628
629 if ((mask & ARGT_MASK) == ARGT_STOP &&
630 argp[idx].type == ARGT_STOP) {
631 return 0;
632 }
633
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100634 /* Convert some argument types. */
635 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100636 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100637 if (argp[idx].type != ARGT_SINT)
638 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
639 argp[idx].type = ARGT_SINT;
640 break;
641
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100642 case ARGT_TIME:
643 if (argp[idx].type != ARGT_SINT)
644 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200645 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100646 break;
647
648 case ARGT_SIZE:
649 if (argp[idx].type != ARGT_SINT)
650 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200651 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100652 break;
653
654 case ARGT_FE:
655 if (argp[idx].type != ARGT_STR)
656 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
657 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
658 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200659 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100660 if (!argp[idx].data.prx)
661 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
662 argp[idx].type = ARGT_FE;
663 break;
664
665 case ARGT_BE:
666 if (argp[idx].type != ARGT_STR)
667 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
668 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
669 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200670 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100671 if (!argp[idx].data.prx)
672 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
673 argp[idx].type = ARGT_BE;
674 break;
675
676 case ARGT_TAB:
677 if (argp[idx].type != ARGT_STR)
678 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
679 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
680 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200681 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100682 if (!argp[idx].data.prx)
683 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
684 argp[idx].type = ARGT_TAB;
685 break;
686
687 case ARGT_SRV:
688 if (argp[idx].type != ARGT_STR)
689 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
690 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
691 trash.str[argp[idx].data.str.len] = 0;
692 sname = strrchr(trash.str, '/');
693 if (sname) {
694 *sname++ = '\0';
695 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200696 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100697 if (!px)
698 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
699 }
700 else {
701 sname = trash.str;
702 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100703 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100704 argp[idx].data.srv = findserver(px, sname);
705 if (!argp[idx].data.srv)
706 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
707 argp[idx].type = ARGT_SRV;
708 break;
709
710 case ARGT_IPV4:
711 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
712 trash.str[argp[idx].data.str.len] = 0;
713 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
714 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
715 argp[idx].type = ARGT_IPV4;
716 break;
717
718 case ARGT_MSK4:
719 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
720 trash.str[argp[idx].data.str.len] = 0;
721 if (!str2mask(trash.str, &argp[idx].data.ipv4))
722 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
723 argp[idx].type = ARGT_MSK4;
724 break;
725
726 case ARGT_IPV6:
727 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
728 trash.str[argp[idx].data.str.len] = 0;
729 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
730 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
731 argp[idx].type = ARGT_IPV6;
732 break;
733
734 case ARGT_MSK6:
735 case ARGT_MAP:
736 case ARGT_REG:
737 case ARGT_USR:
738 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100739 break;
740 }
741
742 /* Check for type of argument. */
743 if ((mask & ARGT_MASK) != argp[idx].type) {
744 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
745 arg_type_names[(mask & ARGT_MASK)],
746 arg_type_names[argp[idx].type & ARGT_MASK]);
747 WILL_LJMP(luaL_argerror(L, first + idx, msg));
748 }
749
750 /* Next argument. */
751 mask >>= ARGT_BITS;
752 idx++;
753 }
754}
755
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100756/*
757 * The following functions are used to make correspondance between the the
758 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100759 *
760 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100761 * - hlua_sethlua : create the association between hlua context and lua_state.
762 */
763static inline struct hlua *hlua_gethlua(lua_State *L)
764{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100765 struct hlua **hlua = lua_getextraspace(L);
766 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100767}
768static inline void hlua_sethlua(struct hlua *hlua)
769{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100770 struct hlua **hlua_store = lua_getextraspace(hlua->T);
771 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100772}
773
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100774/* This function is used to send logs. It try to send on screen (stderr)
775 * and on the default syslog server.
776 */
777static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
778{
779 struct tm tm;
780 char *p;
781
782 /* Cleanup the log message. */
783 p = trash.str;
784 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200785 if (p >= trash.str + trash.size - 1) {
786 /* Break the message if exceed the buffer size. */
787 *(p-4) = ' ';
788 *(p-3) = '.';
789 *(p-2) = '.';
790 *(p-1) = '.';
791 break;
792 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100793 if (isprint(*msg))
794 *p = *msg;
795 else
796 *p = '.';
797 }
798 *p = '\0';
799
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200800 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100801 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200802 get_localtime(date.tv_sec, &tm);
803 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100804 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
805 (int)getpid(), trash.str);
806 fflush(stderr);
807 }
808}
809
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100810/* This function just ensure that the yield will be always
811 * returned with a timeout and permit to set some flags
812 */
813__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100814 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100815{
816 struct hlua *hlua = hlua_gethlua(L);
817
818 /* Set the wake timeout. If timeout is required, we set
819 * the expiration time.
820 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200821 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100822
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100823 hlua->flags |= flags;
824
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100825 /* Process the yield. */
826 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
827}
828
Willy Tarreau87b09662015-04-03 00:22:06 +0200829/* This function initialises the Lua environment stored in the stream.
830 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100831 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200832 *
833 * This function is particular. it initialises a new Lua thread. If the
834 * initialisation fails (example: out of memory error), the lua function
835 * throws an error (longjmp).
836 *
837 * This function manipulates two Lua stack: the main and the thread. Only
838 * the main stack can fail. The thread is not manipulated. This function
839 * MUST NOT manipulate the created thread stack state, because is not
840 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100841 */
842int hlua_ctx_init(struct hlua *lua, struct task *task)
843{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200844 if (!SET_SAFE_LJMP(gL.T)) {
845 lua->Tref = LUA_REFNIL;
846 return 0;
847 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100848 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100849 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100850 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100851 lua->T = lua_newthread(gL.T);
852 if (!lua->T) {
853 lua->Tref = LUA_REFNIL;
854 return 0;
855 }
856 hlua_sethlua(lua);
857 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
858 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200859 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100860 return 1;
861}
862
Willy Tarreau87b09662015-04-03 00:22:06 +0200863/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100864 * is destroyed. The destroy also the memory context. The struct "lua"
865 * is not freed.
866 */
867void hlua_ctx_destroy(struct hlua *lua)
868{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100869 if (!lua->T)
870 return;
871
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100872 /* Purge all the pending signals. */
873 hlua_com_purge(lua);
874
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100875 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
876 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200877
878 /* Forces a garbage collecting process. If the Lua program is finished
879 * without error, we run the GC on the thread pointer. Its freed all
880 * the unused memory.
881 * If the thread is finnish with an error or is currently yielded,
882 * it seems that the GC applied on the thread doesn't clean anything,
883 * so e run the GC on the main thread.
884 * NOTE: maybe this action locks all the Lua threads untiml the en of
885 * the garbage collection.
886 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200887 if (lua->flags & HLUA_MUST_GC) {
888 lua_gc(lua->T, LUA_GCCOLLECT, 0);
889 if (lua_status(lua->T) != LUA_OK)
890 lua_gc(gL.T, LUA_GCCOLLECT, 0);
891 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200892
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200893 lua->T = NULL;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100894}
895
896/* This function is used to restore the Lua context when a coroutine
897 * fails. This function copy the common memory between old coroutine
898 * and the new coroutine. The old coroutine is destroyed, and its
899 * replaced by the new coroutine.
900 * If the flag "keep_msg" is set, the last entry of the old is assumed
901 * as string error message and it is copied in the new stack.
902 */
903static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
904{
905 lua_State *T;
906 int new_ref;
907
908 /* Renew the main LUA stack doesn't have sense. */
909 if (lua == &gL)
910 return 0;
911
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100912 /* New Lua coroutine. */
913 T = lua_newthread(gL.T);
914 if (!T)
915 return 0;
916
917 /* Copy last error message. */
918 if (keep_msg)
919 lua_xmove(lua->T, T, 1);
920
921 /* Copy data between the coroutines. */
922 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
923 lua_xmove(lua->T, T, 1);
924 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
925
926 /* Destroy old data. */
927 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
928
929 /* The thread is garbage collected by Lua. */
930 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
931
932 /* Fill the struct with the new coroutine values. */
933 lua->Mref = new_ref;
934 lua->T = T;
935 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
936
937 /* Set context. */
938 hlua_sethlua(lua);
939
940 return 1;
941}
942
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100943void hlua_hook(lua_State *L, lua_Debug *ar)
944{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100945 struct hlua *hlua = hlua_gethlua(L);
946
947 /* Lua cannot yield when its returning from a function,
948 * so, we can fix the interrupt hook to 1 instruction,
949 * expecting that the function is finnished.
950 */
951 if (lua_gethookmask(L) & LUA_MASKRET) {
952 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
953 return;
954 }
955
956 /* restore the interrupt condition. */
957 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
958
959 /* If we interrupt the Lua processing in yieldable state, we yield.
960 * If the state is not yieldable, trying yield causes an error.
961 */
962 if (lua_isyieldable(L))
963 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
964
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100965 /* If we cannot yield, update the clock and check the timeout. */
966 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200967 hlua->run_time += now_ms - hlua->start_time;
968 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100969 lua_pushfstring(L, "execution timeout");
970 WILL_LJMP(lua_error(L));
971 }
972
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200973 /* Update the start time. */
974 hlua->start_time = now_ms;
975
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100976 /* Try to interrupt the process at the end of the current
977 * unyieldable function.
978 */
979 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100980}
981
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100982/* This function start or resumes the Lua stack execution. If the flag
983 * "yield_allowed" if no set and the LUA stack execution returns a yield
984 * The function return an error.
985 *
986 * The function can returns 4 values:
987 * - HLUA_E_OK : The execution is terminated without any errors.
988 * - HLUA_E_AGAIN : The execution must continue at the next associated
989 * task wakeup.
990 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
991 * the top of the stack.
992 * - HLUA_E_ERR : An error has occured without error message.
993 *
994 * If an error occured, the stack is renewed and it is ready to run new
995 * LUA code.
996 */
997static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
998{
999 int ret;
1000 const char *msg;
1001
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001002 /* Initialise run time counter. */
1003 if (!HLUA_IS_RUNNING(lua))
1004 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001005
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001006resume_execution:
1007
1008 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1009 * instructions. it is used for preventing infinite loops.
1010 */
1011 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1012
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001013 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001014 HLUA_SET_RUN(lua);
1015 HLUA_CLR_CTRLYIELD(lua);
1016 HLUA_CLR_WAKERESWR(lua);
1017 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001018
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001019 /* Update the start time. */
1020 lua->start_time = now_ms;
1021
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001022 /* Call the function. */
1023 ret = lua_resume(lua->T, gL.T, lua->nargs);
1024 switch (ret) {
1025
1026 case LUA_OK:
1027 ret = HLUA_E_OK;
1028 break;
1029
1030 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001031 /* Check if the execution timeout is expired. It it is the case, we
1032 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001033 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001034 tv_update_date(0, 1);
1035 lua->run_time += now_ms - lua->start_time;
1036 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001037 lua_settop(lua->T, 0); /* Empty the stack. */
1038 if (!lua_checkstack(lua->T, 1)) {
1039 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001040 break;
1041 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001042 lua_pushfstring(lua->T, "execution timeout");
1043 ret = HLUA_E_ERRMSG;
1044 break;
1045 }
1046 /* Process the forced yield. if the general yield is not allowed or
1047 * if no task were associated this the current Lua execution
1048 * coroutine, we resume the execution. Else we want to return in the
1049 * scheduler and we want to be waked up again, to continue the
1050 * current Lua execution. So we schedule our own task.
1051 */
1052 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001053 if (!yield_allowed || !lua->task)
1054 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001055 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001056 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001057 if (!yield_allowed) {
1058 lua_settop(lua->T, 0); /* Empty the stack. */
1059 if (!lua_checkstack(lua->T, 1)) {
1060 ret = HLUA_E_ERR;
1061 break;
1062 }
1063 lua_pushfstring(lua->T, "yield not allowed");
1064 ret = HLUA_E_ERRMSG;
1065 break;
1066 }
1067 ret = HLUA_E_AGAIN;
1068 break;
1069
1070 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001071
1072 /* Special exit case. The traditionnal exit is returned as an error
1073 * because the errors ares the only one mean to return immediately
1074 * from and lua execution.
1075 */
1076 if (lua->flags & HLUA_EXIT) {
1077 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001078 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001079 break;
1080 }
1081
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001082 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001083 if (!lua_checkstack(lua->T, 1)) {
1084 ret = HLUA_E_ERR;
1085 break;
1086 }
1087 msg = lua_tostring(lua->T, -1);
1088 lua_settop(lua->T, 0); /* Empty the stack. */
1089 lua_pop(lua->T, 1);
1090 if (msg)
1091 lua_pushfstring(lua->T, "runtime error: %s", msg);
1092 else
1093 lua_pushfstring(lua->T, "unknown runtime error");
1094 ret = HLUA_E_ERRMSG;
1095 break;
1096
1097 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001098 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001099 lua_settop(lua->T, 0); /* Empty the stack. */
1100 if (!lua_checkstack(lua->T, 1)) {
1101 ret = HLUA_E_ERR;
1102 break;
1103 }
1104 lua_pushfstring(lua->T, "out of memory error");
1105 ret = HLUA_E_ERRMSG;
1106 break;
1107
1108 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001109 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001110 if (!lua_checkstack(lua->T, 1)) {
1111 ret = HLUA_E_ERR;
1112 break;
1113 }
1114 msg = lua_tostring(lua->T, -1);
1115 lua_settop(lua->T, 0); /* Empty the stack. */
1116 lua_pop(lua->T, 1);
1117 if (msg)
1118 lua_pushfstring(lua->T, "message handler error: %s", msg);
1119 else
1120 lua_pushfstring(lua->T, "message handler error");
1121 ret = HLUA_E_ERRMSG;
1122 break;
1123
1124 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001125 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001126 lua_settop(lua->T, 0); /* Empty the stack. */
1127 if (!lua_checkstack(lua->T, 1)) {
1128 ret = HLUA_E_ERR;
1129 break;
1130 }
1131 lua_pushfstring(lua->T, "unknonwn error");
1132 ret = HLUA_E_ERRMSG;
1133 break;
1134 }
1135
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001136 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001137 if (lua->flags & HLUA_MUST_GC &&
1138 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001139 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1140
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001141 switch (ret) {
1142 case HLUA_E_AGAIN:
1143 break;
1144
1145 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001146 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001147 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001148 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001149 break;
1150
1151 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001152 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001153 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001154 hlua_ctx_renew(lua, 0);
1155 break;
1156
1157 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001158 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001159 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001160 break;
1161 }
1162
1163 return ret;
1164}
1165
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001166/* This function exit the current code. */
1167__LJMP static int hlua_done(lua_State *L)
1168{
1169 struct hlua *hlua = hlua_gethlua(L);
1170
1171 hlua->flags |= HLUA_EXIT;
1172 WILL_LJMP(lua_error(L));
1173
1174 return 0;
1175}
1176
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001177/* This function is an LUA binding. It provides a function
1178 * for deleting ACL from a referenced ACL file.
1179 */
1180__LJMP static int hlua_del_acl(lua_State *L)
1181{
1182 const char *name;
1183 const char *key;
1184 struct pat_ref *ref;
1185
1186 MAY_LJMP(check_args(L, 2, "del_acl"));
1187
1188 name = MAY_LJMP(luaL_checkstring(L, 1));
1189 key = MAY_LJMP(luaL_checkstring(L, 2));
1190
1191 ref = pat_ref_lookup(name);
1192 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001193 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001194
1195 pat_ref_delete(ref, key);
1196 return 0;
1197}
1198
1199/* This function is an LUA binding. It provides a function
1200 * for deleting map entry from a referenced map file.
1201 */
1202static int hlua_del_map(lua_State *L)
1203{
1204 const char *name;
1205 const char *key;
1206 struct pat_ref *ref;
1207
1208 MAY_LJMP(check_args(L, 2, "del_map"));
1209
1210 name = MAY_LJMP(luaL_checkstring(L, 1));
1211 key = MAY_LJMP(luaL_checkstring(L, 2));
1212
1213 ref = pat_ref_lookup(name);
1214 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001215 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001216
1217 pat_ref_delete(ref, key);
1218 return 0;
1219}
1220
1221/* This function is an LUA binding. It provides a function
1222 * for adding ACL pattern from a referenced ACL file.
1223 */
1224static int hlua_add_acl(lua_State *L)
1225{
1226 const char *name;
1227 const char *key;
1228 struct pat_ref *ref;
1229
1230 MAY_LJMP(check_args(L, 2, "add_acl"));
1231
1232 name = MAY_LJMP(luaL_checkstring(L, 1));
1233 key = MAY_LJMP(luaL_checkstring(L, 2));
1234
1235 ref = pat_ref_lookup(name);
1236 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001237 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001238
1239 if (pat_ref_find_elt(ref, key) == NULL)
1240 pat_ref_add(ref, key, NULL, NULL);
1241 return 0;
1242}
1243
1244/* This function is an LUA binding. It provides a function
1245 * for setting map pattern and sample from a referenced map
1246 * file.
1247 */
1248static int hlua_set_map(lua_State *L)
1249{
1250 const char *name;
1251 const char *key;
1252 const char *value;
1253 struct pat_ref *ref;
1254
1255 MAY_LJMP(check_args(L, 3, "set_map"));
1256
1257 name = MAY_LJMP(luaL_checkstring(L, 1));
1258 key = MAY_LJMP(luaL_checkstring(L, 2));
1259 value = MAY_LJMP(luaL_checkstring(L, 3));
1260
1261 ref = pat_ref_lookup(name);
1262 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001263 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001264
1265 if (pat_ref_find_elt(ref, key) != NULL)
1266 pat_ref_set(ref, key, value, NULL);
1267 else
1268 pat_ref_add(ref, key, value, NULL);
1269 return 0;
1270}
1271
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001272/* A class is a lot of memory that contain data. This data can be a table,
1273 * an integer or user data. This data is associated with a metatable. This
1274 * metatable have an original version registred in the global context with
1275 * the name of the object (_G[<name>] = <metable> ).
1276 *
1277 * A metable is a table that modify the standard behavior of a standard
1278 * access to the associated data. The entries of this new metatable are
1279 * defined as is:
1280 *
1281 * http://lua-users.org/wiki/MetatableEvents
1282 *
1283 * __index
1284 *
1285 * we access an absent field in a table, the result is nil. This is
1286 * true, but it is not the whole truth. Actually, such access triggers
1287 * the interpreter to look for an __index metamethod: If there is no
1288 * such method, as usually happens, then the access results in nil;
1289 * otherwise, the metamethod will provide the result.
1290 *
1291 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1292 * the key does not appear in the table, but the metatable has an __index
1293 * property:
1294 *
1295 * - if the value is a function, the function is called, passing in the
1296 * table and the key; the return value of that function is returned as
1297 * the result.
1298 *
1299 * - if the value is another table, the value of the key in that table is
1300 * asked for and returned (and if it doesn't exist in that table, but that
1301 * table's metatable has an __index property, then it continues on up)
1302 *
1303 * - Use "rawget(myTable,key)" to skip this metamethod.
1304 *
1305 * http://www.lua.org/pil/13.4.1.html
1306 *
1307 * __newindex
1308 *
1309 * Like __index, but control property assignment.
1310 *
1311 * __mode - Control weak references. A string value with one or both
1312 * of the characters 'k' and 'v' which specifies that the the
1313 * keys and/or values in the table are weak references.
1314 *
1315 * __call - Treat a table like a function. When a table is followed by
1316 * parenthesis such as "myTable( 'foo' )" and the metatable has
1317 * a __call key pointing to a function, that function is invoked
1318 * (passing any specified arguments) and the return value is
1319 * returned.
1320 *
1321 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1322 * called, if the metatable for myTable has a __metatable
1323 * key, the value of that key is returned instead of the
1324 * actual metatable.
1325 *
1326 * __tostring - Control string representation. When the builtin
1327 * "tostring( myTable )" function is called, if the metatable
1328 * for myTable has a __tostring property set to a function,
1329 * that function is invoked (passing myTable to it) and the
1330 * return value is used as the string representation.
1331 *
1332 * __len - Control table length. When the table length is requested using
1333 * the length operator ( '#' ), if the metatable for myTable has
1334 * a __len key pointing to a function, that function is invoked
1335 * (passing myTable to it) and the return value used as the value
1336 * of "#myTable".
1337 *
1338 * __gc - Userdata finalizer code. When userdata is set to be garbage
1339 * collected, if the metatable has a __gc field pointing to a
1340 * function, that function is first invoked, passing the userdata
1341 * to it. The __gc metamethod is not called for tables.
1342 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1343 *
1344 * Special metamethods for redefining standard operators:
1345 * http://www.lua.org/pil/13.1.html
1346 *
1347 * __add "+"
1348 * __sub "-"
1349 * __mul "*"
1350 * __div "/"
1351 * __unm "!"
1352 * __pow "^"
1353 * __concat ".."
1354 *
1355 * Special methods for redfining standar relations
1356 * http://www.lua.org/pil/13.2.html
1357 *
1358 * __eq "=="
1359 * __lt "<"
1360 * __le "<="
1361 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001362
1363/*
1364 *
1365 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001366 * Class Map
1367 *
1368 *
1369 */
1370
1371/* Returns a struct hlua_map if the stack entry "ud" is
1372 * a class session, otherwise it throws an error.
1373 */
1374__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1375{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001376 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001377}
1378
1379/* This function is the map constructor. It don't need
1380 * the class Map object. It creates and return a new Map
1381 * object. It must be called only during "body" or "init"
1382 * context because it process some filesystem accesses.
1383 */
1384__LJMP static int hlua_map_new(struct lua_State *L)
1385{
1386 const char *fn;
1387 int match = PAT_MATCH_STR;
1388 struct sample_conv conv;
1389 const char *file = "";
1390 int line = 0;
1391 lua_Debug ar;
1392 char *err = NULL;
1393 struct arg args[2];
1394
1395 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1396 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1397
1398 fn = MAY_LJMP(luaL_checkstring(L, 1));
1399
1400 if (lua_gettop(L) >= 2) {
1401 match = MAY_LJMP(luaL_checkinteger(L, 2));
1402 if (match < 0 || match >= PAT_MATCH_NUM)
1403 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1404 }
1405
1406 /* Get Lua filename and line number. */
1407 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1408 lua_getinfo(L, "Sl", &ar); /* get info about it */
1409 if (ar.currentline > 0) { /* is there info? */
1410 file = ar.short_src;
1411 line = ar.currentline;
1412 }
1413 }
1414
1415 /* fill fake sample_conv struct. */
1416 conv.kw = ""; /* unused. */
1417 conv.process = NULL; /* unused. */
1418 conv.arg_mask = 0; /* unused. */
1419 conv.val_args = NULL; /* unused. */
1420 conv.out_type = SMP_T_STR;
1421 conv.private = (void *)(long)match;
1422 switch (match) {
1423 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1424 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1425 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1426 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1427 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1428 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1429 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001430 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001431 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1432 default:
1433 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1434 }
1435
1436 /* fill fake args. */
1437 args[0].type = ARGT_STR;
1438 args[0].data.str.str = (char *)fn;
1439 args[1].type = ARGT_STOP;
1440
1441 /* load the map. */
1442 if (!sample_load_map(args, &conv, file, line, &err)) {
1443 /* error case: we cant use luaL_error because we must
1444 * free the err variable.
1445 */
1446 luaL_where(L, 1);
1447 lua_pushfstring(L, "'new': %s.", err);
1448 lua_concat(L, 2);
1449 free(err);
1450 WILL_LJMP(lua_error(L));
1451 }
1452
1453 /* create the lua object. */
1454 lua_newtable(L);
1455 lua_pushlightuserdata(L, args[0].data.map);
1456 lua_rawseti(L, -2, 0);
1457
1458 /* Pop a class Map metatable and affect it to the userdata. */
1459 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1460 lua_setmetatable(L, -2);
1461
1462
1463 return 1;
1464}
1465
1466__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1467{
1468 struct map_descriptor *desc;
1469 struct pattern *pat;
1470 struct sample smp;
1471
1472 MAY_LJMP(check_args(L, 2, "lookup"));
1473 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001474 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001475 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001476 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001477 }
1478 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001479 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001480 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001481 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 +02001482 }
1483
1484 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001485 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001486 if (str)
1487 lua_pushstring(L, "");
1488 else
1489 lua_pushnil(L);
1490 return 1;
1491 }
1492
1493 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001494 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001495 return 1;
1496}
1497
1498__LJMP static int hlua_map_lookup(struct lua_State *L)
1499{
1500 return _hlua_map_lookup(L, 0);
1501}
1502
1503__LJMP static int hlua_map_slookup(struct lua_State *L)
1504{
1505 return _hlua_map_lookup(L, 1);
1506}
1507
1508/*
1509 *
1510 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001511 * Class Socket
1512 *
1513 *
1514 */
1515
1516__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1517{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001518 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001519}
1520
1521/* This function is the handler called for each I/O on the established
1522 * connection. It is used for notify space avalaible to send or data
1523 * received.
1524 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001525static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001526{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001527 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001528 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001529
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001530 /* If the connection object is not avalaible, close all the
1531 * streams and wakeup everithing waiting for.
1532 */
1533 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001534 si_shutw(si);
1535 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001536 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001537 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1538 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001539 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001540 }
1541
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001542 /* If we cant write, wakeup the pending write signals. */
1543 if (channel_output_closed(si_ic(si)))
1544 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1545
1546 /* If we cant read, wakeup the pending read signals. */
1547 if (channel_input_closed(si_oc(si)))
1548 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1549
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001550 /* if the connection is not estabkished, inform the stream that we want
1551 * to be notified whenever the connection completes.
1552 */
1553 if (!(c->flags & CO_FL_CONNECTED)) {
1554 si_applet_cant_get(si);
1555 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001556 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001557 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001558
1559 /* This function is called after the connect. */
1560 appctx->ctx.hlua.connected = 1;
1561
1562 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001563 if (channel_may_recv(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001564 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1565
1566 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001567 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001568 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1569}
1570
Willy Tarreau87b09662015-04-03 00:22:06 +02001571/* This function is called when the "struct stream" is destroyed.
1572 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001573 * Wake all the pending signals.
1574 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001575static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001576{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001577 /* Remove my link in the original object. */
1578 if (appctx->ctx.hlua.socket)
1579 appctx->ctx.hlua.socket->s = NULL;
1580
1581 /* Wake all the task waiting for me. */
1582 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1583 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1584}
1585
1586/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001587 * uses this object. If the stream does not exists, just quit.
1588 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001589 * pending signal can rest in the read and write lists. destroy
1590 * it.
1591 */
1592__LJMP static int hlua_socket_gc(lua_State *L)
1593{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001594 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001595 struct appctx *appctx;
1596
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001597 MAY_LJMP(check_args(L, 1, "__gc"));
1598
1599 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001600 if (!socket->s)
1601 return 0;
1602
Willy Tarreau87b09662015-04-03 00:22:06 +02001603 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001604 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001605 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001606 socket->s = NULL;
1607 appctx->ctx.hlua.socket = NULL;
1608
1609 return 0;
1610}
1611
1612/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001613 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001614 */
1615__LJMP static int hlua_socket_close(lua_State *L)
1616{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001617 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001618 struct appctx *appctx;
1619
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001620 MAY_LJMP(check_args(L, 1, "close"));
1621
1622 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001623 if (!socket->s)
1624 return 0;
1625
Willy Tarreau87b09662015-04-03 00:22:06 +02001626 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001627 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001628 appctx = objt_appctx(socket->s->si[0].end);
1629 appctx->ctx.hlua.socket = NULL;
1630 socket->s = NULL;
1631
1632 return 0;
1633}
1634
1635/* This Lua function assumes that the stack contain three parameters.
1636 * 1 - USERDATA containing a struct socket
1637 * 2 - INTEGER with values of the macro defined below
1638 * If the integer is -1, we must read at most one line.
1639 * If the integer is -2, we ust read all the data until the
1640 * end of the stream.
1641 * If the integer is positive value, we must read a number of
1642 * bytes corresponding to this value.
1643 */
1644#define HLSR_READ_LINE (-1)
1645#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001646__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001647{
1648 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1649 int wanted = lua_tointeger(L, 2);
1650 struct hlua *hlua = hlua_gethlua(L);
1651 struct appctx *appctx;
1652 int len;
1653 int nblk;
1654 char *blk1;
1655 int len1;
1656 char *blk2;
1657 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001658 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001659 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001660
1661 /* Check if this lua stack is schedulable. */
1662 if (!hlua || !hlua->task)
1663 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1664 "'frontend', 'backend' or 'task'"));
1665
1666 /* check for connection closed. If some data where read, return it. */
1667 if (!socket->s)
1668 goto connection_closed;
1669
Willy Tarreau94aa6172015-03-13 14:19:06 +01001670 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001671 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001672 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001673 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001674 if (nblk < 0) /* Connection close. */
1675 goto connection_closed;
1676 if (nblk == 0) /* No data avalaible. */
1677 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001678
1679 /* remove final \r\n. */
1680 if (nblk == 1) {
1681 if (blk1[len1-1] == '\n') {
1682 len1--;
1683 skip_at_end++;
1684 if (blk1[len1-1] == '\r') {
1685 len1--;
1686 skip_at_end++;
1687 }
1688 }
1689 }
1690 else {
1691 if (blk2[len2-1] == '\n') {
1692 len2--;
1693 skip_at_end++;
1694 if (blk2[len2-1] == '\r') {
1695 len2--;
1696 skip_at_end++;
1697 }
1698 }
1699 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001700 }
1701
1702 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001703 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001704 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001705 if (nblk < 0) /* Connection close. */
1706 goto connection_closed;
1707 if (nblk == 0) /* No data avalaible. */
1708 goto connection_empty;
1709 }
1710
1711 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001712 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001713 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001714 if (nblk < 0) /* Connection close. */
1715 goto connection_closed;
1716 if (nblk == 0) /* No data avalaible. */
1717 goto connection_empty;
1718
1719 if (len1 > wanted) {
1720 nblk = 1;
1721 len1 = wanted;
1722 } if (nblk == 2 && len1 + len2 > wanted)
1723 len2 = wanted - len1;
1724 }
1725
1726 len = len1;
1727
1728 luaL_addlstring(&socket->b, blk1, len1);
1729 if (nblk == 2) {
1730 len += len2;
1731 luaL_addlstring(&socket->b, blk2, len2);
1732 }
1733
1734 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001735 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001736
1737 /* Don't wait anything. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001738 stream_int_notify(&socket->s->si[0]);
1739 stream_int_update_applet(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001740
1741 /* If the pattern reclaim to read all the data
1742 * in the connection, got out.
1743 */
1744 if (wanted == HLSR_READ_ALL)
1745 goto connection_empty;
1746 else if (wanted >= 0 && len < wanted)
1747 goto connection_empty;
1748
1749 /* Return result. */
1750 luaL_pushresult(&socket->b);
1751 return 1;
1752
1753connection_closed:
1754
1755 /* If the buffer containds data. */
1756 if (socket->b.n > 0) {
1757 luaL_pushresult(&socket->b);
1758 return 1;
1759 }
1760 lua_pushnil(L);
1761 lua_pushstring(L, "connection closed.");
1762 return 2;
1763
1764connection_empty:
1765
1766 appctx = objt_appctx(socket->s->si[0].end);
1767 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1768 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001769 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001770 return 0;
1771}
1772
1773/* This Lus function gets two parameters. The first one can be string
1774 * or a number. If the string is "*l", the user require one line. If
1775 * the string is "*a", the user require all the content of the stream.
1776 * If the value is a number, the user require a number of bytes equal
1777 * to the value. The default value is "*l" (a line).
1778 *
1779 * This paraeter with a variable type is converted in integer. This
1780 * integer takes this values:
1781 * -1 : read a line
1782 * -2 : read all the stream
1783 * >0 : amount if bytes.
1784 *
1785 * The second parameter is optinal. It contains a string that must be
1786 * concatenated with the read data.
1787 */
1788__LJMP static int hlua_socket_receive(struct lua_State *L)
1789{
1790 int wanted = HLSR_READ_LINE;
1791 const char *pattern;
1792 int type;
1793 char *error;
1794 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001795 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001796
1797 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1798 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1799
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001800 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001801
1802 /* check for pattern. */
1803 if (lua_gettop(L) >= 2) {
1804 type = lua_type(L, 2);
1805 if (type == LUA_TSTRING) {
1806 pattern = lua_tostring(L, 2);
1807 if (strcmp(pattern, "*a") == 0)
1808 wanted = HLSR_READ_ALL;
1809 else if (strcmp(pattern, "*l") == 0)
1810 wanted = HLSR_READ_LINE;
1811 else {
1812 wanted = strtoll(pattern, &error, 10);
1813 if (*error != '\0')
1814 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1815 }
1816 }
1817 else if (type == LUA_TNUMBER) {
1818 wanted = lua_tointeger(L, 2);
1819 if (wanted < 0)
1820 WILL_LJMP(luaL_error(L, "Unsupported size."));
1821 }
1822 }
1823
1824 /* Set pattern. */
1825 lua_pushinteger(L, wanted);
1826 lua_replace(L, 2);
1827
1828 /* init bufffer, and fiil it wih prefix. */
1829 luaL_buffinit(L, &socket->b);
1830
1831 /* Check prefix. */
1832 if (lua_gettop(L) >= 3) {
1833 if (lua_type(L, 3) != LUA_TSTRING)
1834 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1835 pattern = lua_tolstring(L, 3, &len);
1836 luaL_addlstring(&socket->b, pattern, len);
1837 }
1838
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001839 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001840}
1841
1842/* Write the Lua input string in the output buffer.
1843 * This fucntion returns a yield if no space are available.
1844 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001845static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001846{
1847 struct hlua_socket *socket;
1848 struct hlua *hlua = hlua_gethlua(L);
1849 struct appctx *appctx;
1850 size_t buf_len;
1851 const char *buf;
1852 int len;
1853 int send_len;
1854 int sent;
1855
1856 /* Check if this lua stack is schedulable. */
1857 if (!hlua || !hlua->task)
1858 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1859 "'frontend', 'backend' or 'task'"));
1860
1861 /* Get object */
1862 socket = MAY_LJMP(hlua_checksocket(L, 1));
1863 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001864 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001865
1866 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001867 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001868 lua_pushinteger(L, -1);
1869 return 1;
1870 }
1871
1872 /* Update the input buffer data. */
1873 buf += sent;
1874 send_len = buf_len - sent;
1875
1876 /* All the data are sent. */
1877 if (sent >= buf_len)
1878 return 1; /* Implicitly return the length sent. */
1879
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001880 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1881 * the request buffer if its not required.
1882 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001883 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001884 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001885 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001886 goto hlua_socket_write_yield_return;
1887 }
1888 }
1889
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001890 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001891 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001892 if (len <= 0)
1893 goto hlua_socket_write_yield_return;
1894
1895 /* send data */
1896 if (len < send_len)
1897 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001898 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001899
1900 /* "Not enough space" (-1), "Buffer too little to contain
1901 * the data" (-2) are not expected because the available length
1902 * is tested.
1903 * Other unknown error are also not expected.
1904 */
1905 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001906 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001907 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001908
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001909 MAY_LJMP(hlua_socket_close(L));
1910 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001911 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001912 return 1;
1913 }
1914
1915 /* update buffers. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001916 stream_int_notify(&socket->s->si[0]);
1917 stream_int_update_applet(&socket->s->si[0]);
1918
Willy Tarreau94aa6172015-03-13 14:19:06 +01001919 socket->s->req.rex = TICK_ETERNITY;
1920 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001921
1922 /* Update length sent. */
1923 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001924 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001925
1926 /* All the data buffer is sent ? */
1927 if (sent + len >= buf_len)
1928 return 1;
1929
1930hlua_socket_write_yield_return:
1931 appctx = objt_appctx(socket->s->si[0].end);
1932 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1933 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001934 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001935 return 0;
1936}
1937
1938/* This function initiate the send of data. It just check the input
1939 * parameters and push an integer in the Lua stack that contain the
1940 * amount of data writed in the buffer. This is used by the function
1941 * "hlua_socket_write_yield" that can yield.
1942 *
1943 * The Lua function gets between 3 and 4 parameters. The first one is
1944 * the associated object. The second is a string buffer. The third is
1945 * a facultative integer that represents where is the buffer position
1946 * of the start of the data that can send. The first byte is the
1947 * position "1". The default value is "1". The fourth argument is a
1948 * facultative integer that represents where is the buffer position
1949 * of the end of the data that can send. The default is the last byte.
1950 */
1951static int hlua_socket_send(struct lua_State *L)
1952{
1953 int i;
1954 int j;
1955 const char *buf;
1956 size_t buf_len;
1957
1958 /* Check number of arguments. */
1959 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1960 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1961
1962 /* Get the string. */
1963 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1964
1965 /* Get and check j. */
1966 if (lua_gettop(L) == 4) {
1967 j = MAY_LJMP(luaL_checkinteger(L, 4));
1968 if (j < 0)
1969 j = buf_len + j + 1;
1970 if (j > buf_len)
1971 j = buf_len + 1;
1972 lua_pop(L, 1);
1973 }
1974 else
1975 j = buf_len;
1976
1977 /* Get and check i. */
1978 if (lua_gettop(L) == 3) {
1979 i = MAY_LJMP(luaL_checkinteger(L, 3));
1980 if (i < 0)
1981 i = buf_len + i + 1;
1982 if (i > buf_len)
1983 i = buf_len + 1;
1984 lua_pop(L, 1);
1985 } else
1986 i = 1;
1987
1988 /* Check bth i and j. */
1989 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001990 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001991 return 1;
1992 }
1993 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001994 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001995 return 1;
1996 }
1997 if (i == 0)
1998 i = 1;
1999 if (j == 0)
2000 j = 1;
2001
2002 /* Pop the string. */
2003 lua_pop(L, 1);
2004
2005 /* Update the buffer length. */
2006 buf += i - 1;
2007 buf_len = j - i + 1;
2008 lua_pushlstring(L, buf, buf_len);
2009
2010 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002011 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002012
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002013 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002014}
2015
Willy Tarreau22b0a682015-06-17 19:43:49 +02002016#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002017__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2018{
2019 static char buffer[SOCKET_INFO_MAX_LEN];
2020 int ret;
2021 int len;
2022 char *p;
2023
2024 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2025 if (ret <= 0) {
2026 lua_pushnil(L);
2027 return 1;
2028 }
2029
2030 if (ret == AF_UNIX) {
2031 lua_pushstring(L, buffer+1);
2032 return 1;
2033 }
2034 else if (ret == AF_INET6) {
2035 buffer[0] = '[';
2036 len = strlen(buffer);
2037 buffer[len] = ']';
2038 len++;
2039 buffer[len] = ':';
2040 len++;
2041 p = buffer;
2042 }
2043 else if (ret == AF_INET) {
2044 p = buffer + 1;
2045 len = strlen(p);
2046 p[len] = ':';
2047 len++;
2048 }
2049 else {
2050 lua_pushnil(L);
2051 return 1;
2052 }
2053
2054 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2055 lua_pushnil(L);
2056 return 1;
2057 }
2058
2059 lua_pushstring(L, p);
2060 return 1;
2061}
2062
2063/* Returns information about the peer of the connection. */
2064__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2065{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002066 struct hlua_socket *socket;
2067 struct connection *conn;
2068
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002069 MAY_LJMP(check_args(L, 1, "getpeername"));
2070
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002071 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002072
2073 /* Check if the tcp object is avalaible. */
2074 if (!socket->s) {
2075 lua_pushnil(L);
2076 return 1;
2077 }
2078
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002079 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002080 if (!conn) {
2081 lua_pushnil(L);
2082 return 1;
2083 }
2084
Willy Tarreaua71f6422016-11-16 17:00:14 +01002085 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002086 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Willy Tarreaua71f6422016-11-16 17:00:14 +01002087 lua_pushnil(L);
2088 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002089 }
2090
2091 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2092}
2093
2094/* Returns information about my connection side. */
2095static int hlua_socket_getsockname(struct lua_State *L)
2096{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002097 struct hlua_socket *socket;
2098 struct connection *conn;
2099
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002100 MAY_LJMP(check_args(L, 1, "getsockname"));
2101
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002102 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002103
2104 /* Check if the tcp object is avalaible. */
2105 if (!socket->s) {
2106 lua_pushnil(L);
2107 return 1;
2108 }
2109
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002110 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002111 if (!conn) {
2112 lua_pushnil(L);
2113 return 1;
2114 }
2115
Willy Tarreaua71f6422016-11-16 17:00:14 +01002116 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002117 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Willy Tarreaua71f6422016-11-16 17:00:14 +01002118 lua_pushnil(L);
2119 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002120 }
2121
2122 return hlua_socket_info(L, &conn->addr.from);
2123}
2124
2125/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002126static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002127 .obj_type = OBJ_TYPE_APPLET,
2128 .name = "<LUA_TCP>",
2129 .fct = hlua_socket_handler,
2130 .release = hlua_socket_release,
2131};
2132
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002133__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002134{
2135 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2136 struct hlua *hlua = hlua_gethlua(L);
2137 struct appctx *appctx;
2138
2139 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002140 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002141 lua_pushnil(L);
2142 lua_pushstring(L, "Can't connect");
2143 return 2;
2144 }
2145
2146 appctx = objt_appctx(socket->s->si[0].end);
2147
2148 /* Check for connection established. */
2149 if (appctx->ctx.hlua.connected) {
2150 lua_pushinteger(L, 1);
2151 return 1;
2152 }
2153
2154 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2155 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002156 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002157 return 0;
2158}
2159
2160/* This function fail or initite the connection. */
2161__LJMP static int hlua_socket_connect(struct lua_State *L)
2162{
2163 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002164 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002165 const char *ip;
2166 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002167 struct hlua *hlua;
2168 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002169 int low, high;
2170 struct sockaddr_storage *addr;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002171
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002172 if (lua_gettop(L) < 2)
2173 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002174
2175 /* Get args. */
2176 socket = MAY_LJMP(hlua_checksocket(L, 1));
2177 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002178 if (lua_gettop(L) >= 3)
2179 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002180
Willy Tarreau973a5422015-08-05 21:47:23 +02002181 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002182 if (!conn)
2183 WILL_LJMP(luaL_error(L, "connect: internal error"));
2184
Willy Tarreau3adac082015-09-26 17:51:09 +02002185 /* needed for the connection not to be closed */
2186 conn->target = socket->s->target;
2187
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002188 /* Parse ip address. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002189 addr = str2sa_range(ip, &low, &high, NULL, NULL, NULL, 0);
2190 if (!addr)
2191 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
2192 if (low != high)
2193 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
2194 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002195
2196 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002197 if (low == 0) {
2198 if (conn->addr.to.ss_family == AF_INET) {
2199 if (port == -1)
2200 WILL_LJMP(luaL_error(L, "connect: port missing"));
2201 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2202 } else if (conn->addr.to.ss_family == AF_INET6) {
2203 if (port == -1)
2204 WILL_LJMP(luaL_error(L, "connect: port missing"));
2205 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2206 }
2207 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002208
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002209 hlua = hlua_gethlua(L);
2210 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002211
2212 /* inform the stream that we want to be notified whenever the
2213 * connection completes.
2214 */
2215 si_applet_cant_get(&socket->s->si[0]);
2216 si_applet_cant_put(&socket->s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002217 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002218
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002219 hlua->flags |= HLUA_MUST_GC;
2220
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002221 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2222 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002223 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002224
2225 return 0;
2226}
2227
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002228#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002229__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2230{
2231 struct hlua_socket *socket;
2232
2233 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2234 socket = MAY_LJMP(hlua_checksocket(L, 1));
2235 socket->s->target = &socket_ssl.obj_type;
2236 return MAY_LJMP(hlua_socket_connect(L));
2237}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002238#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002239
2240__LJMP static int hlua_socket_setoption(struct lua_State *L)
2241{
2242 return 0;
2243}
2244
2245__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2246{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002247 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002248 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002249
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002250 MAY_LJMP(check_args(L, 2, "settimeout"));
2251
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002252 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002253 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002254
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002255 socket->s->req.rto = tmout;
2256 socket->s->req.wto = tmout;
2257 socket->s->res.rto = tmout;
2258 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002259
2260 return 0;
2261}
2262
2263__LJMP static int hlua_socket_new(lua_State *L)
2264{
2265 struct hlua_socket *socket;
2266 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002267 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002268 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002269 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002270
2271 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002272 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002273 hlua_pusherror(L, "socket: full stack");
2274 goto out_fail_conf;
2275 }
2276
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002277 /* Create the object: obj[0] = userdata. */
2278 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002279 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002280 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002281 memset(socket, 0, sizeof(*socket));
2282
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002283 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002284 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002285 hlua_pusherror(L, "socket: uninitialized pools.");
2286 goto out_fail_conf;
2287 }
2288
Willy Tarreau87b09662015-04-03 00:22:06 +02002289 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002290 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2291 lua_setmetatable(L, -2);
2292
Willy Tarreaud420a972015-04-06 00:39:18 +02002293 /* Create the applet context */
2294 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002295 if (!appctx) {
2296 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002297 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002298 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002299
Willy Tarreaud420a972015-04-06 00:39:18 +02002300 appctx->ctx.hlua.socket = socket;
2301 appctx->ctx.hlua.connected = 0;
2302 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2303 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002304
Willy Tarreaud420a972015-04-06 00:39:18 +02002305 /* Now create a session, task and stream for this applet */
2306 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2307 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002308 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002309 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002310 }
2311
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002312 task = task_new();
2313 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002314 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002315 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002316 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002317 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002318
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002319 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002320 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002322 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323 }
2324
Willy Tarreaud420a972015-04-06 00:39:18 +02002325 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002326 socket->s = strm;
2327 strm->hlua.T = NULL;
2328 strm->hlua.Tref = LUA_REFNIL;
2329 strm->hlua.Mref = LUA_REFNIL;
2330 strm->hlua.nargs = 0;
2331 strm->hlua.flags = 0;
2332 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002333
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002334 /* Configure "right" stream interface. this "si" is used to connect
2335 * and retrieve data from the server. The connection is initialized
2336 * with the "struct server".
2337 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002338 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002339
2340 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002341 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2342 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002343
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002344 /* Update statistics counters. */
2345 socket_proxy.feconn++; /* beconn will be increased later */
2346 jobs++;
2347 totalconn++;
2348
2349 /* Return yield waiting for connection. */
2350 return 1;
2351
Willy Tarreaud420a972015-04-06 00:39:18 +02002352 out_fail_stream:
2353 task_free(task);
2354 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002355 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002356 out_fail_sess:
2357 appctx_free(appctx);
2358 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002359 WILL_LJMP(lua_error(L));
2360 return 0;
2361}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002362
2363/*
2364 *
2365 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002366 * Class Channel
2367 *
2368 *
2369 */
2370
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002371/* The state between the channel data and the HTTP parser state can be
2372 * unconsistent, so reset the parser and call it again. Warning, this
2373 * action not revalidate the request and not send a 400 if the modified
2374 * resuest is not valid.
2375 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002376 * This function never fails. The direction is set using dir, which equals
2377 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002378 */
2379static void hlua_resynchonize_proto(struct stream *stream, int dir)
2380{
2381 /* Protocol HTTP. */
2382 if (stream->be->mode == PR_MODE_HTTP) {
2383
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002384 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002385 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002386 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002387 http_txn_reset_res(stream->txn);
2388
2389 if (stream->txn->hdr_idx.v)
2390 hdr_idx_init(&stream->txn->hdr_idx);
2391
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002392 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002393 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002394 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002395 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2396 }
2397}
2398
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002399/* Check the protocole integrity after the Lua manipulations. Close the stream
2400 * and returns 0 if fails, otherwise returns 1. The direction is set using dir,
2401 * which equals either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002402 */
2403static int hlua_check_proto(struct stream *stream, int dir)
2404{
2405 const struct chunk msg = { .len = 0 };
2406
Willy Tarreau9af89f72015-09-26 11:50:08 +02002407 /* Protocol HTTP. The message parsing state must match the request or
2408 * response state. The problem that may happen is that Lua modifies
2409 * the request or response message *after* it was parsed, and corrupted
2410 * it so that it could not be processed anymore. We just need to verify
2411 * if the parser is still expected to run or not.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002412 */
2413 if (stream->be->mode == PR_MODE_HTTP) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002414 if (dir == SMP_OPT_DIR_REQ &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002415 !(stream->req.analysers & AN_REQ_WAIT_HTTP) &&
Thierry FOURNIER / OZON.IO8dc73162016-11-18 19:06:21 +01002416 stream->txn->req.msg_state < HTTP_MSG_ERROR) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002417 stream_int_retnclose(&stream->si[0], &msg);
2418 return 0;
2419 }
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002420 else if (dir == SMP_OPT_DIR_RES &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002421 !(stream->res.analysers & AN_RES_WAIT_HTTP) &&
Thierry FOURNIER / OZON.IO8dc73162016-11-18 19:06:21 +01002422 stream->txn->rsp.msg_state < HTTP_MSG_ERROR) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002423 stream_int_retnclose(&stream->si[0], &msg);
2424 return 0;
2425 }
2426 }
2427 return 1;
2428}
2429
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002430/* Returns the struct hlua_channel join to the class channel in the
2431 * stack entry "ud" or throws an argument error.
2432 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002433__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002434{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002435 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002436}
2437
Willy Tarreau47860ed2015-03-10 14:07:50 +01002438/* Pushes the channel onto the top of the stack. If the stask does not have a
2439 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002440 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002441static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002442{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002443 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002444 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002445 return 0;
2446
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002447 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002448 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002449 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002450
2451 /* Pop a class sesison metatable and affect it to the userdata. */
2452 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2453 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002454 return 1;
2455}
2456
2457/* Duplicate all the data present in the input channel and put it
2458 * in a string LUA variables. Returns -1 and push a nil value in
2459 * the stack if the channel is closed and all the data are consumed,
2460 * returns 0 if no data are available, otherwise it returns the length
2461 * of the builded string.
2462 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002463static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002464{
2465 char *blk1;
2466 char *blk2;
2467 int len1;
2468 int len2;
2469 int ret;
2470 luaL_Buffer b;
2471
Willy Tarreau47860ed2015-03-10 14:07:50 +01002472 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002473 if (unlikely(ret == 0))
2474 return 0;
2475
2476 if (unlikely(ret < 0)) {
2477 lua_pushnil(L);
2478 return -1;
2479 }
2480
2481 luaL_buffinit(L, &b);
2482 luaL_addlstring(&b, blk1, len1);
2483 if (unlikely(ret == 2))
2484 luaL_addlstring(&b, blk2, len2);
2485 luaL_pushresult(&b);
2486
2487 if (unlikely(ret == 2))
2488 return len1 + len2;
2489 return len1;
2490}
2491
2492/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2493 * a yield. This function keep the data in the buffer.
2494 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002495__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002496{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002497 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002498
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002499 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2500
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002501 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002502 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002503 return 1;
2504}
2505
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002506/* Check arguments for the function "hlua_channel_dup_yield". */
2507__LJMP static int hlua_channel_dup(lua_State *L)
2508{
2509 MAY_LJMP(check_args(L, 1, "dup"));
2510 MAY_LJMP(hlua_checkchannel(L, 1));
2511 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2512}
2513
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002514/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2515 * a yield. This function consumes the data in the buffer. It returns
2516 * a string containing the data or a nil pointer if no data are available
2517 * and the channel is closed.
2518 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002519__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002520{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002521 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002522 int ret;
2523
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002524 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002525
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002526 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002527 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002528 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002529
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002530 if (unlikely(ret == -1))
2531 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002532
Willy Tarreau47860ed2015-03-10 14:07:50 +01002533 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002534 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002535 return 1;
2536}
2537
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002538/* Check arguments for the fucntion "hlua_channel_get_yield". */
2539__LJMP static int hlua_channel_get(lua_State *L)
2540{
2541 MAY_LJMP(check_args(L, 1, "get"));
2542 MAY_LJMP(hlua_checkchannel(L, 1));
2543 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2544}
2545
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002546/* This functions consumes and returns one line. If the channel is closed,
2547 * and the last data does not contains a final '\n', the data are returned
2548 * without the final '\n'. When no more data are avalaible, it returns nil
2549 * value.
2550 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002551__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002552{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002553 char *blk1;
2554 char *blk2;
2555 int len1;
2556 int len2;
2557 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002558 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002559 int ret;
2560 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002561
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002562 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2563
Willy Tarreau47860ed2015-03-10 14:07:50 +01002564 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002565 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002566 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002567
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002568 if (ret == -1) {
2569 lua_pushnil(L);
2570 return 1;
2571 }
2572
2573 luaL_buffinit(L, &b);
2574 luaL_addlstring(&b, blk1, len1);
2575 len = len1;
2576 if (unlikely(ret == 2)) {
2577 luaL_addlstring(&b, blk2, len2);
2578 len += len2;
2579 }
2580 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002581 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002582 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002583 return 1;
2584}
2585
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002586/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2587__LJMP static int hlua_channel_getline(lua_State *L)
2588{
2589 MAY_LJMP(check_args(L, 1, "getline"));
2590 MAY_LJMP(hlua_checkchannel(L, 1));
2591 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2592}
2593
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002594/* This function takes a string as input, and append it at the
2595 * input side of channel. If the data is too big, but a space
2596 * is probably available after sending some data, the function
2597 * yield. If the data is bigger than the buffer, or if the
2598 * channel is closed, it returns -1. otherwise, it returns the
2599 * amount of data writed.
2600 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002601__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002602{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002603 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002604 size_t len;
2605 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2606 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2607 int ret;
2608 int max;
2609
Willy Tarreau47860ed2015-03-10 14:07:50 +01002610 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002611 if (max > len - l)
2612 max = len - l;
2613
Willy Tarreau47860ed2015-03-10 14:07:50 +01002614 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002615 if (ret == -2 || ret == -3) {
2616 lua_pushinteger(L, -1);
2617 return 1;
2618 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002619 if (ret == -1) {
2620 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002621 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002622 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002623 l += ret;
2624 lua_pop(L, 1);
2625 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002626 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002627
Willy Tarreau47860ed2015-03-10 14:07:50 +01002628 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2629 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002630 /* There are no space avalaible, and the output buffer is empty.
2631 * in this case, we cannot add more data, so we cannot yield,
2632 * we return the amount of copyied data.
2633 */
2634 return 1;
2635 }
2636 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002637 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002638 return 1;
2639}
2640
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002641/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002642 * of the writed string, or -1 if the channel is closed or if the
2643 * buffer size is too little for the data.
2644 */
2645__LJMP static int hlua_channel_append(lua_State *L)
2646{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002647 size_t len;
2648
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002649 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002650 MAY_LJMP(hlua_checkchannel(L, 1));
2651 MAY_LJMP(luaL_checklstring(L, 2, &len));
2652 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002653 lua_pushinteger(L, 0);
2654
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002655 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002656}
2657
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002658/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002659 * his process by cleaning the buffer. The result is a replacement
2660 * of the current data. It returns the length of the writed string,
2661 * or -1 if the channel is closed or if the buffer size is too
2662 * little for the data.
2663 */
2664__LJMP static int hlua_channel_set(lua_State *L)
2665{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002666 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002667
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002668 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002669 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002670 lua_pushinteger(L, 0);
2671
Willy Tarreau47860ed2015-03-10 14:07:50 +01002672 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002673
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002674 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002675}
2676
2677/* Append data in the output side of the buffer. This data is immediatly
2678 * sent. The fcuntion returns the ammount of data writed. If the buffer
2679 * cannot contains the data, the function yield. The function returns -1
2680 * if the channel is closed.
2681 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002682__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002683{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002684 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002685 size_t len;
2686 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2687 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2688 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002689 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002690
Willy Tarreau47860ed2015-03-10 14:07:50 +01002691 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002692 lua_pushinteger(L, -1);
2693 return 1;
2694 }
2695
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002696 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2697 * the request buffer if its not required.
2698 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002699 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002700 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002701 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002702 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002703 }
2704 }
2705
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002706 /* the writed data will be immediatly sent, so we can check
2707 * the avalaible space without taking in account the reserve.
2708 * The reserve is guaranted for the processing of incoming
2709 * data, because the buffer will be flushed.
2710 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002711 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002712
2713 /* If there are no space avalaible, and the output buffer is empty.
2714 * in this case, we cannot add more data, so we cannot yield,
2715 * we return the amount of copyied data.
2716 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002717 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002718 return 1;
2719
2720 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002721 if (max > len - l)
2722 max = len - l;
2723
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002724 /* The buffer avalaible size may be not contiguous. This test
2725 * detects a non contiguous buffer and realign it.
2726 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002727 if (bi_space_for_replace(chn->buf) < max)
2728 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002729
2730 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002731 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002732
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002733 /* buffer replace considers that the input part is filled.
2734 * so, I must forward these new data in the output part.
2735 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002736 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002737
2738 l += max;
2739 lua_pop(L, 1);
2740 lua_pushinteger(L, l);
2741
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002742 /* If there are no space avalaible, and the output buffer is empty.
2743 * in this case, we cannot add more data, so we cannot yield,
2744 * we return the amount of copyied data.
2745 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002746 max = chn->buf->size - buffer_len(chn->buf);
2747 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002748 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002749
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002750 if (l < len) {
2751 /* If we are waiting for space in the response buffer, we
2752 * must set the flag WAKERESWR. This flag required the task
2753 * wake up if any activity is detected on the response buffer.
2754 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002755 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002756 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002757 else
2758 HLUA_SET_WAKEREQWR(hlua);
2759 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002760 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002761
2762 return 1;
2763}
2764
2765/* Just a wraper of "_hlua_channel_send". This wrapper permits
2766 * yield the LUA process, and resume it without checking the
2767 * input arguments.
2768 */
2769__LJMP static int hlua_channel_send(lua_State *L)
2770{
2771 MAY_LJMP(check_args(L, 2, "send"));
2772 lua_pushinteger(L, 0);
2773
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002774 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002775}
2776
2777/* This function forward and amount of butes. The data pass from
2778 * the input side of the buffer to the output side, and can be
2779 * forwarded. This function never fails.
2780 *
2781 * The Lua function takes an amount of bytes to be forwarded in
2782 * imput. It returns the number of bytes forwarded.
2783 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002784__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002785{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002786 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002787 int len;
2788 int l;
2789 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002790 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002791
2792 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2793 len = MAY_LJMP(luaL_checkinteger(L, 2));
2794 l = MAY_LJMP(luaL_checkinteger(L, -1));
2795
2796 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002797 if (max > chn->buf->i)
2798 max = chn->buf->i;
2799 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002800 l += max;
2801
2802 lua_pop(L, 1);
2803 lua_pushinteger(L, l);
2804
2805 /* Check if it miss bytes to forward. */
2806 if (l < len) {
2807 /* The the input channel or the output channel are closed, we
2808 * must return the amount of data forwarded.
2809 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002810 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002811 return 1;
2812
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002813 /* If we are waiting for space data in the response buffer, we
2814 * must set the flag WAKERESWR. This flag required the task
2815 * wake up if any activity is detected on the response buffer.
2816 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002817 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002818 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002819 else
2820 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002821
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002822 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002823 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002824 }
2825
2826 return 1;
2827}
2828
2829/* Just check the input and prepare the stack for the previous
2830 * function "hlua_channel_forward_yield"
2831 */
2832__LJMP static int hlua_channel_forward(lua_State *L)
2833{
2834 MAY_LJMP(check_args(L, 2, "forward"));
2835 MAY_LJMP(hlua_checkchannel(L, 1));
2836 MAY_LJMP(luaL_checkinteger(L, 2));
2837
2838 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002839 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002840}
2841
2842/* Just returns the number of bytes available in the input
2843 * side of the buffer. This function never fails.
2844 */
2845__LJMP static int hlua_channel_get_in_len(lua_State *L)
2846{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002847 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002848
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002849 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002850 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002851 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002852 return 1;
2853}
2854
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01002855/* Returns true if the channel is full. */
2856__LJMP static int hlua_channel_is_full(lua_State *L)
2857{
2858 struct channel *chn;
2859 int rem;
2860
2861 MAY_LJMP(check_args(L, 1, "is_full"));
2862 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2863
2864 rem = chn->buf->size;
2865 rem -= chn->buf->o; /* Output size */
2866 rem -= chn->buf->i; /* Input size */
2867 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
2868
2869 lua_pushboolean(L, rem <= 0);
2870 return 1;
2871}
2872
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002873/* Just returns the number of bytes available in the output
2874 * side of the buffer. This function never fails.
2875 */
2876__LJMP static int hlua_channel_get_out_len(lua_State *L)
2877{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002878 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002879
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002880 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002881 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002882 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002883 return 1;
2884}
2885
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002886/*
2887 *
2888 *
2889 * Class Fetches
2890 *
2891 *
2892 */
2893
2894/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002895 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002896 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002897__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002898{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002899 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002900}
2901
2902/* This function creates and push in the stack a fetch object according
2903 * with a current TXN.
2904 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002905static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002906{
Willy Tarreau7073c472015-04-06 11:15:40 +02002907 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002908
2909 /* Check stack size. */
2910 if (!lua_checkstack(L, 3))
2911 return 0;
2912
2913 /* Create the object: obj[0] = userdata.
2914 * Note that the base of the Fetches object is the
2915 * transaction object.
2916 */
2917 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002918 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002919 lua_rawseti(L, -2, 0);
2920
Willy Tarreau7073c472015-04-06 11:15:40 +02002921 hsmp->s = txn->s;
2922 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01002923 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002924 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002925
2926 /* Pop a class sesison metatable and affect it to the userdata. */
2927 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2928 lua_setmetatable(L, -2);
2929
2930 return 1;
2931}
2932
2933/* This function is an LUA binding. It is called with each sample-fetch.
2934 * It uses closure argument to store the associated sample-fetch. It
2935 * returns only one argument or throws an error. An error is thrown
2936 * only if an error is encountered during the argument parsing. If
2937 * the "sample-fetch" function fails, nil is returned.
2938 */
2939__LJMP static int hlua_run_sample_fetch(lua_State *L)
2940{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002941 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002942 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002943 struct arg args[ARGM_NBARGS + 1];
2944 int i;
2945 struct sample smp;
2946
2947 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002948 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002949
2950 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002951 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002952
Thierry FOURNIERca988662015-12-20 18:43:03 +01002953 /* Check execution authorization. */
2954 if (f->use & SMP_USE_HTTP_ANY &&
2955 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
2956 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
2957 "is not available in Lua services", f->kw);
2958 WILL_LJMP(lua_error(L));
2959 }
2960
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002961 /* Get extra arguments. */
2962 for (i = 0; i < lua_gettop(L) - 1; i++) {
2963 if (i >= ARGM_NBARGS)
2964 break;
2965 hlua_lua2arg(L, i + 2, &args[i]);
2966 }
2967 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01002968 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002969
2970 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002971 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002972
2973 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002974 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002975 lua_pushfstring(L, "error in arguments");
2976 WILL_LJMP(lua_error(L));
2977 }
2978
2979 /* Initialise the sample. */
2980 memset(&smp, 0, sizeof(smp));
2981
2982 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01002983 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02002984 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002985 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002986 lua_pushstring(L, "");
2987 else
2988 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002989 return 1;
2990 }
2991
2992 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002993 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002994 hlua_smp2lua_str(L, &smp);
2995 else
2996 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002997 return 1;
2998}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002999
3000/*
3001 *
3002 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003003 * Class Converters
3004 *
3005 *
3006 */
3007
3008/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003009 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003010 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003011__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003012{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003013 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003014}
3015
3016/* This function creates and push in the stack a Converters object
3017 * according with a current TXN.
3018 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003019static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003020{
Willy Tarreau7073c472015-04-06 11:15:40 +02003021 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003022
3023 /* Check stack size. */
3024 if (!lua_checkstack(L, 3))
3025 return 0;
3026
3027 /* Create the object: obj[0] = userdata.
3028 * Note that the base of the Converters object is the
3029 * same than the TXN object.
3030 */
3031 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003032 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003033 lua_rawseti(L, -2, 0);
3034
Willy Tarreau7073c472015-04-06 11:15:40 +02003035 hsmp->s = txn->s;
3036 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003037 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003038 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003039
Willy Tarreau87b09662015-04-03 00:22:06 +02003040 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003041 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3042 lua_setmetatable(L, -2);
3043
3044 return 1;
3045}
3046
3047/* This function is an LUA binding. It is called with each converter.
3048 * It uses closure argument to store the associated converter. It
3049 * returns only one argument or throws an error. An error is thrown
3050 * only if an error is encountered during the argument parsing. If
3051 * the converter function function fails, nil is returned.
3052 */
3053__LJMP static int hlua_run_sample_conv(lua_State *L)
3054{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003055 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003056 struct sample_conv *conv;
3057 struct arg args[ARGM_NBARGS + 1];
3058 int i;
3059 struct sample smp;
3060
3061 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003062 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003063
3064 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003065 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003066
3067 /* Get extra arguments. */
3068 for (i = 0; i < lua_gettop(L) - 2; i++) {
3069 if (i >= ARGM_NBARGS)
3070 break;
3071 hlua_lua2arg(L, i + 3, &args[i]);
3072 }
3073 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003074 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003075
3076 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003077 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003078
3079 /* Run the special args checker. */
3080 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3081 hlua_pusherror(L, "error in arguments");
3082 WILL_LJMP(lua_error(L));
3083 }
3084
3085 /* Initialise the sample. */
3086 if (!hlua_lua2smp(L, 2, &smp)) {
3087 hlua_pusherror(L, "error in the input argument");
3088 WILL_LJMP(lua_error(L));
3089 }
3090
Willy Tarreau1777ea62016-03-10 16:15:46 +01003091 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3092
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003093 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003094 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003095 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003096 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003097 WILL_LJMP(lua_error(L));
3098 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003099 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3100 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003101 hlua_pusherror(L, "error during the input argument casting");
3102 WILL_LJMP(lua_error(L));
3103 }
3104
3105 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003106 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003107 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003108 lua_pushstring(L, "");
3109 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003110 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003111 return 1;
3112 }
3113
3114 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003115 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003116 hlua_smp2lua_str(L, &smp);
3117 else
3118 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003119 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003120}
3121
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003122/*
3123 *
3124 *
3125 * Class AppletTCP
3126 *
3127 *
3128 */
3129
3130/* Returns a struct hlua_txn if the stack entry "ud" is
3131 * a class stream, otherwise it throws an error.
3132 */
3133__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3134{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003135 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003136}
3137
3138/* This function creates and push in the stack an Applet object
3139 * according with a current TXN.
3140 */
3141static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3142{
3143 struct hlua_appctx *appctx;
3144 struct stream_interface *si = ctx->owner;
3145 struct stream *s = si_strm(si);
3146 struct proxy *p = s->be;
3147
3148 /* Check stack size. */
3149 if (!lua_checkstack(L, 3))
3150 return 0;
3151
3152 /* Create the object: obj[0] = userdata.
3153 * Note that the base of the Converters object is the
3154 * same than the TXN object.
3155 */
3156 lua_newtable(L);
3157 appctx = lua_newuserdata(L, sizeof(*appctx));
3158 lua_rawseti(L, -2, 0);
3159 appctx->appctx = ctx;
3160 appctx->htxn.s = s;
3161 appctx->htxn.p = p;
3162
3163 /* Create the "f" field that contains a list of fetches. */
3164 lua_pushstring(L, "f");
3165 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3166 return 0;
3167 lua_settable(L, -3);
3168
3169 /* Create the "sf" field that contains a list of stringsafe fetches. */
3170 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003171 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003172 return 0;
3173 lua_settable(L, -3);
3174
3175 /* Create the "c" field that contains a list of converters. */
3176 lua_pushstring(L, "c");
3177 if (!hlua_converters_new(L, &appctx->htxn, 0))
3178 return 0;
3179 lua_settable(L, -3);
3180
3181 /* Create the "sc" field that contains a list of stringsafe converters. */
3182 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003183 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003184 return 0;
3185 lua_settable(L, -3);
3186
3187 /* Pop a class stream metatable and affect it to the table. */
3188 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3189 lua_setmetatable(L, -2);
3190
3191 return 1;
3192}
3193
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003194__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3195{
3196 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3197 struct stream *s = appctx->htxn.s;
3198 struct hlua *hlua = &s->hlua;
3199
3200 MAY_LJMP(check_args(L, 2, "set_priv"));
3201
3202 /* Remove previous value. */
3203 if (hlua->Mref != -1)
3204 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3205
3206 /* Get and store new value. */
3207 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3208 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3209
3210 return 0;
3211}
3212
3213__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3214{
3215 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3216 struct stream *s = appctx->htxn.s;
3217 struct hlua *hlua = &s->hlua;
3218
3219 /* Push configuration index in the stack. */
3220 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3221
3222 return 1;
3223}
3224
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003225/* If expected data not yet available, it returns a yield. This function
3226 * consumes the data in the buffer. It returns a string containing the
3227 * data. This string can be empty.
3228 */
3229__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3230{
3231 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3232 struct stream_interface *si = appctx->appctx->owner;
3233 int ret;
3234 char *blk1;
3235 int len1;
3236 char *blk2;
3237 int len2;
3238
3239 /* Read the maximum amount of data avalaible. */
3240 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3241
3242 /* Data not yet avalaible. return yield. */
3243 if (ret == 0) {
3244 si_applet_cant_get(si);
3245 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3246 }
3247
3248 /* End of data: commit the total strings and return. */
3249 if (ret < 0) {
3250 luaL_pushresult(&appctx->b);
3251 return 1;
3252 }
3253
3254 /* Ensure that the block 2 length is usable. */
3255 if (ret == 1)
3256 len2 = 0;
3257
3258 /* dont check the max length read and dont check. */
3259 luaL_addlstring(&appctx->b, blk1, len1);
3260 luaL_addlstring(&appctx->b, blk2, len2);
3261
3262 /* Consume input channel output buffer data. */
3263 bo_skip(si_oc(si), len1 + len2);
3264 luaL_pushresult(&appctx->b);
3265 return 1;
3266}
3267
3268/* Check arguments for the fucntion "hlua_channel_get_yield". */
3269__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3270{
3271 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3272
3273 /* Initialise the string catenation. */
3274 luaL_buffinit(L, &appctx->b);
3275
3276 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3277}
3278
3279/* If expected data not yet available, it returns a yield. This function
3280 * consumes the data in the buffer. It returns a string containing the
3281 * data. This string can be empty.
3282 */
3283__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3284{
3285 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3286 struct stream_interface *si = appctx->appctx->owner;
3287 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3288 int ret;
3289 char *blk1;
3290 int len1;
3291 char *blk2;
3292 int len2;
3293
3294 /* Read the maximum amount of data avalaible. */
3295 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3296
3297 /* Data not yet avalaible. return yield. */
3298 if (ret == 0) {
3299 si_applet_cant_get(si);
3300 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3301 }
3302
3303 /* End of data: commit the total strings and return. */
3304 if (ret < 0) {
3305 luaL_pushresult(&appctx->b);
3306 return 1;
3307 }
3308
3309 /* Ensure that the block 2 length is usable. */
3310 if (ret == 1)
3311 len2 = 0;
3312
3313 if (len == -1) {
3314
3315 /* If len == -1, catenate all the data avalaile and
3316 * yield because we want to get all the data until
3317 * the end of data stream.
3318 */
3319 luaL_addlstring(&appctx->b, blk1, len1);
3320 luaL_addlstring(&appctx->b, blk2, len2);
3321 bo_skip(si_oc(si), len1 + len2);
3322 si_applet_cant_get(si);
3323 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3324
3325 } else {
3326
3327 /* Copy the fisrt block caping to the length required. */
3328 if (len1 > len)
3329 len1 = len;
3330 luaL_addlstring(&appctx->b, blk1, len1);
3331 len -= len1;
3332
3333 /* Copy the second block. */
3334 if (len2 > len)
3335 len2 = len;
3336 luaL_addlstring(&appctx->b, blk2, len2);
3337 len -= len2;
3338
3339 /* Consume input channel output buffer data. */
3340 bo_skip(si_oc(si), len1 + len2);
3341
3342 /* If we are no other data avalaible, yield waiting for new data. */
3343 if (len > 0) {
3344 lua_pushinteger(L, len);
3345 lua_replace(L, 2);
3346 si_applet_cant_get(si);
3347 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3348 }
3349
3350 /* return the result. */
3351 luaL_pushresult(&appctx->b);
3352 return 1;
3353 }
3354
3355 /* we never executes this */
3356 hlua_pusherror(L, "Lua: internal error");
3357 WILL_LJMP(lua_error(L));
3358 return 0;
3359}
3360
3361/* Check arguments for the fucntion "hlua_channel_get_yield". */
3362__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3363{
3364 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3365 int len = -1;
3366
3367 if (lua_gettop(L) > 2)
3368 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3369 if (lua_gettop(L) >= 2) {
3370 len = MAY_LJMP(luaL_checkinteger(L, 2));
3371 lua_pop(L, 1);
3372 }
3373
3374 /* Confirm or set the required length */
3375 lua_pushinteger(L, len);
3376
3377 /* Initialise the string catenation. */
3378 luaL_buffinit(L, &appctx->b);
3379
3380 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3381}
3382
3383/* Append data in the output side of the buffer. This data is immediatly
3384 * sent. The fcuntion returns the ammount of data writed. If the buffer
3385 * cannot contains the data, the function yield. The function returns -1
3386 * if the channel is closed.
3387 */
3388__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3389{
3390 size_t len;
3391 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3392 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3393 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3394 struct stream_interface *si = appctx->appctx->owner;
3395 struct channel *chn = si_ic(si);
3396 int max;
3397
3398 /* Get the max amount of data which can write as input in the channel. */
3399 max = channel_recv_max(chn);
3400 if (max > (len - l))
3401 max = len - l;
3402
3403 /* Copy data. */
3404 bi_putblk(chn, str + l, max);
3405
3406 /* update counters. */
3407 l += max;
3408 lua_pop(L, 1);
3409 lua_pushinteger(L, l);
3410
3411 /* If some data is not send, declares the situation to the
3412 * applet, and returns a yield.
3413 */
3414 if (l < len) {
3415 si_applet_cant_put(si);
3416 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3417 }
3418
3419 return 1;
3420}
3421
3422/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3423 * yield the LUA process, and resume it without checking the
3424 * input arguments.
3425 */
3426__LJMP static int hlua_applet_tcp_send(lua_State *L)
3427{
3428 MAY_LJMP(check_args(L, 2, "send"));
3429 lua_pushinteger(L, 0);
3430
3431 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3432}
3433
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003434/*
3435 *
3436 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003437 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003438 *
3439 *
3440 */
3441
3442/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003443 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003444 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003445__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003446{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003447 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003448}
3449
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003450/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003451 * according with a current TXN.
3452 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003453static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003454{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003455 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003456 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003457 struct stream_interface *si = ctx->owner;
3458 struct stream *s = si_strm(si);
3459 struct proxy *px = s->be;
3460 struct http_txn *txn = s->txn;
3461 const char *path;
3462 const char *end;
3463 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003464
3465 /* Check stack size. */
3466 if (!lua_checkstack(L, 3))
3467 return 0;
3468
3469 /* Create the object: obj[0] = userdata.
3470 * Note that the base of the Converters object is the
3471 * same than the TXN object.
3472 */
3473 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003474 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003475 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003476 appctx->appctx = ctx;
3477 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
3478 appctx->htxn.s = s;
3479 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003480
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003481 /* Create the "f" field that contains a list of fetches. */
3482 lua_pushstring(L, "f");
3483 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3484 return 0;
3485 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003486
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003487 /* Create the "sf" field that contains a list of stringsafe fetches. */
3488 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003489 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003490 return 0;
3491 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003492
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003493 /* Create the "c" field that contains a list of converters. */
3494 lua_pushstring(L, "c");
3495 if (!hlua_converters_new(L, &appctx->htxn, 0))
3496 return 0;
3497 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003498
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003499 /* Create the "sc" field that contains a list of stringsafe converters. */
3500 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003501 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003502 return 0;
3503 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003504
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003505 /* Stores the request method. */
3506 lua_pushstring(L, "method");
3507 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3508 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003509
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003510 /* Stores the http version. */
3511 lua_pushstring(L, "version");
3512 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3513 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003514
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003515 /* creates an array of headers. hlua_http_get_headers() crates and push
3516 * the array on the top of the stack.
3517 */
3518 lua_pushstring(L, "headers");
3519 htxn.s = s;
3520 htxn.p = px;
3521 htxn.dir = SMP_OPT_DIR_REQ;
3522 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3523 return 0;
3524 lua_settable(L, -3);
3525
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003526 /* Get path and qs */
3527 path = http_get_path(txn);
3528 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3529 p = path;
3530 while (p < end && *p != '?')
3531 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003532
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003533 /* Stores the request path. */
3534 lua_pushstring(L, "path");
3535 lua_pushlstring(L, path, p - path);
3536 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003537
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003538 /* Stores the query string. */
3539 lua_pushstring(L, "qs");
3540 if (*p == '?')
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003541 p++;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003542 lua_pushlstring(L, p, end - p);
3543 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003544
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003545 /* Stores the request path. */
3546 lua_pushstring(L, "length");
3547 lua_pushinteger(L, txn->req.body_len);
3548 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003549
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003550 /* Create an array of HTTP request headers. */
3551 lua_pushstring(L, "headers");
3552 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3553 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003554
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003555 /* Create an empty array of HTTP request headers. */
3556 lua_pushstring(L, "response");
3557 lua_newtable(L);
3558 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003559
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003560 /* Pop a class stream metatable and affect it to the table. */
3561 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3562 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003563
3564 return 1;
3565}
3566
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003567__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3568{
3569 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3570 struct stream *s = appctx->htxn.s;
3571 struct hlua *hlua = &s->hlua;
3572
3573 MAY_LJMP(check_args(L, 2, "set_priv"));
3574
3575 /* Remove previous value. */
3576 if (hlua->Mref != -1)
3577 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3578
3579 /* Get and store new value. */
3580 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3581 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3582
3583 return 0;
3584}
3585
3586__LJMP static int hlua_applet_http_get_priv(lua_State *L)
3587{
3588 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3589 struct stream *s = appctx->htxn.s;
3590 struct hlua *hlua = &s->hlua;
3591
3592 /* Push configuration index in the stack. */
3593 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3594
3595 return 1;
3596}
3597
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003598/* If expected data not yet available, it returns a yield. This function
3599 * consumes the data in the buffer. It returns a string containing the
3600 * data. This string can be empty.
3601 */
3602__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003603{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003604 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3605 struct stream_interface *si = appctx->appctx->owner;
3606 struct channel *chn = si_ic(si);
3607 int ret;
3608 char *blk1;
3609 int len1;
3610 char *blk2;
3611 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003612
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003613 /* Maybe we cant send a 100-continue ? */
3614 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3615 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3616 /* if ret == -2 or -3 the channel closed or the message si too
3617 * big for the buffers. We cant send anything. So, we ignoring
3618 * the error, considers that the 100-continue is sent, and try
3619 * to receive.
3620 * If ret is -1, we dont have room in the buffer, so we yield.
3621 */
3622 if (ret == -1) {
3623 si_applet_cant_put(si);
3624 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3625 }
3626 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3627 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003628
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003629 /* Check for the end of the data. */
3630 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3631 luaL_pushresult(&appctx->b);
3632 return 1;
3633 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003634
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003635 /* Read the maximum amount of data avalaible. */
3636 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003637
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003638 /* Data not yet avalaible. return yield. */
3639 if (ret == 0) {
3640 si_applet_cant_get(si);
3641 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3642 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003643
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003644 /* End of data: commit the total strings and return. */
3645 if (ret < 0) {
3646 luaL_pushresult(&appctx->b);
3647 return 1;
3648 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003649
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003650 /* Ensure that the block 2 length is usable. */
3651 if (ret == 1)
3652 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003653
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003654 /* Copy the fisrt block caping to the length required. */
3655 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3656 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3657 luaL_addlstring(&appctx->b, blk1, len1);
3658 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003659
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003660 /* Copy the second block. */
3661 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3662 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3663 luaL_addlstring(&appctx->b, blk2, len2);
3664 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003665
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003666 /* Consume input channel output buffer data. */
3667 bo_skip(si_oc(si), len1 + len2);
3668 luaL_pushresult(&appctx->b);
3669 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003670}
3671
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003672/* Check arguments for the fucntion "hlua_channel_get_yield". */
3673__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003674{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003675 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003676
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003677 /* Initialise the string catenation. */
3678 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003679
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003680 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003681}
3682
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003683/* If expected data not yet available, it returns a yield. This function
3684 * consumes the data in the buffer. It returns a string containing the
3685 * data. This string can be empty.
3686 */
3687__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003688{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003689 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3690 struct stream_interface *si = appctx->appctx->owner;
3691 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3692 struct channel *chn = si_ic(si);
3693 int ret;
3694 char *blk1;
3695 int len1;
3696 char *blk2;
3697 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003698
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003699 /* Maybe we cant send a 100-continue ? */
3700 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3701 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3702 /* if ret == -2 or -3 the channel closed or the message si too
3703 * big for the buffers. We cant send anything. So, we ignoring
3704 * the error, considers that the 100-continue is sent, and try
3705 * to receive.
3706 * If ret is -1, we dont have room in the buffer, so we yield.
3707 */
3708 if (ret == -1) {
3709 si_applet_cant_put(si);
3710 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3711 }
3712 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3713 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003714
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003715 /* Read the maximum amount of data avalaible. */
3716 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003717
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003718 /* Data not yet avalaible. return yield. */
3719 if (ret == 0) {
3720 si_applet_cant_get(si);
3721 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3722 }
3723
3724 /* End of data: commit the total strings and return. */
3725 if (ret < 0) {
3726 luaL_pushresult(&appctx->b);
3727 return 1;
3728 }
3729
3730 /* Ensure that the block 2 length is usable. */
3731 if (ret == 1)
3732 len2 = 0;
3733
3734 /* Copy the fisrt block caping to the length required. */
3735 if (len1 > len)
3736 len1 = len;
3737 luaL_addlstring(&appctx->b, blk1, len1);
3738 len -= len1;
3739
3740 /* Copy the second block. */
3741 if (len2 > len)
3742 len2 = len;
3743 luaL_addlstring(&appctx->b, blk2, len2);
3744 len -= len2;
3745
3746 /* Consume input channel output buffer data. */
3747 bo_skip(si_oc(si), len1 + len2);
3748 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
3749 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
3750
3751 /* If we are no other data avalaible, yield waiting for new data. */
3752 if (len > 0) {
3753 lua_pushinteger(L, len);
3754 lua_replace(L, 2);
3755 si_applet_cant_get(si);
3756 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3757 }
3758
3759 /* return the result. */
3760 luaL_pushresult(&appctx->b);
3761 return 1;
3762}
3763
3764/* Check arguments for the fucntion "hlua_channel_get_yield". */
3765__LJMP static int hlua_applet_http_recv(lua_State *L)
3766{
3767 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3768 int len = -1;
3769
3770 /* Check arguments. */
3771 if (lua_gettop(L) > 2)
3772 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3773 if (lua_gettop(L) >= 2) {
3774 len = MAY_LJMP(luaL_checkinteger(L, 2));
3775 lua_pop(L, 1);
3776 }
3777
3778 /* Check the required length */
3779 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3780 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3781 lua_pushinteger(L, len);
3782
3783 /* Initialise the string catenation. */
3784 luaL_buffinit(L, &appctx->b);
3785
3786 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
3787}
3788
3789/* Append data in the output side of the buffer. This data is immediatly
3790 * sent. The fcuntion returns the ammount of data writed. If the buffer
3791 * cannot contains the data, the function yield. The function returns -1
3792 * if the channel is closed.
3793 */
3794__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
3795{
3796 size_t len;
3797 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3798 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3799 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3800 struct stream_interface *si = appctx->appctx->owner;
3801 struct channel *chn = si_ic(si);
3802 int max;
3803
3804 /* Get the max amount of data which can write as input in the channel. */
3805 max = channel_recv_max(chn);
3806 if (max > (len - l))
3807 max = len - l;
3808
3809 /* Copy data. */
3810 bi_putblk(chn, str + l, max);
3811
3812 /* update counters. */
3813 l += max;
3814 lua_pop(L, 1);
3815 lua_pushinteger(L, l);
3816
3817 /* If some data is not send, declares the situation to the
3818 * applet, and returns a yield.
3819 */
3820 if (l < len) {
3821 si_applet_cant_put(si);
3822 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
3823 }
3824
3825 return 1;
3826}
3827
3828/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
3829 * yield the LUA process, and resume it without checking the
3830 * input arguments.
3831 */
3832__LJMP static int hlua_applet_http_send(lua_State *L)
3833{
3834 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3835 size_t len;
3836 char hex[10];
3837
3838 MAY_LJMP(luaL_checklstring(L, 2, &len));
3839
3840 /* If transfer encoding chunked is selected, we surround the data
3841 * by chunk data.
3842 */
3843 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
3844 snprintf(hex, 9, "%x", (unsigned int)len);
3845 lua_pushfstring(L, "%s\r\n", hex);
3846 lua_insert(L, 2); /* swap the last 2 entries. */
3847 lua_pushstring(L, "\r\n");
3848 lua_concat(L, 3);
3849 }
3850
3851 /* This interger is used for followinf the amount of data sent. */
3852 lua_pushinteger(L, 0);
3853
3854 /* We want to send some data. Headers must be sent. */
3855 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
3856 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
3857 WILL_LJMP(lua_error(L));
3858 }
3859
3860 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
3861}
3862
3863__LJMP static int hlua_applet_http_addheader(lua_State *L)
3864{
3865 const char *name;
3866 int ret;
3867
3868 MAY_LJMP(hlua_checkapplet_http(L, 1));
3869 name = MAY_LJMP(luaL_checkstring(L, 2));
3870 MAY_LJMP(luaL_checkstring(L, 3));
3871
3872 /* Push in the stack the "response" entry. */
3873 ret = lua_getfield(L, 1, "response");
3874 if (ret != LUA_TTABLE) {
3875 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
3876 "is expected as an array. %s found", lua_typename(L, ret));
3877 WILL_LJMP(lua_error(L));
3878 }
3879
3880 /* check if the header is already registered if it is not
3881 * the case, register it.
3882 */
3883 ret = lua_getfield(L, -1, name);
3884 if (ret == LUA_TNIL) {
3885
3886 /* Entry not found. */
3887 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
3888
3889 /* Insert the new header name in the array in the top of the stack.
3890 * It left the new array in the top of the stack.
3891 */
3892 lua_newtable(L);
3893 lua_pushvalue(L, 2);
3894 lua_pushvalue(L, -2);
3895 lua_settable(L, -4);
3896
3897 } else if (ret != LUA_TTABLE) {
3898
3899 /* corruption error. */
3900 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
3901 "is expected as an array. %s found", name, lua_typename(L, ret));
3902 WILL_LJMP(lua_error(L));
3903 }
3904
3905 /* Now the top od thestack is an array of values. We push
3906 * the header value as new entry.
3907 */
3908 lua_pushvalue(L, 3);
3909 ret = lua_rawlen(L, -2);
3910 lua_rawseti(L, -2, ret + 1);
3911 lua_pushboolean(L, 1);
3912 return 1;
3913}
3914
3915__LJMP static int hlua_applet_http_status(lua_State *L)
3916{
3917 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3918 int status = MAY_LJMP(luaL_checkinteger(L, 2));
3919
3920 if (status < 100 || status > 599) {
3921 lua_pushboolean(L, 0);
3922 return 1;
3923 }
3924
3925 appctx->appctx->ctx.hlua_apphttp.status = status;
3926 lua_pushboolean(L, 1);
3927 return 1;
3928}
3929
3930/* We will build the status line and the headers of the HTTP response.
3931 * We will try send at once if its not possible, we give back the hand
3932 * waiting for more room.
3933 */
3934__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
3935{
3936 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3937 struct stream_interface *si = appctx->appctx->owner;
3938 struct channel *chn = si_ic(si);
3939 int ret;
3940 size_t len;
3941 const char *msg;
3942
3943 /* Get the message as the first argument on the stack. */
3944 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
3945
3946 /* Send the message at once. */
3947 ret = bi_putblk(chn, msg, len);
3948
3949 /* if ret == -2 or -3 the channel closed or the message si too
3950 * big for the buffers.
3951 */
3952 if (ret == -2 || ret == -3) {
3953 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
3954 WILL_LJMP(lua_error(L));
3955 }
3956
3957 /* If ret is -1, we dont have room in the buffer, so we yield. */
3958 if (ret == -1) {
3959 si_applet_cant_put(si);
3960 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
3961 }
3962
3963 /* Headers sent, set the flag. */
3964 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
3965 return 0;
3966}
3967
3968__LJMP static int hlua_applet_http_start_response(lua_State *L)
3969{
3970 struct chunk *tmp = get_trash_chunk();
3971 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003972 const char *name;
3973 const char *value;
3974 int id;
3975 int hdr_connection = 0;
3976 int hdr_contentlength = -1;
3977 int hdr_chunked = 0;
3978
3979 /* Use the same http version than the request. */
3980 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01003981 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003982 appctx->appctx->ctx.hlua_apphttp.status,
3983 get_reason(appctx->appctx->ctx.hlua_apphttp.status));
3984
3985 /* Get the array associated to the field "response" in the object AppletHTTP. */
3986 lua_pushvalue(L, 0);
3987 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
3988 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
3989 appctx->appctx->rule->arg.hlua_rule->fcn.name);
3990 WILL_LJMP(lua_error(L));
3991 }
3992
3993 /* Browse the list of headers. */
3994 lua_pushnil(L);
3995 while(lua_next(L, -2) != 0) {
3996
3997 /* We expect a string as -2. */
3998 if (lua_type(L, -2) != LUA_TSTRING) {
3999 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4000 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4001 lua_typename(L, lua_type(L, -2)));
4002 WILL_LJMP(lua_error(L));
4003 }
4004 name = lua_tostring(L, -2);
4005
4006 /* We expect an array as -1. */
4007 if (lua_type(L, -1) != LUA_TTABLE) {
4008 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4009 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4010 name,
4011 lua_typename(L, lua_type(L, -1)));
4012 WILL_LJMP(lua_error(L));
4013 }
4014
4015 /* Browse the table who is on the top of the stack. */
4016 lua_pushnil(L);
4017 while(lua_next(L, -2) != 0) {
4018
4019 /* We expect a number as -2. */
4020 if (lua_type(L, -2) != LUA_TNUMBER) {
4021 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4022 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4023 name,
4024 lua_typename(L, lua_type(L, -2)));
4025 WILL_LJMP(lua_error(L));
4026 }
4027 id = lua_tointeger(L, -2);
4028
4029 /* We expect a string as -2. */
4030 if (lua_type(L, -1) != LUA_TSTRING) {
4031 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4032 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4033 name, id,
4034 lua_typename(L, lua_type(L, -1)));
4035 WILL_LJMP(lua_error(L));
4036 }
4037 value = lua_tostring(L, -1);
4038
4039 /* Catenate a new header. */
4040 chunk_appendf(tmp, "%s: %s\r\n", name, value);
4041
4042 /* Protocol checks. */
4043
4044 /* Check if the header conneciton is present. */
4045 if (strcasecmp("connection", name) == 0)
4046 hdr_connection = 1;
4047
4048 /* Copy the header content length. The length conversion
4049 * is done without control. If it contains a ad value, this
4050 * is not our problem.
4051 */
4052 if (strcasecmp("content-length", name) == 0)
4053 hdr_contentlength = atoi(value);
4054
4055 /* Check if the client annouces a transfer-encoding chunked it self. */
4056 if (strcasecmp("transfer-encoding", name) == 0 &&
4057 strcasecmp("chunked", value) == 0)
4058 hdr_chunked = 1;
4059
4060 /* Remove the array from the stack, and get next element with a remaining string. */
4061 lua_pop(L, 1);
4062 }
4063
4064 /* Remove the array from the stack, and get next element with a remaining string. */
4065 lua_pop(L, 1);
4066 }
4067
4068 /* If the http protocol version is 1.1, we expect an header "connection" set
4069 * to "close" to be HAProxy/keeplive compliant. Otherwise, we expect nothing.
4070 * If the header conneciton is present, don't change it, if it is not present,
4071 * we must set.
4072 *
4073 * we set a "connection: close" header for ensuring that the keepalive will be
4074 * respected by haproxy. HAProcy considers that the application cloe the connection
4075 * and it keep the connection from the client open.
4076 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004077 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 && !hdr_connection)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004078 chunk_appendf(tmp, "Connection: close\r\n");
4079
4080 /* If we dont have a content-length set, we must announce a transfer enconding
4081 * chunked. This is required by haproxy for the keepalive compliance.
4082 * If the applet annouce a transfer-encoding chunked itslef, don't
4083 * do anything.
4084 */
4085 if (hdr_contentlength == -1 && hdr_chunked == 0) {
4086 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4087 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4088 }
4089
4090 /* Finalize headers. */
4091 chunk_appendf(tmp, "\r\n");
4092
4093 /* Remove the last entry and the array of headers */
4094 lua_pop(L, 2);
4095
4096 /* Push the headers block. */
4097 lua_pushlstring(L, tmp->str, tmp->len);
4098
4099 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4100}
4101
4102/*
4103 *
4104 *
4105 * Class HTTP
4106 *
4107 *
4108 */
4109
4110/* Returns a struct hlua_txn if the stack entry "ud" is
4111 * a class stream, otherwise it throws an error.
4112 */
4113__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4114{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004115 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004116}
4117
4118/* This function creates and push in the stack a HTTP object
4119 * according with a current TXN.
4120 */
4121static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4122{
4123 struct hlua_txn *htxn;
4124
4125 /* Check stack size. */
4126 if (!lua_checkstack(L, 3))
4127 return 0;
4128
4129 /* Create the object: obj[0] = userdata.
4130 * Note that the base of the Converters object is the
4131 * same than the TXN object.
4132 */
4133 lua_newtable(L);
4134 htxn = lua_newuserdata(L, sizeof(*htxn));
4135 lua_rawseti(L, -2, 0);
4136
4137 htxn->s = txn->s;
4138 htxn->p = txn->p;
4139
4140 /* Pop a class stream metatable and affect it to the table. */
4141 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4142 lua_setmetatable(L, -2);
4143
4144 return 1;
4145}
4146
4147/* This function creates ans returns an array of HTTP headers.
4148 * This function does not fails. It is used as wrapper with the
4149 * 2 following functions.
4150 */
4151__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4152{
4153 const char *cur_ptr, *cur_next, *p;
4154 int old_idx, cur_idx;
4155 struct hdr_idx_elem *cur_hdr;
4156 const char *hn, *hv;
4157 int hnl, hvl;
4158 int type;
4159 const char *in;
4160 char *out;
4161 int len;
4162
4163 /* Create the table. */
4164 lua_newtable(L);
4165
4166 if (!htxn->s->txn)
4167 return 1;
4168
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004169 /* Check if a valid response is parsed */
4170 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4171 return 1;
4172
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004173 /* Build array of headers. */
4174 old_idx = 0;
4175 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4176
4177 while (1) {
4178 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4179 if (!cur_idx)
4180 break;
4181 old_idx = cur_idx;
4182
4183 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4184 cur_ptr = cur_next;
4185 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4186
4187 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4188 * and the next header starts at cur_next. We'll check
4189 * this header in the list as well as against the default
4190 * rule.
4191 */
4192
4193 /* look for ': *'. */
4194 hn = cur_ptr;
4195 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4196 if (p >= cur_ptr+cur_hdr->len)
4197 continue;
4198 hnl = p - hn;
4199 p++;
4200 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4201 p++;
4202 if (p >= cur_ptr+cur_hdr->len)
4203 continue;
4204 hv = p;
4205 hvl = cur_ptr+cur_hdr->len-p;
4206
4207 /* Lowercase the key. Don't check the size of trash, it have
4208 * the size of one buffer and the input data contains in one
4209 * buffer.
4210 */
4211 out = trash.str;
4212 for (in=hn; in<hn+hnl; in++, out++)
4213 *out = tolower(*in);
4214 *out = '\0';
4215
4216 /* Check for existing entry:
4217 * assume that the table is on the top of the stack, and
4218 * push the key in the stack, the function lua_gettable()
4219 * perform the lookup.
4220 */
4221 lua_pushlstring(L, trash.str, hnl);
4222 lua_gettable(L, -2);
4223 type = lua_type(L, -1);
4224
4225 switch (type) {
4226 case LUA_TNIL:
4227 /* Table not found, create it. */
4228 lua_pop(L, 1); /* remove the nil value. */
4229 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4230 lua_newtable(L); /* create and push empty table. */
4231 lua_pushlstring(L, hv, hvl); /* push header value. */
4232 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4233 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4234 break;
4235
4236 case LUA_TTABLE:
4237 /* Entry found: push the value in the table. */
4238 len = lua_rawlen(L, -1);
4239 lua_pushlstring(L, hv, hvl); /* push header value. */
4240 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4241 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4242 break;
4243
4244 default:
4245 /* Other cases are errors. */
4246 hlua_pusherror(L, "internal error during the parsing of headers.");
4247 WILL_LJMP(lua_error(L));
4248 }
4249 }
4250
4251 return 1;
4252}
4253
4254__LJMP static int hlua_http_req_get_headers(lua_State *L)
4255{
4256 struct hlua_txn *htxn;
4257
4258 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4259 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4260
4261 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4262}
4263
4264__LJMP static int hlua_http_res_get_headers(lua_State *L)
4265{
4266 struct hlua_txn *htxn;
4267
4268 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4269 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4270
4271 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4272}
4273
4274/* This function replace full header, or just a value in
4275 * the request or in the response. It is a wrapper fir the
4276 * 4 following functions.
4277 */
4278__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4279 struct http_msg *msg, int action)
4280{
4281 size_t name_len;
4282 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4283 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4284 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4285 struct my_regex re;
4286
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004287 /* Check if a valid response is parsed */
4288 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4289 return 0;
4290
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004291 if (!regex_comp(reg, &re, 1, 1, NULL))
4292 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4293
4294 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4295 regex_free(&re);
4296 return 0;
4297}
4298
4299__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4300{
4301 struct hlua_txn *htxn;
4302
4303 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4304 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4305
4306 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4307}
4308
4309__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4310{
4311 struct hlua_txn *htxn;
4312
4313 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4314 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4315
4316 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4317}
4318
4319__LJMP static int hlua_http_req_rep_val(lua_State *L)
4320{
4321 struct hlua_txn *htxn;
4322
4323 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4324 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4325
4326 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4327}
4328
4329__LJMP static int hlua_http_res_rep_val(lua_State *L)
4330{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004331 struct hlua_txn *htxn;
4332
4333 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4334 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4335
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004336 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004337}
4338
4339/* This function deletes all the occurences of an header.
4340 * It is a wrapper for the 2 following functions.
4341 */
4342__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4343{
4344 size_t len;
4345 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4346 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004347 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004348
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004349 /* Check if a valid response is parsed */
4350 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4351 return 0;
4352
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004353 ctx.idx = 0;
4354 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4355 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4356 return 0;
4357}
4358
4359__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4360{
4361 struct hlua_txn *htxn;
4362
4363 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4364 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4365
Willy Tarreaueee5b512015-04-03 23:46:31 +02004366 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004367}
4368
4369__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4370{
4371 struct hlua_txn *htxn;
4372
4373 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4374 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4375
Willy Tarreaueee5b512015-04-03 23:46:31 +02004376 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004377}
4378
4379/* This function adds an header. It is a wrapper used by
4380 * the 2 following functions.
4381 */
4382__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4383{
4384 size_t name_len;
4385 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4386 size_t value_len;
4387 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4388 char *p;
4389
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004390 /* Check if a valid message is parsed */
4391 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4392 return 0;
4393
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004394 /* Check length. */
4395 trash.len = value_len + name_len + 2;
4396 if (trash.len > trash.size)
4397 return 0;
4398
4399 /* Creates the header string. */
4400 p = trash.str;
4401 memcpy(p, name, name_len);
4402 p += name_len;
4403 *p = ':';
4404 p++;
4405 *p = ' ';
4406 p++;
4407 memcpy(p, value, value_len);
4408
Willy Tarreaueee5b512015-04-03 23:46:31 +02004409 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004410 trash.str, trash.len) != 0);
4411
4412 return 0;
4413}
4414
4415__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4416{
4417 struct hlua_txn *htxn;
4418
4419 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4420 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4421
Willy Tarreaueee5b512015-04-03 23:46:31 +02004422 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004423}
4424
4425__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4426{
4427 struct hlua_txn *htxn;
4428
4429 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4430 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4431
Willy Tarreaueee5b512015-04-03 23:46:31 +02004432 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004433}
4434
4435static int hlua_http_req_set_hdr(lua_State *L)
4436{
4437 struct hlua_txn *htxn;
4438
4439 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4440 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4441
Willy Tarreaueee5b512015-04-03 23:46:31 +02004442 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4443 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004444}
4445
4446static int hlua_http_res_set_hdr(lua_State *L)
4447{
4448 struct hlua_txn *htxn;
4449
4450 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4451 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4452
Willy Tarreaueee5b512015-04-03 23:46:31 +02004453 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4454 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004455}
4456
4457/* This function set the method. */
4458static int hlua_http_req_set_meth(lua_State *L)
4459{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004460 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004461 size_t name_len;
4462 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004463
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004464 /* Check if a valid request is parsed */
4465 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4466 lua_pushboolean(L, 0);
4467 return 1;
4468 }
4469
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004470 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004471 return 1;
4472}
4473
4474/* This function set the method. */
4475static int hlua_http_req_set_path(lua_State *L)
4476{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004477 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004478 size_t name_len;
4479 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004480
4481 /* Check if a valid request is parsed */
4482 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4483 lua_pushboolean(L, 0);
4484 return 1;
4485 }
4486
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004487 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004488 return 1;
4489}
4490
4491/* This function set the query-string. */
4492static int hlua_http_req_set_query(lua_State *L)
4493{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004494 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004495 size_t name_len;
4496 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004497
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004498 /* Check if a valid request is parsed */
4499 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4500 lua_pushboolean(L, 0);
4501 return 1;
4502 }
4503
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004504 /* Check length. */
4505 if (name_len > trash.size - 1) {
4506 lua_pushboolean(L, 0);
4507 return 1;
4508 }
4509
4510 /* Add the mark question as prefix. */
4511 chunk_reset(&trash);
4512 trash.str[trash.len++] = '?';
4513 memcpy(trash.str + trash.len, name, name_len);
4514 trash.len += name_len;
4515
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004516 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004517 return 1;
4518}
4519
4520/* This function set the uri. */
4521static int hlua_http_req_set_uri(lua_State *L)
4522{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004523 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004524 size_t name_len;
4525 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004526
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004527 /* Check if a valid request is parsed */
4528 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4529 lua_pushboolean(L, 0);
4530 return 1;
4531 }
4532
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004533 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004534 return 1;
4535}
4536
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004537/* This function set the response code. */
4538static int hlua_http_res_set_status(lua_State *L)
4539{
4540 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4541 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
4542
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004543 /* Check if a valid response is parsed */
4544 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4545 return 0;
4546
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004547 http_set_status(code, htxn->s);
4548 return 0;
4549}
4550
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004551/*
4552 *
4553 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004554 * Class TXN
4555 *
4556 *
4557 */
4558
4559/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004560 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004561 */
4562__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4563{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004564 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004565}
4566
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004567__LJMP static int hlua_set_var(lua_State *L)
4568{
4569 struct hlua_txn *htxn;
4570 const char *name;
4571 size_t len;
4572 struct sample smp;
4573
4574 MAY_LJMP(check_args(L, 3, "set_var"));
4575
4576 /* It is useles to retrieve the stream, but this function
4577 * runs only in a stream context.
4578 */
4579 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4580 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4581
4582 /* Converts the third argument in a sample. */
4583 hlua_lua2smp(L, 3, &smp);
4584
4585 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01004586 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004587 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004588 return 0;
4589}
4590
Christopher Faulet85d79c92016-11-09 16:54:56 +01004591__LJMP static int hlua_unset_var(lua_State *L)
4592{
4593 struct hlua_txn *htxn;
4594 const char *name;
4595 size_t len;
4596 struct sample smp;
4597
4598 MAY_LJMP(check_args(L, 2, "unset_var"));
4599
4600 /* It is useles to retrieve the stream, but this function
4601 * runs only in a stream context.
4602 */
4603 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4604 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4605
4606 /* Unset the variable. */
4607 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
4608 vars_unset_by_name(name, len, &smp);
4609 return 0;
4610}
4611
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004612__LJMP static int hlua_get_var(lua_State *L)
4613{
4614 struct hlua_txn *htxn;
4615 const char *name;
4616 size_t len;
4617 struct sample smp;
4618
4619 MAY_LJMP(check_args(L, 2, "get_var"));
4620
4621 /* It is useles to retrieve the stream, but this function
4622 * runs only in a stream context.
4623 */
4624 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4625 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4626
Willy Tarreau7560dd42016-03-10 16:28:58 +01004627 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004628 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004629 lua_pushnil(L);
4630 return 1;
4631 }
4632
4633 return hlua_smp2lua(L, &smp);
4634}
4635
Willy Tarreau59551662015-03-10 14:23:13 +01004636__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004637{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004638 struct hlua *hlua;
4639
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004640 MAY_LJMP(check_args(L, 2, "set_priv"));
4641
Willy Tarreau87b09662015-04-03 00:22:06 +02004642 /* It is useles to retrieve the stream, but this function
4643 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004644 */
4645 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004646 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004647
4648 /* Remove previous value. */
4649 if (hlua->Mref != -1)
4650 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
4651
4652 /* Get and store new value. */
4653 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4654 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4655
4656 return 0;
4657}
4658
Willy Tarreau59551662015-03-10 14:23:13 +01004659__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004660{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004661 struct hlua *hlua;
4662
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004663 MAY_LJMP(check_args(L, 1, "get_priv"));
4664
Willy Tarreau87b09662015-04-03 00:22:06 +02004665 /* It is useles to retrieve the stream, but this function
4666 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004667 */
4668 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004669 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004670
4671 /* Push configuration index in the stack. */
4672 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4673
4674 return 1;
4675}
4676
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004677/* Create stack entry containing a class TXN. This function
4678 * return 0 if the stack does not contains free slots,
4679 * otherwise it returns 1.
4680 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004681static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004682{
Willy Tarreaude491382015-04-06 11:04:28 +02004683 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004684
4685 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004686 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004687 return 0;
4688
4689 /* NOTE: The allocation never fails. The failure
4690 * throw an error, and the function never returns.
4691 * if the throw is not avalaible, the process is aborted.
4692 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004693 /* Create the object: obj[0] = userdata. */
4694 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004695 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004696 lua_rawseti(L, -2, 0);
4697
Willy Tarreaude491382015-04-06 11:04:28 +02004698 htxn->s = s;
4699 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004700 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004701 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004702
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004703 /* Create the "f" field that contains a list of fetches. */
4704 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004705 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004706 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004707 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004708
4709 /* Create the "sf" field that contains a list of stringsafe fetches. */
4710 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004711 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004712 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004713 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004714
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004715 /* Create the "c" field that contains a list of converters. */
4716 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004717 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004718 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004719 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004720
4721 /* Create the "sc" field that contains a list of stringsafe converters. */
4722 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004723 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004724 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004725 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004726
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004727 /* Create the "req" field that contains the request channel object. */
4728 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004729 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004730 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004731 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004732
4733 /* Create the "res" field that contains the response channel object. */
4734 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004735 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004736 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004737 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004738
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004739 /* Creates the HTTP object is the current proxy allows http. */
4740 lua_pushstring(L, "http");
4741 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02004742 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004743 return 0;
4744 }
4745 else
4746 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004747 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004748
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004749 /* Pop a class sesison metatable and affect it to the userdata. */
4750 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
4751 lua_setmetatable(L, -2);
4752
4753 return 1;
4754}
4755
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004756__LJMP static int hlua_txn_deflog(lua_State *L)
4757{
4758 const char *msg;
4759 struct hlua_txn *htxn;
4760
4761 MAY_LJMP(check_args(L, 2, "deflog"));
4762 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4763 msg = MAY_LJMP(luaL_checkstring(L, 2));
4764
4765 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
4766 return 0;
4767}
4768
4769__LJMP static int hlua_txn_log(lua_State *L)
4770{
4771 int level;
4772 const char *msg;
4773 struct hlua_txn *htxn;
4774
4775 MAY_LJMP(check_args(L, 3, "log"));
4776 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4777 level = MAY_LJMP(luaL_checkinteger(L, 2));
4778 msg = MAY_LJMP(luaL_checkstring(L, 3));
4779
4780 if (level < 0 || level >= NB_LOG_LEVELS)
4781 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4782
4783 hlua_sendlog(htxn->s->be, level, msg);
4784 return 0;
4785}
4786
4787__LJMP static int hlua_txn_log_debug(lua_State *L)
4788{
4789 const char *msg;
4790 struct hlua_txn *htxn;
4791
4792 MAY_LJMP(check_args(L, 2, "Debug"));
4793 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4794 msg = MAY_LJMP(luaL_checkstring(L, 2));
4795 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
4796 return 0;
4797}
4798
4799__LJMP static int hlua_txn_log_info(lua_State *L)
4800{
4801 const char *msg;
4802 struct hlua_txn *htxn;
4803
4804 MAY_LJMP(check_args(L, 2, "Info"));
4805 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4806 msg = MAY_LJMP(luaL_checkstring(L, 2));
4807 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
4808 return 0;
4809}
4810
4811__LJMP static int hlua_txn_log_warning(lua_State *L)
4812{
4813 const char *msg;
4814 struct hlua_txn *htxn;
4815
4816 MAY_LJMP(check_args(L, 2, "Warning"));
4817 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4818 msg = MAY_LJMP(luaL_checkstring(L, 2));
4819 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
4820 return 0;
4821}
4822
4823__LJMP static int hlua_txn_log_alert(lua_State *L)
4824{
4825 const char *msg;
4826 struct hlua_txn *htxn;
4827
4828 MAY_LJMP(check_args(L, 2, "Alert"));
4829 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4830 msg = MAY_LJMP(luaL_checkstring(L, 2));
4831 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
4832 return 0;
4833}
4834
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004835__LJMP static int hlua_txn_set_loglevel(lua_State *L)
4836{
4837 struct hlua_txn *htxn;
4838 int ll;
4839
4840 MAY_LJMP(check_args(L, 2, "set_loglevel"));
4841 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4842 ll = MAY_LJMP(luaL_checkinteger(L, 2));
4843
4844 if (ll < 0 || ll > 7)
4845 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
4846
4847 htxn->s->logs.level = ll;
4848 return 0;
4849}
4850
4851__LJMP static int hlua_txn_set_tos(lua_State *L)
4852{
4853 struct hlua_txn *htxn;
4854 struct connection *cli_conn;
4855 int tos;
4856
4857 MAY_LJMP(check_args(L, 2, "set_tos"));
4858 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4859 tos = MAY_LJMP(luaL_checkinteger(L, 2));
4860
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004861 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Vincent Bernat6e615892016-05-18 16:17:44 +02004862 inet_set_tos(cli_conn->t.sock.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004863
4864 return 0;
4865}
4866
4867__LJMP static int hlua_txn_set_mark(lua_State *L)
4868{
4869#ifdef SO_MARK
4870 struct hlua_txn *htxn;
4871 struct connection *cli_conn;
4872 int mark;
4873
4874 MAY_LJMP(check_args(L, 2, "set_mark"));
4875 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4876 mark = MAY_LJMP(luaL_checkinteger(L, 2));
4877
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004878 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02004879 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004880#endif
4881 return 0;
4882}
4883
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004884/* This function is an Lua binding that send pending data
4885 * to the client, and close the stream interface.
4886 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004887__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004888{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004889 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02004890 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01004891 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004892
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004893 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004894 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02004895 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004896
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004897 /* If the flags NOTERM is set, we cannot terminate the http
4898 * session, so we just end the execution of the current
4899 * lua code.
4900 */
4901 if (htxn->flags & HLUA_TXN_NOTERM) {
4902 WILL_LJMP(hlua_done(L));
4903 return 0;
4904 }
4905
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004906 ic = &htxn->s->req;
4907 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01004908
Willy Tarreau630ef452015-08-28 10:06:15 +02004909 if (htxn->s->txn) {
4910 /* HTTP mode, let's stay in sync with the stream */
4911 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
4912 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
4913 htxn->s->txn->req.sov = 0;
4914 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
4915 oc->analysers = AN_RES_HTTP_XFER_BODY;
4916 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
4917 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
4918
Willy Tarreau630ef452015-08-28 10:06:15 +02004919 /* Note that if we want to support keep-alive, we need
4920 * to bypass the close/shutr_now calls below, but that
4921 * may only be done if the HTTP request was already
4922 * processed and the connection header is known (ie
4923 * not during TCP rules).
4924 */
4925 }
4926
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004927 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01004928 channel_abort(ic);
4929 channel_auto_close(ic);
4930 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004931
4932 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01004933 channel_auto_read(oc);
4934 channel_auto_close(oc);
4935 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004936
Willy Tarreau0458b082015-08-28 09:40:04 +02004937 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004938
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02004939 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004940 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004941 return 0;
4942}
4943
4944__LJMP static int hlua_log(lua_State *L)
4945{
4946 int level;
4947 const char *msg;
4948
4949 MAY_LJMP(check_args(L, 2, "log"));
4950 level = MAY_LJMP(luaL_checkinteger(L, 1));
4951 msg = MAY_LJMP(luaL_checkstring(L, 2));
4952
4953 if (level < 0 || level >= NB_LOG_LEVELS)
4954 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4955
4956 hlua_sendlog(NULL, level, msg);
4957 return 0;
4958}
4959
4960__LJMP static int hlua_log_debug(lua_State *L)
4961{
4962 const char *msg;
4963
4964 MAY_LJMP(check_args(L, 1, "debug"));
4965 msg = MAY_LJMP(luaL_checkstring(L, 1));
4966 hlua_sendlog(NULL, LOG_DEBUG, msg);
4967 return 0;
4968}
4969
4970__LJMP static int hlua_log_info(lua_State *L)
4971{
4972 const char *msg;
4973
4974 MAY_LJMP(check_args(L, 1, "info"));
4975 msg = MAY_LJMP(luaL_checkstring(L, 1));
4976 hlua_sendlog(NULL, LOG_INFO, msg);
4977 return 0;
4978}
4979
4980__LJMP static int hlua_log_warning(lua_State *L)
4981{
4982 const char *msg;
4983
4984 MAY_LJMP(check_args(L, 1, "warning"));
4985 msg = MAY_LJMP(luaL_checkstring(L, 1));
4986 hlua_sendlog(NULL, LOG_WARNING, msg);
4987 return 0;
4988}
4989
4990__LJMP static int hlua_log_alert(lua_State *L)
4991{
4992 const char *msg;
4993
4994 MAY_LJMP(check_args(L, 1, "alert"));
4995 msg = MAY_LJMP(luaL_checkstring(L, 1));
4996 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004997 return 0;
4998}
4999
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005000__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005001{
5002 int wakeup_ms = lua_tointeger(L, -1);
5003 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005004 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005005 return 0;
5006}
5007
5008__LJMP static int hlua_sleep(lua_State *L)
5009{
5010 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005011 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005012
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005013 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005014
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005015 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005016 wakeup_ms = tick_add(now_ms, delay);
5017 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005018
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005019 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5020 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005021}
5022
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005023__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005024{
5025 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005026 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005027
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005028 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005029
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005030 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005031 wakeup_ms = tick_add(now_ms, delay);
5032 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005033
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005034 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5035 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005036}
5037
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005038/* This functionis an LUA binding. it permits to give back
5039 * the hand at the HAProxy scheduler. It is used when the
5040 * LUA processing consumes a lot of time.
5041 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005042__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005043{
5044 return 0;
5045}
5046
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005047__LJMP static int hlua_yield(lua_State *L)
5048{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005049 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5050 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005051}
5052
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005053/* This function change the nice of the currently executed
5054 * task. It is used set low or high priority at the current
5055 * task.
5056 */
Willy Tarreau59551662015-03-10 14:23:13 +01005057__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005058{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005059 struct hlua *hlua;
5060 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005061
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005062 MAY_LJMP(check_args(L, 1, "set_nice"));
5063 hlua = hlua_gethlua(L);
5064 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005065
5066 /* If he task is not set, I'm in a start mode. */
5067 if (!hlua || !hlua->task)
5068 return 0;
5069
5070 if (nice < -1024)
5071 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005072 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005073 nice = 1024;
5074
5075 hlua->task->nice = nice;
5076 return 0;
5077}
5078
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005079/* This function is used as a calback of a task. It is called by the
5080 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5081 * return an E_AGAIN signal, the emmiter of this signal must set a
5082 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005083 *
5084 * Task wrapper are longjmp safe because the only one Lua code
5085 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005086 */
5087static struct task *hlua_process_task(struct task *task)
5088{
5089 struct hlua *hlua = task->context;
5090 enum hlua_exec status;
5091
5092 /* We need to remove the task from the wait queue before executing
5093 * the Lua code because we don't know if it needs to wait for
5094 * another timer or not in the case of E_AGAIN.
5095 */
5096 task_delete(task);
5097
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005098 /* If it is the first call to the task, we must initialize the
5099 * execution timeouts.
5100 */
5101 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005102 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005103
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005104 /* Execute the Lua code. */
5105 status = hlua_ctx_resume(hlua, 1);
5106
5107 switch (status) {
5108 /* finished or yield */
5109 case HLUA_E_OK:
5110 hlua_ctx_destroy(hlua);
5111 task_delete(task);
5112 task_free(task);
5113 break;
5114
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005115 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5116 if (hlua->wake_time != TICK_ETERNITY)
5117 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005118 break;
5119
5120 /* finished with error. */
5121 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005122 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005123 hlua_ctx_destroy(hlua);
5124 task_delete(task);
5125 task_free(task);
5126 break;
5127
5128 case HLUA_E_ERR:
5129 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005130 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005131 hlua_ctx_destroy(hlua);
5132 task_delete(task);
5133 task_free(task);
5134 break;
5135 }
5136 return NULL;
5137}
5138
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005139/* This function is an LUA binding that register LUA function to be
5140 * executed after the HAProxy configuration parsing and before the
5141 * HAProxy scheduler starts. This function expect only one LUA
5142 * argument that is a function. This function returns nothing, but
5143 * throws if an error is encountered.
5144 */
5145__LJMP static int hlua_register_init(lua_State *L)
5146{
5147 struct hlua_init_function *init;
5148 int ref;
5149
5150 MAY_LJMP(check_args(L, 1, "register_init"));
5151
5152 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5153
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005154 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005155 if (!init)
5156 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5157
5158 init->function_ref = ref;
5159 LIST_ADDQ(&hlua_init_functions, &init->l);
5160 return 0;
5161}
5162
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005163/* This functio is an LUA binding. It permits to register a task
5164 * executed in parallel of the main HAroxy activity. The task is
5165 * created and it is set in the HAProxy scheduler. It can be called
5166 * from the "init" section, "post init" or during the runtime.
5167 *
5168 * Lua prototype:
5169 *
5170 * <none> core.register_task(<function>)
5171 */
5172static int hlua_register_task(lua_State *L)
5173{
5174 struct hlua *hlua;
5175 struct task *task;
5176 int ref;
5177
5178 MAY_LJMP(check_args(L, 1, "register_task"));
5179
5180 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5181
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005182 hlua = calloc(1, sizeof(*hlua));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005183 if (!hlua)
5184 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5185
5186 task = task_new();
5187 task->context = hlua;
5188 task->process = hlua_process_task;
5189
5190 if (!hlua_ctx_init(hlua, task))
5191 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5192
5193 /* Restore the function in the stack. */
5194 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5195 hlua->nargs = 0;
5196
5197 /* Schedule task. */
5198 task_schedule(task, now_ms);
5199
5200 return 0;
5201}
5202
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005203/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5204 * doesn't allow "yield" functions because the HAProxy engine cannot
5205 * resume converters.
5206 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005207static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005208{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005209 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005210 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005211 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005212
Willy Tarreaube508f12016-03-10 11:47:01 +01005213 if (!stream)
5214 return 0;
5215
Willy Tarreau87b09662015-04-03 00:22:06 +02005216 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005217 * Lua context can be not initialized. This behavior
5218 * permits to save performances because a systematic
5219 * Lua initialization cause 5% performances loss.
5220 */
Willy Tarreau87b09662015-04-03 00:22:06 +02005221 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005222 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005223 return 0;
5224 }
5225
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005226 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005227 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005228
5229 /* The following Lua calls can fail. */
5230 if (!SET_SAFE_LJMP(stream->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005231 if (lua_type(stream->hlua.T, -1) == LUA_TSTRING)
5232 error = lua_tostring(stream->hlua.T, -1);
5233 else
5234 error = "critical error";
5235 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005236 return 0;
5237 }
5238
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005239 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005240 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005241 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005242 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005243 return 0;
5244 }
5245
5246 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005247 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005248
5249 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005250 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005251 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005252 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005253 return 0;
5254 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005255 hlua_smp2lua(stream->hlua.T, smp);
Thierry Fournier4a53bfd2016-05-27 16:35:01 +02005256 stream->hlua.nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005257
5258 /* push keywords in the stack. */
5259 if (arg_p) {
5260 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02005261 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005262 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005263 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005264 return 0;
5265 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005266 hlua_arg2lua(stream->hlua.T, arg_p);
5267 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005268 }
5269 }
5270
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005271 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005272 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005273
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005274 /* At this point the execution is safe. */
5275 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005276 }
5277
5278 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005279 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005280 /* finished. */
5281 case HLUA_E_OK:
5282 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005283 hlua_lua2smp(stream->hlua.T, -1, smp);
5284 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005285 return 1;
5286
5287 /* yield. */
5288 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005289 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005290 return 0;
5291
5292 /* finished with error. */
5293 case HLUA_E_ERRMSG:
5294 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005295 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
5296 fcn->name, lua_tostring(stream->hlua.T, -1));
Willy Tarreau87b09662015-04-03 00:22:06 +02005297 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005298 return 0;
5299
5300 case HLUA_E_ERR:
5301 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005302 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005303
5304 default:
5305 return 0;
5306 }
5307}
5308
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005309/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5310 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005311 * resume sample-fetches. This function will be called by the sample
5312 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005313 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005314static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5315 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005316{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005317 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005318 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005319 const char *error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005320
Willy Tarreaube508f12016-03-10 11:47:01 +01005321 if (!stream)
5322 return 0;
5323
Willy Tarreau87b09662015-04-03 00:22:06 +02005324 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005325 * Lua context can be not initialized. This behavior
5326 * permits to save performances because a systematic
5327 * Lua initialization cause 5% performances loss.
5328 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005329 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005330 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005331 return 0;
5332 }
5333
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005334 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005335 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005336
5337 /* The following Lua calls can fail. */
5338 if (!SET_SAFE_LJMP(stream->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005339 if (lua_type(stream->hlua.T, -1) == LUA_TSTRING)
5340 error = lua_tostring(stream->hlua.T, -1);
5341 else
5342 error = "critical error";
5343 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005344 return 0;
5345 }
5346
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005347 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005348 if (!lua_checkstack(stream->hlua.T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005349 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005350 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005351 return 0;
5352 }
5353
5354 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005355 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005356
5357 /* push arguments in the stack. */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005358 if (!hlua_txn_new(stream->hlua.T, stream, smp->px, smp->opt & SMP_OPT_DIR,
5359 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005360 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005361 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005362 return 0;
5363 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005364 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005365
5366 /* push keywords in the stack. */
5367 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5368 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005369 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005370 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005371 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005372 return 0;
5373 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005374 hlua_arg2lua(stream->hlua.T, arg_p);
5375 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005376 }
5377
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005378 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005379 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005380
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005381 /* At this point the execution is safe. */
5382 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005383 }
5384
5385 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005386 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005387 /* finished. */
5388 case HLUA_E_OK:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005389 if (!hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005390 return 0;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005391 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005392 hlua_lua2smp(stream->hlua.T, -1, smp);
5393 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005394
5395 /* Set the end of execution flag. */
5396 smp->flags &= ~SMP_F_MAY_CHANGE;
5397 return 1;
5398
5399 /* yield. */
5400 case HLUA_E_AGAIN:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005401 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005402 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005403 return 0;
5404
5405 /* finished with error. */
5406 case HLUA_E_ERRMSG:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005407 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005408 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005409 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
5410 fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005411 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005412 return 0;
5413
5414 case HLUA_E_ERR:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005415 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005416 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005417 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005418
5419 default:
5420 return 0;
5421 }
5422}
5423
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005424/* This function is an LUA binding used for registering
5425 * "sample-conv" functions. It expects a converter name used
5426 * in the haproxy configuration file, and an LUA function.
5427 */
5428__LJMP static int hlua_register_converters(lua_State *L)
5429{
5430 struct sample_conv_kw_list *sck;
5431 const char *name;
5432 int ref;
5433 int len;
5434 struct hlua_function *fcn;
5435
5436 MAY_LJMP(check_args(L, 2, "register_converters"));
5437
5438 /* First argument : converter name. */
5439 name = MAY_LJMP(luaL_checkstring(L, 1));
5440
5441 /* Second argument : lua function. */
5442 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5443
5444 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005445 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005446 if (!sck)
5447 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005448 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005449 if (!fcn)
5450 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5451
5452 /* Fill fcn. */
5453 fcn->name = strdup(name);
5454 if (!fcn->name)
5455 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5456 fcn->function_ref = ref;
5457
5458 /* List head */
5459 sck->list.n = sck->list.p = NULL;
5460
5461 /* converter keyword. */
5462 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005463 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005464 if (!sck->kw[0].kw)
5465 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5466
5467 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5468 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005469 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 +01005470 sck->kw[0].val_args = NULL;
5471 sck->kw[0].in_type = SMP_T_STR;
5472 sck->kw[0].out_type = SMP_T_STR;
5473 sck->kw[0].private = fcn;
5474
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005475 /* Register this new converter */
5476 sample_register_convs(sck);
5477
5478 return 0;
5479}
5480
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005481/* This fucntion is an LUA binding used for registering
5482 * "sample-fetch" functions. It expects a converter name used
5483 * in the haproxy configuration file, and an LUA function.
5484 */
5485__LJMP static int hlua_register_fetches(lua_State *L)
5486{
5487 const char *name;
5488 int ref;
5489 int len;
5490 struct sample_fetch_kw_list *sfk;
5491 struct hlua_function *fcn;
5492
5493 MAY_LJMP(check_args(L, 2, "register_fetches"));
5494
5495 /* First argument : sample-fetch name. */
5496 name = MAY_LJMP(luaL_checkstring(L, 1));
5497
5498 /* Second argument : lua function. */
5499 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5500
5501 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005502 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005503 if (!sfk)
5504 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005505 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005506 if (!fcn)
5507 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5508
5509 /* Fill fcn. */
5510 fcn->name = strdup(name);
5511 if (!fcn->name)
5512 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5513 fcn->function_ref = ref;
5514
5515 /* List head */
5516 sfk->list.n = sfk->list.p = NULL;
5517
5518 /* sample-fetch keyword. */
5519 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005520 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005521 if (!sfk->kw[0].kw)
5522 return luaL_error(L, "lua out of memory error.");
5523
5524 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5525 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005526 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 +01005527 sfk->kw[0].val_args = NULL;
5528 sfk->kw[0].out_type = SMP_T_STR;
5529 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5530 sfk->kw[0].val = 0;
5531 sfk->kw[0].private = fcn;
5532
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005533 /* Register this new fetch. */
5534 sample_register_fetches(sfk);
5535
5536 return 0;
5537}
5538
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005539/* This function is a wrapper to execute each LUA function declared
5540 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005541 * return ACT_RET_CONT if the processing is finished (with or without
5542 * error) and return ACT_RET_YIELD if the function must be called again
5543 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005544 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005545static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005546 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005547{
5548 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005549 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005550 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005551 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005552
5553 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01005554 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
5555 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
5556 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
5557 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005558 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005559 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005560 return ACT_RET_CONT;
5561 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005562
Willy Tarreau87b09662015-04-03 00:22:06 +02005563 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005564 * Lua context can be not initialized. This behavior
5565 * permits to save performances because a systematic
5566 * Lua initialization cause 5% performances loss.
5567 */
5568 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005569 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005570 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005571 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005572 }
5573
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005574 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01005575 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005576
5577 /* The following Lua calls can fail. */
5578 if (!SET_SAFE_LJMP(s->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005579 if (lua_type(s->hlua.T, -1) == LUA_TSTRING)
5580 error = lua_tostring(s->hlua.T, -1);
5581 else
5582 error = "critical error";
5583 SEND_ERR(px, "Lua function '%s': %s.\n",
5584 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005585 return ACT_RET_CONT;
5586 }
5587
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005588 /* Check stack available size. */
5589 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005590 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005591 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005592 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005593 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005594 }
5595
5596 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005597 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005598
Willy Tarreau87b09662015-04-03 00:22:06 +02005599 /* Create and and push object stream in the stack. */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005600 if (!hlua_txn_new(s->hlua.T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005601 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005602 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005603 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005604 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005605 }
5606 s->hlua.nargs = 1;
5607
5608 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005609 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005610 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005611 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005612 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005613 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005614 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005615 }
5616 lua_pushstring(s->hlua.T, *arg);
5617 s->hlua.nargs++;
5618 }
5619
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005620 /* Now the execution is safe. */
5621 RESET_SAFE_LJMP(s->hlua.T);
5622
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005623 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005624 s->hlua.max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005625 }
5626
5627 /* Execute the function. */
Willy Tarreau528192d2015-09-27 10:48:01 +02005628 switch (hlua_ctx_resume(&s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005629 /* finished. */
5630 case HLUA_E_OK:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005631 if (!hlua_check_proto(s, dir))
5632 return ACT_RET_ERR;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005633 if (s->hlua.flags & HLUA_STOP)
5634 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005635 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005636
5637 /* yield. */
5638 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005639 /* Set timeout in the required channel. */
5640 if (s->hlua.wake_time != TICK_ETERNITY) {
5641 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005642 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005643 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005644 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005645 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005646 /* Some actions can be wake up when a "write" event
5647 * is detected on a response channel. This is useful
5648 * only for actions targetted on the requests.
5649 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01005650 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005651 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005652 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005653 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005654 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01005655 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005656 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005657 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005658
5659 /* finished with error. */
5660 case HLUA_E_ERRMSG:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005661 if (!hlua_check_proto(s, dir))
5662 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005663 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005664 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005665 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005666 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005667 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005668
5669 case HLUA_E_ERR:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005670 if (!hlua_check_proto(s, dir))
5671 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005672 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005673 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005674 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005675
5676 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005677 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005678 }
5679}
5680
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005681struct task *hlua_applet_wakeup(struct task *t)
5682{
5683 struct appctx *ctx = t->context;
5684 struct stream_interface *si = ctx->owner;
5685
5686 /* If the applet is wake up without any expected work, the sheduler
5687 * remove it from the run queue. This flag indicate that the applet
5688 * is waiting for write. If the buffer is full, the main processing
5689 * will send some data and after call the applet, otherwise it call
5690 * the applet ASAP.
5691 */
5692 si_applet_cant_put(si);
5693 appctx_wakeup(ctx);
5694 return NULL;
5695}
5696
5697static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5698{
5699 struct stream_interface *si = ctx->owner;
5700 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5701 struct task *task;
5702 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005703 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005704
5705 HLUA_INIT(hlua);
5706 ctx->ctx.hlua_apptcp.flags = 0;
5707
5708 /* Create task used by signal to wakeup applets. */
5709 task = task_new();
5710 if (!task) {
5711 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5712 ctx->rule->arg.hlua_rule->fcn.name);
5713 return 0;
5714 }
5715 task->nice = 0;
5716 task->context = ctx;
5717 task->process = hlua_applet_wakeup;
5718 ctx->ctx.hlua_apptcp.task = task;
5719
5720 /* In the execution wrappers linked with a stream, the
5721 * Lua context can be not initialized. This behavior
5722 * permits to save performances because a systematic
5723 * Lua initialization cause 5% performances loss.
5724 */
5725 if (!hlua_ctx_init(hlua, task)) {
5726 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
5727 ctx->rule->arg.hlua_rule->fcn.name);
5728 return 0;
5729 }
5730
5731 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005732 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005733
5734 /* The following Lua calls can fail. */
5735 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005736 if (lua_type(hlua->T, -1) == LUA_TSTRING)
5737 error = lua_tostring(hlua->T, -1);
5738 else
5739 error = "critical error";
5740 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
5741 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005742 RESET_SAFE_LJMP(hlua->T);
5743 return 0;
5744 }
5745
5746 /* Check stack available size. */
5747 if (!lua_checkstack(hlua->T, 1)) {
5748 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5749 ctx->rule->arg.hlua_rule->fcn.name);
5750 RESET_SAFE_LJMP(hlua->T);
5751 return 0;
5752 }
5753
5754 /* Restore the function in the stack. */
5755 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5756
5757 /* Create and and push object stream in the stack. */
5758 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
5759 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5760 ctx->rule->arg.hlua_rule->fcn.name);
5761 RESET_SAFE_LJMP(hlua->T);
5762 return 0;
5763 }
5764 hlua->nargs = 1;
5765
5766 /* push keywords in the stack. */
5767 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5768 if (!lua_checkstack(hlua->T, 1)) {
5769 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5770 ctx->rule->arg.hlua_rule->fcn.name);
5771 RESET_SAFE_LJMP(hlua->T);
5772 return 0;
5773 }
5774 lua_pushstring(hlua->T, *arg);
5775 hlua->nargs++;
5776 }
5777
5778 RESET_SAFE_LJMP(hlua->T);
5779
5780 /* Wakeup the applet ASAP. */
5781 si_applet_cant_get(si);
5782 si_applet_cant_put(si);
5783
5784 return 1;
5785}
5786
5787static void hlua_applet_tcp_fct(struct appctx *ctx)
5788{
5789 struct stream_interface *si = ctx->owner;
5790 struct stream *strm = si_strm(si);
5791 struct channel *res = si_ic(si);
5792 struct act_rule *rule = ctx->rule;
5793 struct proxy *px = strm->be;
5794 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5795
5796 /* The applet execution is already done. */
5797 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
5798 return;
5799
5800 /* If the stream is disconnect or closed, ldo nothing. */
5801 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5802 return;
5803
5804 /* Execute the function. */
5805 switch (hlua_ctx_resume(hlua, 1)) {
5806 /* finished. */
5807 case HLUA_E_OK:
5808 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5809
5810 /* log time */
5811 strm->logs.tv_request = now;
5812
5813 /* eat the whole request */
5814 bo_skip(si_oc(si), si_ob(si)->o);
5815 res->flags |= CF_READ_NULL;
5816 si_shutr(si);
5817 return;
5818
5819 /* yield. */
5820 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01005821 if (hlua->wake_time != TICK_ETERNITY)
5822 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005823 return;
5824
5825 /* finished with error. */
5826 case HLUA_E_ERRMSG:
5827 /* Display log. */
5828 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
5829 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
5830 lua_pop(hlua->T, 1);
5831 goto error;
5832
5833 case HLUA_E_ERR:
5834 /* Display log. */
5835 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
5836 rule->arg.hlua_rule->fcn.name);
5837 goto error;
5838
5839 default:
5840 goto error;
5841 }
5842
5843error:
5844
5845 /* For all other cases, just close the stream. */
5846 si_shutw(si);
5847 si_shutr(si);
5848 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5849}
5850
5851static void hlua_applet_tcp_release(struct appctx *ctx)
5852{
5853 task_free(ctx->ctx.hlua_apptcp.task);
5854 ctx->ctx.hlua_apptcp.task = NULL;
5855 hlua_ctx_destroy(&ctx->ctx.hlua_apptcp.hlua);
5856}
5857
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005858/* The function returns 1 if the initialisation is complete, 0 if
5859 * an errors occurs and -1 if more data are required for initializing
5860 * the applet.
5861 */
5862static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5863{
5864 struct stream_interface *si = ctx->owner;
5865 struct channel *req = si_oc(si);
5866 struct http_msg *msg;
5867 struct http_txn *txn;
5868 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5869 char **arg;
5870 struct hdr_ctx hdr;
5871 struct task *task;
5872 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01005873 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005874
5875 /* Wait for a full HTTP request. */
5876 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
5877 if (smp.flags & SMP_F_MAY_CHANGE)
5878 return -1;
5879 return 0;
5880 }
5881 txn = strm->txn;
5882 msg = &txn->req;
5883
Willy Tarreau0078bfc2015-10-07 20:20:28 +02005884 /* We want two things in HTTP mode :
5885 * - enforce server-close mode if we were in keep-alive, so that the
5886 * applet is released after each response ;
5887 * - enable request body transfer to the applet in order to resync
5888 * with the response body.
5889 */
5890 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
5891 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02005892
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005893 HLUA_INIT(hlua);
5894 ctx->ctx.hlua_apphttp.left_bytes = -1;
5895 ctx->ctx.hlua_apphttp.flags = 0;
5896
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01005897 if (txn->req.flags & HTTP_MSGF_VER_11)
5898 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
5899
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005900 /* Create task used by signal to wakeup applets. */
5901 task = task_new();
5902 if (!task) {
5903 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
5904 ctx->rule->arg.hlua_rule->fcn.name);
5905 return 0;
5906 }
5907 task->nice = 0;
5908 task->context = ctx;
5909 task->process = hlua_applet_wakeup;
5910 ctx->ctx.hlua_apphttp.task = task;
5911
5912 /* In the execution wrappers linked with a stream, the
5913 * Lua context can be not initialized. This behavior
5914 * permits to save performances because a systematic
5915 * Lua initialization cause 5% performances loss.
5916 */
5917 if (!hlua_ctx_init(hlua, task)) {
5918 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
5919 ctx->rule->arg.hlua_rule->fcn.name);
5920 return 0;
5921 }
5922
5923 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005924 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005925
5926 /* The following Lua calls can fail. */
5927 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005928 if (lua_type(hlua->T, -1) == LUA_TSTRING)
5929 error = lua_tostring(hlua->T, -1);
5930 else
5931 error = "critical error";
5932 SEND_ERR(px, "Lua applet http '%s': %s.\n",
5933 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005934 return 0;
5935 }
5936
5937 /* Check stack available size. */
5938 if (!lua_checkstack(hlua->T, 1)) {
5939 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5940 ctx->rule->arg.hlua_rule->fcn.name);
5941 RESET_SAFE_LJMP(hlua->T);
5942 return 0;
5943 }
5944
5945 /* Restore the function in the stack. */
5946 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5947
5948 /* Create and and push object stream in the stack. */
5949 if (!hlua_applet_http_new(hlua->T, ctx)) {
5950 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5951 ctx->rule->arg.hlua_rule->fcn.name);
5952 RESET_SAFE_LJMP(hlua->T);
5953 return 0;
5954 }
5955 hlua->nargs = 1;
5956
5957 /* Look for a 100-continue expected. */
5958 if (msg->flags & HTTP_MSGF_VER_11) {
5959 hdr.idx = 0;
5960 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
5961 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
5962 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
5963 }
5964
5965 /* push keywords in the stack. */
5966 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5967 if (!lua_checkstack(hlua->T, 1)) {
5968 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5969 ctx->rule->arg.hlua_rule->fcn.name);
5970 RESET_SAFE_LJMP(hlua->T);
5971 return 0;
5972 }
5973 lua_pushstring(hlua->T, *arg);
5974 hlua->nargs++;
5975 }
5976
5977 RESET_SAFE_LJMP(hlua->T);
5978
5979 /* Wakeup the applet when data is ready for read. */
5980 si_applet_cant_get(si);
5981
5982 return 1;
5983}
5984
5985static void hlua_applet_http_fct(struct appctx *ctx)
5986{
5987 struct stream_interface *si = ctx->owner;
5988 struct stream *strm = si_strm(si);
5989 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005990 struct act_rule *rule = ctx->rule;
5991 struct proxy *px = strm->be;
5992 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5993 char *blk1;
5994 int len1;
5995 char *blk2;
5996 int len2;
5997 int ret;
5998
5999 /* If the stream is disconnect or closed, ldo nothing. */
6000 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6001 return;
6002
6003 /* Set the currently running flag. */
6004 if (!HLUA_IS_RUNNING(hlua) &&
6005 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6006
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006007 /* Wait for full HTTP analysys. */
6008 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6009 si_applet_cant_get(si);
6010 return;
6011 }
6012
6013 /* Store the max amount of bytes that we can read. */
6014 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6015
6016 /* We need to flush the request header. This left the body
6017 * for the Lua.
6018 */
6019
6020 /* Read the maximum amount of data avalaible. */
6021 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
6022 if (ret == -1)
6023 return;
6024
6025 /* No data available, ask for more data. */
6026 if (ret == 1)
6027 len2 = 0;
6028 if (ret == 0)
6029 len1 = 0;
6030 if (len1 + len2 < strm->txn->req.eoh + 2) {
6031 si_applet_cant_get(si);
6032 return;
6033 }
6034
6035 /* skip the requests bytes. */
6036 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
6037 }
6038
6039 /* Executes The applet if it is not done. */
6040 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6041
6042 /* Execute the function. */
6043 switch (hlua_ctx_resume(hlua, 1)) {
6044 /* finished. */
6045 case HLUA_E_OK:
6046 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6047 break;
6048
6049 /* yield. */
6050 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006051 if (hlua->wake_time != TICK_ETERNITY)
6052 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006053 return;
6054
6055 /* finished with error. */
6056 case HLUA_E_ERRMSG:
6057 /* Display log. */
6058 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6059 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6060 lua_pop(hlua->T, 1);
6061 goto error;
6062
6063 case HLUA_E_ERR:
6064 /* Display log. */
6065 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6066 rule->arg.hlua_rule->fcn.name);
6067 goto error;
6068
6069 default:
6070 goto error;
6071 }
6072 }
6073
6074 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6075
6076 /* We must send the final chunk. */
6077 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6078 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6079
6080 /* sent last chunk at once. */
6081 ret = bi_putblk(res, "0\r\n\r\n", 5);
6082
6083 /* critical error. */
6084 if (ret == -2 || ret == -3) {
6085 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6086 rule->arg.hlua_rule->fcn.name);
6087 goto error;
6088 }
6089
6090 /* no enough space error. */
6091 if (ret == -1) {
6092 si_applet_cant_put(si);
6093 return;
6094 }
6095
6096 /* set the last chunk sent. */
6097 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6098 }
6099
6100 /* close the connection. */
6101
6102 /* status / log */
6103 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6104 strm->logs.tv_request = now;
6105
6106 /* eat the whole request */
6107 bo_skip(si_oc(si), si_ob(si)->o);
6108 res->flags |= CF_READ_NULL;
6109 si_shutr(si);
6110
6111 return;
6112 }
6113
6114error:
6115
6116 /* If we are in HTTP mode, and we are not send any
6117 * data, return a 500 server error in best effort:
6118 * if there are no room avalaible in the buffer,
6119 * just close the connection.
6120 */
6121 bi_putblk(res, error_500, strlen(error_500));
6122 if (!(strm->flags & SF_ERR_MASK))
6123 strm->flags |= SF_ERR_RESOURCE;
6124 si_shutw(si);
6125 si_shutr(si);
6126 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6127}
6128
6129static void hlua_applet_http_release(struct appctx *ctx)
6130{
6131 task_free(ctx->ctx.hlua_apphttp.task);
6132 ctx->ctx.hlua_apphttp.task = NULL;
6133 hlua_ctx_destroy(&ctx->ctx.hlua_apphttp.hlua);
6134}
6135
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006136/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6137 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006138 *
6139 * This function can fail with an abort() due to an Lua critical error.
6140 * We are in the configuration parsing process of HAProxy, this abort() is
6141 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006142 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006143static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6144 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006145{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006146 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006147
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006148 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006149 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006150 if (!rule->arg.hlua_rule) {
6151 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006152 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006153 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006154
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006155 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006156 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006157
6158 /* TODO: later accept arguments. */
6159 rule->arg.hlua_rule->args = NULL;
6160
Thierry FOURNIER42148732015-09-02 17:17:33 +02006161 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006162 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006163 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006164}
6165
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006166static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6167 struct act_rule *rule, char **err)
6168{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006169 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006170
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006171 /* HTTP applets are forbidden in tcp-request rules.
6172 * HTTP applet request requires everything initilized by
6173 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6174 * The applet will be immediately initilized, but its before
6175 * the call of this analyzer.
6176 */
6177 if (rule->from != ACT_F_HTTP_REQ) {
6178 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6179 return ACT_RET_PRS_ERR;
6180 }
6181
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006182 /* Memory for the rule. */
6183 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6184 if (!rule->arg.hlua_rule) {
6185 memprintf(err, "out of memory error");
6186 return ACT_RET_PRS_ERR;
6187 }
6188
6189 /* Reference the Lua function and store the reference. */
6190 rule->arg.hlua_rule->fcn = *fcn;
6191
6192 /* TODO: later accept arguments. */
6193 rule->arg.hlua_rule->args = NULL;
6194
6195 /* Add applet pointer in the rule. */
6196 rule->applet.obj_type = OBJ_TYPE_APPLET;
6197 rule->applet.name = fcn->name;
6198 rule->applet.init = hlua_applet_http_init;
6199 rule->applet.fct = hlua_applet_http_fct;
6200 rule->applet.release = hlua_applet_http_release;
6201 rule->applet.timeout = hlua_timeout_applet;
6202
6203 return ACT_RET_PRS_OK;
6204}
6205
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006206/* This function is an LUA binding used for registering
6207 * "sample-conv" functions. It expects a converter name used
6208 * in the haproxy configuration file, and an LUA function.
6209 */
6210__LJMP static int hlua_register_action(lua_State *L)
6211{
6212 struct action_kw_list *akl;
6213 const char *name;
6214 int ref;
6215 int len;
6216 struct hlua_function *fcn;
6217
Thierry FOURNIERed0bdaa2015-12-20 19:51:06 +01006218 MAY_LJMP(check_args(L, 3, "register_action"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006219
6220 /* First argument : converter name. */
6221 name = MAY_LJMP(luaL_checkstring(L, 1));
6222
6223 /* Second argument : environment. */
6224 if (lua_type(L, 2) != LUA_TTABLE)
6225 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6226
6227 /* Third argument : lua function. */
6228 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6229
6230 /* browse the second argulent as an array. */
6231 lua_pushnil(L);
6232 while (lua_next(L, 2) != 0) {
6233 if (lua_type(L, -1) != LUA_TSTRING)
6234 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6235
6236 /* Check required environment. Only accepted "http" or "tcp". */
6237 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006238 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006239 if (!akl)
6240 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006241 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006242 if (!fcn)
6243 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6244
6245 /* Fill fcn. */
6246 fcn->name = strdup(name);
6247 if (!fcn->name)
6248 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6249 fcn->function_ref = ref;
6250
6251 /* List head */
6252 akl->list.n = akl->list.p = NULL;
6253
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006254 /* action keyword. */
6255 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006256 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006257 if (!akl->kw[0].kw)
6258 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6259
6260 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6261
6262 akl->kw[0].match_pfx = 0;
6263 akl->kw[0].private = fcn;
6264 akl->kw[0].parse = action_register_lua;
6265
6266 /* select the action registering point. */
6267 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6268 tcp_req_cont_keywords_register(akl);
6269 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6270 tcp_res_cont_keywords_register(akl);
6271 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6272 http_req_keywords_register(akl);
6273 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6274 http_res_keywords_register(akl);
6275 else
6276 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6277 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6278 "are expected.", lua_tostring(L, -1)));
6279
6280 /* pop the environment string. */
6281 lua_pop(L, 1);
6282 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006283 return ACT_RET_PRS_OK;
6284}
6285
6286static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6287 struct act_rule *rule, char **err)
6288{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006289 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006290
6291 /* Memory for the rule. */
6292 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6293 if (!rule->arg.hlua_rule) {
6294 memprintf(err, "out of memory error");
6295 return ACT_RET_PRS_ERR;
6296 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006297
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006298 /* Reference the Lua function and store the reference. */
6299 rule->arg.hlua_rule->fcn = *fcn;
6300
6301 /* TODO: later accept arguments. */
6302 rule->arg.hlua_rule->args = NULL;
6303
6304 /* Add applet pointer in the rule. */
6305 rule->applet.obj_type = OBJ_TYPE_APPLET;
6306 rule->applet.name = fcn->name;
6307 rule->applet.init = hlua_applet_tcp_init;
6308 rule->applet.fct = hlua_applet_tcp_fct;
6309 rule->applet.release = hlua_applet_tcp_release;
6310 rule->applet.timeout = hlua_timeout_applet;
6311
6312 return 0;
6313}
6314
6315/* This function is an LUA binding used for registering
6316 * "sample-conv" functions. It expects a converter name used
6317 * in the haproxy configuration file, and an LUA function.
6318 */
6319__LJMP static int hlua_register_service(lua_State *L)
6320{
6321 struct action_kw_list *akl;
6322 const char *name;
6323 const char *env;
6324 int ref;
6325 int len;
6326 struct hlua_function *fcn;
6327
6328 MAY_LJMP(check_args(L, 3, "register_service"));
6329
6330 /* First argument : converter name. */
6331 name = MAY_LJMP(luaL_checkstring(L, 1));
6332
6333 /* Second argument : environment. */
6334 env = MAY_LJMP(luaL_checkstring(L, 2));
6335
6336 /* Third argument : lua function. */
6337 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6338
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006339 /* Allocate and fill the sample fetch keyword struct. */
6340 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6341 if (!akl)
6342 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6343 fcn = calloc(1, sizeof(*fcn));
6344 if (!fcn)
6345 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6346
6347 /* Fill fcn. */
6348 len = strlen("<lua.>") + strlen(name) + 1;
6349 fcn->name = calloc(1, len);
6350 if (!fcn->name)
6351 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6352 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6353 fcn->function_ref = ref;
6354
6355 /* List head */
6356 akl->list.n = akl->list.p = NULL;
6357
6358 /* converter keyword. */
6359 len = strlen("lua.") + strlen(name) + 1;
6360 akl->kw[0].kw = calloc(1, len);
6361 if (!akl->kw[0].kw)
6362 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6363
6364 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6365
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01006366 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006367 if (strcmp(env, "tcp") == 0)
6368 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006369 else if (strcmp(env, "http") == 0)
6370 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006371 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006372 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6373 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006374
6375 akl->kw[0].match_pfx = 0;
6376 akl->kw[0].private = fcn;
6377
6378 /* End of array. */
6379 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6380
6381 /* Register this new converter */
6382 service_keywords_register(akl);
6383
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006384 return 0;
6385}
6386
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006387/* This function initialises Lua cli handler. It copies the
6388 * arguments in the Lua stack and create channel IO objects.
6389 */
6390static int hlua_cli_parse_fct(char **args, struct appctx *appctx, void *private)
6391{
6392 struct hlua *hlua;
6393 struct hlua_function *fcn;
6394 int i;
6395 const char *error;
6396
6397 hlua = &appctx->ctx.hlua_cli.hlua;
6398 fcn = private;
6399 appctx->private = private;
6400
6401 /* Create task used by signal to wakeup applets.
6402 * We use the same wakeup fonction than the Lua applet_tcp and
6403 * applet_http. It is absolutely compatible.
6404 */
6405 appctx->ctx.hlua_cli.task = task_new();
6406 if (!appctx->ctx.hlua_cli.task) {
6407 SEND_ERR(NULL, "Lua applet tcp '%s': out of memory.\n", fcn->name);
6408 return 0;
6409 }
6410 appctx->ctx.hlua_cli.task->nice = 0;
6411 appctx->ctx.hlua_cli.task->context = appctx;
6412 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
6413
6414 /* Initialises the Lua context */
6415 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
6416 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
6417 return 1;
6418 }
6419
6420 /* The following Lua calls can fail. */
6421 if (!SET_SAFE_LJMP(hlua->T)) {
6422 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6423 error = lua_tostring(hlua->T, -1);
6424 else
6425 error = "critical error";
6426 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
6427 goto error;
6428 }
6429
6430 /* Check stack available size. */
6431 if (!lua_checkstack(hlua->T, 2)) {
6432 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6433 goto error;
6434 }
6435
6436 /* Restore the function in the stack. */
6437 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
6438
6439 /* Once the arguments parsed, the CLI is like an AppletTCP,
6440 * so push AppletTCP in the stack.
6441 * TODO: get_priv() and set_priv() are useless. Maybe we will
6442 * create a new object without these two functions.
6443 */
6444 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
6445 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6446 goto error;
6447 }
6448 hlua->nargs = 1;
6449
6450 /* push keywords in the stack. */
6451 for (i = 0; *args[i]; i++) {
6452 /* Check stack available size. */
6453 if (!lua_checkstack(hlua->T, 1)) {
6454 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6455 goto error;
6456 }
6457 lua_pushstring(hlua->T, args[i]);
6458 hlua->nargs++;
6459 }
6460
6461 /* We must initialize the execution timeouts. */
6462 hlua->max_time = hlua_timeout_session;
6463
6464 /* At this point the execution is safe. */
6465 RESET_SAFE_LJMP(hlua->T);
6466
6467 /* It's ok */
6468 return 0;
6469
6470 /* It's not ok. */
6471error:
6472 RESET_SAFE_LJMP(hlua->T);
6473 hlua_ctx_destroy(hlua);
6474 return 1;
6475}
6476
6477static int hlua_cli_io_handler_fct(struct appctx *appctx)
6478{
6479 struct hlua *hlua;
6480 struct stream_interface *si;
6481 struct hlua_function *fcn;
6482
6483 hlua = &appctx->ctx.hlua_cli.hlua;
6484 si = appctx->owner;
6485 fcn = appctx->private;
6486
6487 /* If the stream is disconnect or closed, ldo nothing. */
6488 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6489 return 1;
6490
6491 /* Execute the function. */
6492 switch (hlua_ctx_resume(hlua, 1)) {
6493
6494 /* finished. */
6495 case HLUA_E_OK:
6496 return 1;
6497
6498 /* yield. */
6499 case HLUA_E_AGAIN:
6500 /* We want write. */
6501 if (HLUA_IS_WAKERESWR(hlua))
6502 si_applet_cant_put(si);
6503 /* Set the timeout. */
6504 if (hlua->wake_time != TICK_ETERNITY)
6505 task_schedule(hlua->task, hlua->wake_time);
6506 return 0;
6507
6508 /* finished with error. */
6509 case HLUA_E_ERRMSG:
6510 /* Display log. */
6511 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
6512 fcn->name, lua_tostring(hlua->T, -1));
6513 lua_pop(hlua->T, 1);
6514 return 1;
6515
6516 case HLUA_E_ERR:
6517 /* Display log. */
6518 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
6519 fcn->name);
6520 return 1;
6521
6522 default:
6523 return 1;
6524 }
6525
6526 return 1;
6527}
6528
6529static void hlua_cli_io_release_fct(struct appctx *appctx)
6530{
6531 struct hlua *hlua;
6532
6533 hlua = &appctx->ctx.hlua_cli.hlua;
6534 hlua_ctx_destroy(hlua);
6535}
6536
6537/* This function is an LUA binding used for registering
6538 * new keywords in the cli. It expects a list of keywords
6539 * which are the "path". It is limited to 5 keywords. A
6540 * description of the command, a function to be executed
6541 * for the parsing and a function for io handlers.
6542 */
6543__LJMP static int hlua_register_cli(lua_State *L)
6544{
6545 struct cli_kw_list *cli_kws;
6546 const char *message;
6547 int ref_io;
6548 int len;
6549 struct hlua_function *fcn;
6550 int index;
6551 int i;
6552
6553 MAY_LJMP(check_args(L, 3, "register_cli"));
6554
6555 /* First argument : an array of maximum 5 keywords. */
6556 if (!lua_istable(L, 1))
6557 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
6558
6559 /* Second argument : string with contextual message. */
6560 message = MAY_LJMP(luaL_checkstring(L, 2));
6561
6562 /* Third and fourth argument : lua function. */
6563 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
6564
6565 /* Allocate and fill the sample fetch keyword struct. */
6566 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
6567 if (!cli_kws)
6568 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6569 fcn = calloc(1, sizeof(*fcn));
6570 if (!fcn)
6571 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6572
6573 /* Fill path. */
6574 index = 0;
6575 lua_pushnil(L);
6576 while(lua_next(L, 1) != 0) {
6577 if (index >= 5)
6578 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
6579 if (lua_type(L, -1) != LUA_TSTRING)
6580 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
6581 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
6582 if (!cli_kws->kw[0].str_kw[index])
6583 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6584 index++;
6585 lua_pop(L, 1);
6586 }
6587
6588 /* Copy help message. */
6589 cli_kws->kw[0].usage = strdup(message);
6590 if (!cli_kws->kw[0].usage)
6591 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6592
6593 /* Fill fcn io handler. */
6594 len = strlen("<lua.cli>") + 1;
6595 for (i = 0; i < index; i++)
6596 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
6597 fcn->name = calloc(1, len);
6598 if (!fcn->name)
6599 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6600 strncat((char *)fcn->name, "<lua.cli", len);
6601 for (i = 0; i < index; i++) {
6602 strncat((char *)fcn->name, ".", len);
6603 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
6604 }
6605 strncat((char *)fcn->name, ">", len);
6606 fcn->function_ref = ref_io;
6607
6608 /* Fill last entries. */
6609 cli_kws->kw[0].private = fcn;
6610 cli_kws->kw[0].parse = hlua_cli_parse_fct;
6611 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
6612 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
6613
6614 /* Register this new converter */
6615 cli_register_kw(cli_kws);
6616
6617 return 0;
6618}
6619
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006620static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
6621 struct proxy *defpx, const char *file, int line,
6622 char **err, unsigned int *timeout)
6623{
6624 const char *error;
6625
6626 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
6627 if (error && *error != '\0') {
6628 memprintf(err, "%s: invalid timeout", args[0]);
6629 return -1;
6630 }
6631 return 0;
6632}
6633
6634static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
6635 struct proxy *defpx, const char *file, int line,
6636 char **err)
6637{
6638 return hlua_read_timeout(args, section_type, curpx, defpx,
6639 file, line, err, &hlua_timeout_session);
6640}
6641
6642static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
6643 struct proxy *defpx, const char *file, int line,
6644 char **err)
6645{
6646 return hlua_read_timeout(args, section_type, curpx, defpx,
6647 file, line, err, &hlua_timeout_task);
6648}
6649
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006650static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
6651 struct proxy *defpx, const char *file, int line,
6652 char **err)
6653{
6654 return hlua_read_timeout(args, section_type, curpx, defpx,
6655 file, line, err, &hlua_timeout_applet);
6656}
6657
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006658static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
6659 struct proxy *defpx, const char *file, int line,
6660 char **err)
6661{
6662 char *error;
6663
6664 hlua_nb_instruction = strtoll(args[1], &error, 10);
6665 if (*error != '\0') {
6666 memprintf(err, "%s: invalid number", args[0]);
6667 return -1;
6668 }
6669 return 0;
6670}
6671
Willy Tarreau32f61e22015-03-18 17:54:59 +01006672static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
6673 struct proxy *defpx, const char *file, int line,
6674 char **err)
6675{
6676 char *error;
6677
6678 if (*(args[1]) == 0) {
6679 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
6680 return -1;
6681 }
6682 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
6683 if (*error != '\0') {
6684 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
6685 return -1;
6686 }
6687 return 0;
6688}
6689
6690
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006691/* This function is called by the main configuration key "lua-load". It loads and
6692 * execute an lua file during the parsing of the HAProxy configuration file. It is
6693 * the main lua entry point.
6694 *
6695 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
6696 * occured, otherwise it returns 0.
6697 *
6698 * In some error case, LUA set an error message in top of the stack. This function
6699 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006700 *
6701 * This function can fail with an abort() due to an Lua critical error.
6702 * We are in the configuration parsing process of HAProxy, this abort() is
6703 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006704 */
6705static int hlua_load(char **args, int section_type, struct proxy *curpx,
6706 struct proxy *defpx, const char *file, int line,
6707 char **err)
6708{
6709 int error;
6710
6711 /* Just load and compile the file. */
6712 error = luaL_loadfile(gL.T, args[1]);
6713 if (error) {
6714 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
6715 lua_pop(gL.T, 1);
6716 return -1;
6717 }
6718
6719 /* If no syntax error where detected, execute the code. */
6720 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
6721 switch (error) {
6722 case LUA_OK:
6723 break;
6724 case LUA_ERRRUN:
6725 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
6726 lua_pop(gL.T, 1);
6727 return -1;
6728 case LUA_ERRMEM:
6729 memprintf(err, "lua out of memory error\n");
6730 return -1;
6731 case LUA_ERRERR:
6732 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
6733 lua_pop(gL.T, 1);
6734 return -1;
6735 case LUA_ERRGCMM:
6736 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
6737 lua_pop(gL.T, 1);
6738 return -1;
6739 default:
6740 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
6741 lua_pop(gL.T, 1);
6742 return -1;
6743 }
6744
6745 return 0;
6746}
6747
6748/* configuration keywords declaration */
6749static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006750 { CFG_GLOBAL, "lua-load", hlua_load },
6751 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
6752 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02006753 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006754 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01006755 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006756 { 0, NULL, NULL },
6757}};
6758
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006759/* This function can fail with an abort() due to an Lua critical error.
6760 * We are in the initialisation process of HAProxy, this abort() is
6761 * tolerated.
6762 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006763int hlua_post_init()
6764{
6765 struct hlua_init_function *init;
6766 const char *msg;
6767 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006768 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006769
Thierry Fournier3d4a6752016-02-19 20:53:30 +01006770 /* Call post initialisation function in safe environement. */
6771 if (!SET_SAFE_LJMP(gL.T)) {
6772 if (lua_type(gL.T, -1) == LUA_TSTRING)
6773 error = lua_tostring(gL.T, -1);
6774 else
6775 error = "critical error";
6776 fprintf(stderr, "Lua post-init: %s.\n", error);
6777 exit(1);
6778 }
6779 hlua_fcn_post_init(gL.T);
6780 RESET_SAFE_LJMP(gL.T);
6781
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006782 list_for_each_entry(init, &hlua_init_functions, l) {
6783 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
6784 ret = hlua_ctx_resume(&gL, 0);
6785 switch (ret) {
6786 case HLUA_E_OK:
6787 lua_pop(gL.T, -1);
6788 return 1;
6789 case HLUA_E_AGAIN:
6790 Alert("lua init: yield not allowed.\n");
6791 return 0;
6792 case HLUA_E_ERRMSG:
6793 msg = lua_tostring(gL.T, -1);
6794 Alert("lua init: %s.\n", msg);
6795 return 0;
6796 case HLUA_E_ERR:
6797 default:
6798 Alert("lua init: unknown runtime error.\n");
6799 return 0;
6800 }
6801 }
6802 return 1;
6803}
6804
Willy Tarreau32f61e22015-03-18 17:54:59 +01006805/* The memory allocator used by the Lua stack. <ud> is a pointer to the
6806 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
6807 * is the previously allocated size or the kind of object in case of a new
6808 * allocation. <nsize> is the requested new size.
6809 */
6810static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
6811{
6812 struct hlua_mem_allocator *zone = ud;
6813
6814 if (nsize == 0) {
6815 /* it's a free */
6816 if (ptr)
6817 zone->allocated -= osize;
6818 free(ptr);
6819 return NULL;
6820 }
6821
6822 if (!ptr) {
6823 /* it's a new allocation */
6824 if (zone->limit && zone->allocated + nsize > zone->limit)
6825 return NULL;
6826
6827 ptr = malloc(nsize);
6828 if (ptr)
6829 zone->allocated += nsize;
6830 return ptr;
6831 }
6832
6833 /* it's a realloc */
6834 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
6835 return NULL;
6836
6837 ptr = realloc(ptr, nsize);
6838 if (ptr)
6839 zone->allocated += nsize - osize;
6840 return ptr;
6841}
6842
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006843/* Ithis function can fail with an abort() due to an Lua critical error.
6844 * We are in the initialisation process of HAProxy, this abort() is
6845 * tolerated.
6846 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01006847void hlua_init(void)
6848{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006849 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006850 int idx;
6851 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006852 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006853 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006854 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006855#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006856 struct srv_kw *kw;
6857 int tmp_error;
6858 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01006859 char *args[] = { /* SSL client configuration. */
6860 "ssl",
6861 "verify",
6862 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01006863 NULL
6864 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006865#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006866
Willy Tarreau87b09662015-04-03 00:22:06 +02006867 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006868 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
6869
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006870 /* Register configuration keywords. */
6871 cfg_register_keywords(&cfg_kws);
6872
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006873 /* Init main lua stack. */
6874 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01006875 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006876 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006877 gL.T = luaL_newstate();
6878 hlua_sethlua(&gL);
6879 gL.Tref = LUA_REFNIL;
6880 gL.task = NULL;
6881
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006882 /* From this point, until the end of the initialisation fucntion,
6883 * the Lua function can fail with an abort. We are in the initialisation
6884 * process of HAProxy, this abort() is tolerated.
6885 */
6886
Willy Tarreau32f61e22015-03-18 17:54:59 +01006887 /* change the memory allocators to track memory usage */
6888 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
6889
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006890 /* Initialise lua. */
6891 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006892
Thierry Fournier75933d42016-01-21 09:30:18 +01006893 /* Set safe environment for the initialisation. */
6894 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006895 if (lua_type(gL.T, -1) == LUA_TSTRING)
6896 error_msg = lua_tostring(gL.T, -1);
6897 else
6898 error_msg = "critical error";
6899 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01006900 exit(1);
6901 }
6902
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006903 /*
6904 *
6905 * Create "core" object.
6906 *
6907 */
6908
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01006909 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006910 lua_newtable(gL.T);
6911
6912 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006913 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006914 hlua_class_const_int(gL.T, log_levels[i], i);
6915
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006916 /* Register special functions. */
6917 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006918 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006919 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006920 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006921 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006922 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006923 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006924 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01006925 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006926 hlua_class_function(gL.T, "sleep", hlua_sleep);
6927 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01006928 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
6929 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
6930 hlua_class_function(gL.T, "set_map", hlua_set_map);
6931 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006932 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006933 hlua_class_function(gL.T, "log", hlua_log);
6934 hlua_class_function(gL.T, "Debug", hlua_log_debug);
6935 hlua_class_function(gL.T, "Info", hlua_log_info);
6936 hlua_class_function(gL.T, "Warning", hlua_log_warning);
6937 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02006938 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01006939 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006940
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006941 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006942
6943 /*
6944 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006945 * Register class Map
6946 *
6947 */
6948
6949 /* This table entry is the object "Map" base. */
6950 lua_newtable(gL.T);
6951
6952 /* register pattern types. */
6953 for (i=0; i<PAT_MATCH_NUM; i++)
6954 hlua_class_const_int(gL.T, pat_match_names[i], i);
6955
6956 /* register constructor. */
6957 hlua_class_function(gL.T, "new", hlua_map_new);
6958
6959 /* Create and fill the metatable. */
6960 lua_newtable(gL.T);
6961
6962 /* Create and fille the __index entry. */
6963 lua_pushstring(gL.T, "__index");
6964 lua_newtable(gL.T);
6965
6966 /* Register . */
6967 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
6968 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
6969
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006970 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006971
Thierry Fournier45e78d72016-02-19 18:34:46 +01006972 /* Register previous table in the registry with reference and named entry.
6973 * The function hlua_register_metatable() pops the stack, so we
6974 * previously create a copy of the table.
6975 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006976 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01006977 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006978
6979 /* Assign the metatable to the mai Map object. */
6980 lua_setmetatable(gL.T, -2);
6981
6982 /* Set a name to the table. */
6983 lua_setglobal(gL.T, "Map");
6984
6985 /*
6986 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006987 * Register class Channel
6988 *
6989 */
6990
6991 /* Create and fill the metatable. */
6992 lua_newtable(gL.T);
6993
6994 /* Create and fille the __index entry. */
6995 lua_pushstring(gL.T, "__index");
6996 lua_newtable(gL.T);
6997
6998 /* Register . */
6999 hlua_class_function(gL.T, "get", hlua_channel_get);
7000 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7001 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7002 hlua_class_function(gL.T, "set", hlua_channel_set);
7003 hlua_class_function(gL.T, "append", hlua_channel_append);
7004 hlua_class_function(gL.T, "send", hlua_channel_send);
7005 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7006 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7007 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007008 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007009
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007010 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007011
7012 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007013 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007014
7015 /*
7016 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007017 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007018 *
7019 */
7020
7021 /* Create and fill the metatable. */
7022 lua_newtable(gL.T);
7023
7024 /* Create and fille the __index entry. */
7025 lua_pushstring(gL.T, "__index");
7026 lua_newtable(gL.T);
7027
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007028 /* Browse existing fetches and create the associated
7029 * object method.
7030 */
7031 sf = NULL;
7032 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7033
7034 /* Dont register the keywork if the arguments check function are
7035 * not safe during the runtime.
7036 */
7037 if ((sf->val_args != NULL) &&
7038 (sf->val_args != val_payload_lv) &&
7039 (sf->val_args != val_hdr))
7040 continue;
7041
7042 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7043 * by an underscore.
7044 */
7045 strncpy(trash.str, sf->kw, trash.size);
7046 trash.str[trash.size - 1] = '\0';
7047 for (p = trash.str; *p; p++)
7048 if (*p == '.' || *p == '-' || *p == '+')
7049 *p = '_';
7050
7051 /* Register the function. */
7052 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007053 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007054 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007055 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007056 }
7057
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007058 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007059
7060 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007061 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007062
7063 /*
7064 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007065 * Register class Converters
7066 *
7067 */
7068
7069 /* Create and fill the metatable. */
7070 lua_newtable(gL.T);
7071
7072 /* Create and fill the __index entry. */
7073 lua_pushstring(gL.T, "__index");
7074 lua_newtable(gL.T);
7075
7076 /* Browse existing converters and create the associated
7077 * object method.
7078 */
7079 sc = NULL;
7080 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7081 /* Dont register the keywork if the arguments check function are
7082 * not safe during the runtime.
7083 */
7084 if (sc->val_args != NULL)
7085 continue;
7086
7087 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7088 * by an underscore.
7089 */
7090 strncpy(trash.str, sc->kw, trash.size);
7091 trash.str[trash.size - 1] = '\0';
7092 for (p = trash.str; *p; p++)
7093 if (*p == '.' || *p == '-' || *p == '+')
7094 *p = '_';
7095
7096 /* Register the function. */
7097 lua_pushstring(gL.T, trash.str);
7098 lua_pushlightuserdata(gL.T, sc);
7099 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007100 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007101 }
7102
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007103 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007104
7105 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007106 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007107
7108 /*
7109 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007110 * Register class HTTP
7111 *
7112 */
7113
7114 /* Create and fill the metatable. */
7115 lua_newtable(gL.T);
7116
7117 /* Create and fille the __index entry. */
7118 lua_pushstring(gL.T, "__index");
7119 lua_newtable(gL.T);
7120
7121 /* Register Lua functions. */
7122 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7123 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7124 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7125 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7126 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7127 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7128 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7129 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7130 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7131 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7132
7133 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7134 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7135 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7136 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7137 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7138 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007139 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007140
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007141 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007142
7143 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007144 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007145
7146 /*
7147 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007148 * Register class AppletTCP
7149 *
7150 */
7151
7152 /* Create and fill the metatable. */
7153 lua_newtable(gL.T);
7154
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007155 /* Create and fille the __index entry. */
7156 lua_pushstring(gL.T, "__index");
7157 lua_newtable(gL.T);
7158
7159 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007160 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7161 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7162 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7163 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7164 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007165
7166 lua_settable(gL.T, -3);
7167
7168 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007169 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007170
7171 /*
7172 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007173 * Register class AppletHTTP
7174 *
7175 */
7176
7177 /* Create and fill the metatable. */
7178 lua_newtable(gL.T);
7179
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007180 /* Create and fille the __index entry. */
7181 lua_pushstring(gL.T, "__index");
7182 lua_newtable(gL.T);
7183
7184 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007185 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7186 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007187 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7188 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7189 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7190 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7191 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7192 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7193
7194 lua_settable(gL.T, -3);
7195
7196 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007197 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007198
7199 /*
7200 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007201 * Register class TXN
7202 *
7203 */
7204
7205 /* Create and fill the metatable. */
7206 lua_newtable(gL.T);
7207
7208 /* Create and fille the __index entry. */
7209 lua_pushstring(gL.T, "__index");
7210 lua_newtable(gL.T);
7211
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007212 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007213 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7214 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007215 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007216 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007217 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007218 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007219 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7220 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7221 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007222 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7223 hlua_class_function(gL.T, "log", hlua_txn_log);
7224 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7225 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7226 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7227 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007228
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007229 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007230
7231 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007232 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007233
7234 /*
7235 *
7236 * Register class Socket
7237 *
7238 */
7239
7240 /* Create and fill the metatable. */
7241 lua_newtable(gL.T);
7242
7243 /* Create and fille the __index entry. */
7244 lua_pushstring(gL.T, "__index");
7245 lua_newtable(gL.T);
7246
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007247#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007248 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007249#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007250 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7251 hlua_class_function(gL.T, "send", hlua_socket_send);
7252 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7253 hlua_class_function(gL.T, "close", hlua_socket_close);
7254 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7255 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7256 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7257 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7258
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007259 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007260
7261 /* Register the garbage collector entry. */
7262 lua_pushstring(gL.T, "__gc");
7263 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007264 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007265
7266 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007267 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007268
7269 /* Proxy and server configuration initialisation. */
7270 memset(&socket_proxy, 0, sizeof(socket_proxy));
7271 init_new_proxy(&socket_proxy);
7272 socket_proxy.parent = NULL;
7273 socket_proxy.last_change = now.tv_sec;
7274 socket_proxy.id = "LUA-SOCKET";
7275 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7276 socket_proxy.maxconn = 0;
7277 socket_proxy.accept = NULL;
7278 socket_proxy.options2 |= PR_O2_INDEPSTR;
7279 socket_proxy.srv = NULL;
7280 socket_proxy.conn_retries = 0;
7281 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7282
7283 /* Init TCP server: unchanged parameters */
7284 memset(&socket_tcp, 0, sizeof(socket_tcp));
7285 socket_tcp.next = NULL;
7286 socket_tcp.proxy = &socket_proxy;
7287 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7288 LIST_INIT(&socket_tcp.actconns);
7289 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007290 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007291 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007292 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007293 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
7294 socket_tcp.last_change = 0;
7295 socket_tcp.id = "LUA-TCP-CONN";
7296 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7297 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7298 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7299
7300 /* XXX: Copy default parameter from default server,
7301 * but the default server is not initialized.
7302 */
7303 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7304 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7305 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7306 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7307 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7308 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7309 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7310 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7311 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7312 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7313
7314 socket_tcp.check.status = HCHK_STATUS_INI;
7315 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7316 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7317 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7318 socket_tcp.check.server = &socket_tcp;
7319
7320 socket_tcp.agent.status = HCHK_STATUS_INI;
7321 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7322 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7323 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7324 socket_tcp.agent.server = &socket_tcp;
7325
7326 socket_tcp.xprt = &raw_sock;
7327
7328#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007329 /* Init TCP server: unchanged parameters */
7330 memset(&socket_ssl, 0, sizeof(socket_ssl));
7331 socket_ssl.next = NULL;
7332 socket_ssl.proxy = &socket_proxy;
7333 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7334 LIST_INIT(&socket_ssl.actconns);
7335 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007336 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007337 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007338 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007339 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
7340 socket_ssl.last_change = 0;
7341 socket_ssl.id = "LUA-SSL-CONN";
7342 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7343 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7344 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7345
7346 /* XXX: Copy default parameter from default server,
7347 * but the default server is not initialized.
7348 */
7349 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7350 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7351 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7352 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7353 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7354 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7355 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7356 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7357 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7358 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7359
7360 socket_ssl.check.status = HCHK_STATUS_INI;
7361 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7362 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7363 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7364 socket_ssl.check.server = &socket_ssl;
7365
7366 socket_ssl.agent.status = HCHK_STATUS_INI;
7367 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7368 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7369 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7370 socket_ssl.agent.server = &socket_ssl;
7371
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007372 socket_ssl.use_ssl = 1;
7373 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007374
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007375 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007376 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7377 /*
7378 *
7379 * If the keyword is not known, we can search in the registered
7380 * server keywords. This is usefull to configure special SSL
7381 * features like client certificates and ssl_verify.
7382 *
7383 */
7384 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7385 if (tmp_error != 0) {
7386 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7387 abort(); /* This must be never arrives because the command line
7388 not editable by the user. */
7389 }
7390 idx += kw->skip;
7391 }
7392 }
7393
7394 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007395 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007396#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007397
7398 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007399}