blob: 0045a1c5d9456e0c0c8d94ddb76c76bb0f9de4ca [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010013#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020014#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010016#include <lauxlib.h>
17#include <lua.h>
18#include <lualib.h>
19
Thierry FOURNIER463119c2015-03-10 00:35:36 +010020#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
21#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010022#endif
23
Thierry FOURNIER380d0932015-01-23 14:27:52 +010024#include <ebpttree.h>
25
26#include <common/cfgparse.h>
27
William Lallemand9ed62032016-11-21 17:49:11 +010028#include <types/cli.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010029#include <types/hlua.h>
30#include <types/proxy.h>
William Lallemand9ed62032016-11-21 17:49:11 +010031#include <types/stats.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010032
Thierry FOURNIER55da1652015-01-23 11:36:30 +010033#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020034#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010035#include <proto/channel.h>
William Lallemand9ed62032016-11-21 17:49:11 +010036#include <proto/cli.h>
Willy Tarreaua71f6422016-11-16 17:00:14 +010037#include <proto/connection.h>
William Lallemand9ed62032016-11-21 17:49:11 +010038#include <proto/stats.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010039#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010040#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010041#include <proto/hlua_fcn.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020042#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010043#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010044#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010045#include <proto/payload.h>
46#include <proto/proto_http.h>
47#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010048#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020049#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020050#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010051#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010052#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010053#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020054#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010055
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010056/* Lua uses longjmp to perform yield or throwing errors. This
57 * macro is used only for identifying the function that can
58 * not return because a longjmp is executed.
59 * __LJMP marks a prototype of hlua file that can use longjmp.
60 * WILL_LJMP() marks an lua function that will use longjmp.
61 * MAY_LJMP() marks an lua function that may use longjmp.
62 */
63#define __LJMP
64#define WILL_LJMP(func) func
65#define MAY_LJMP(func) func
66
Thierry FOURNIERbabae282015-09-17 11:36:37 +020067/* This couple of function executes securely some Lua calls outside of
68 * the lua runtime environment. Each Lua call can return a longjmp
69 * if it encounter a memory error.
70 *
71 * Lua documentation extract:
72 *
73 * If an error happens outside any protected environment, Lua calls
74 * a panic function (see lua_atpanic) and then calls abort, thus
75 * exiting the host application. Your panic function can avoid this
76 * exit by never returning (e.g., doing a long jump to your own
77 * recovery point outside Lua).
78 *
79 * The panic function runs as if it were a message handler (see
80 * §2.3); in particular, the error message is at the top of the
81 * stack. However, there is no guarantee about stack space. To push
82 * anything on the stack, the panic function must first check the
83 * available space (see §4.2).
84 *
85 * We must check all the Lua entry point. This includes:
86 * - The include/proto/hlua.h exported functions
87 * - the task wrapper function
88 * - The action wrapper function
89 * - The converters wrapper function
90 * - The sample-fetch wrapper functions
91 *
92 * It is tolerated that the initilisation function returns an abort.
93 * Before each Lua abort, an error message is writed on stderr.
94 *
95 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
96 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
97 * because they must be exists in the program stack when the longjmp
98 * is called.
99 */
100jmp_buf safe_ljmp_env;
101static int hlua_panic_safe(lua_State *L) { return 0; }
102static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
103
104#define SET_SAFE_LJMP(__L) \
105 ({ \
106 int ret; \
107 if (setjmp(safe_ljmp_env) != 0) { \
108 lua_atpanic(__L, hlua_panic_safe); \
109 ret = 0; \
110 } else { \
111 lua_atpanic(__L, hlua_panic_ljmp); \
112 ret = 1; \
113 } \
114 ret; \
115 })
116
117/* If we are the last function catching Lua errors, we
118 * must reset the panic function.
119 */
120#define RESET_SAFE_LJMP(__L) \
121 do { \
122 lua_atpanic(__L, hlua_panic_safe); \
123 } while(0)
124
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200125/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200126#define APPLET_DONE 0x01 /* applet processing is done. */
127#define APPLET_100C 0x02 /* 100 continue expected. */
128#define APPLET_HDR_SENT 0x04 /* Response header sent. */
129#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
130#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100131#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200132
133#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200134
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100135/* The main Lua execution context. */
136struct hlua gL;
137
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100138/* This is the memory pool containing struct lua for applets
139 * (including cli).
140 */
141struct pool_head *pool2_hlua;
142
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100143/* This is the memory pool containing all the signal structs. These
144 * struct are used to store each requiered signal between two tasks.
145 */
146struct pool_head *pool2_hlua_com;
147
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100148/* Used for Socket connection. */
149static struct proxy socket_proxy;
150static struct server socket_tcp;
151#ifdef USE_OPENSSL
152static struct server socket_ssl;
153#endif
154
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100155/* List head of the function called at the initialisation time. */
156struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
157
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100158/* The following variables contains the reference of the different
159 * Lua classes. These references are useful for identify metadata
160 * associated with an object.
161 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100162static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100163static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100164static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100165static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100166static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100167static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200168static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200169static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200170static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100171
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100172/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200173 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100174 * short timeout. Lua linked with tasks doesn't have a timeout
175 * because a task may remain alive during all the haproxy execution.
176 */
177static unsigned int hlua_timeout_session = 4000; /* session timeout. */
178static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200179static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100180
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100181/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
182 * it is used for preventing infinite loops.
183 *
184 * I test the scheer with an infinite loop containing one incrementation
185 * and one test. I run this loop between 10 seconds, I raise a ceil of
186 * 710M loops from one interrupt each 9000 instructions, so I fix the value
187 * to one interrupt each 10 000 instructions.
188 *
189 * configured | Number of
190 * instructions | loops executed
191 * between two | in milions
192 * forced yields |
193 * ---------------+---------------
194 * 10 | 160
195 * 500 | 670
196 * 1000 | 680
197 * 5000 | 700
198 * 7000 | 700
199 * 8000 | 700
200 * 9000 | 710 <- ceil
201 * 10000 | 710
202 * 100000 | 710
203 * 1000000 | 710
204 *
205 */
206static unsigned int hlua_nb_instruction = 10000;
207
Willy Tarreau32f61e22015-03-18 17:54:59 +0100208/* Descriptor for the memory allocation state. If limit is not null, it will
209 * be enforced on any memory allocation.
210 */
211struct hlua_mem_allocator {
212 size_t allocated;
213 size_t limit;
214};
215
216static struct hlua_mem_allocator hlua_global_allocator;
217
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200218static const char error_500[] =
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200219 "HTTP/1.0 500 Internal Server Error\r\n"
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200220 "Cache-Control: no-cache\r\n"
221 "Connection: close\r\n"
222 "Content-Type: text/html\r\n"
223 "\r\n"
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200224 "<html><body><h1>500 Internal Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200225
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100226/* These functions converts types between HAProxy internal args or
227 * sample and LUA types. Another function permits to check if the
228 * LUA stack contains arguments according with an required ARG_T
229 * format.
230 */
231static int hlua_arg2lua(lua_State *L, const struct arg *arg);
232static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100233__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100234 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100235static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100236static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100237static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
238
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200239__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
240
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200241#define SEND_ERR(__be, __fmt, __args...) \
242 do { \
243 send_log(__be, LOG_ERR, __fmt, ## __args); \
244 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
245 Alert(__fmt, ## __args); \
246 } while (0)
247
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100248/* Used to check an Lua function type in the stack. It creates and
249 * returns a reference of the function. This function throws an
250 * error if the rgument is not a "function".
251 */
252__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
253{
254 if (!lua_isfunction(L, argno)) {
255 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
256 WILL_LJMP(luaL_argerror(L, argno, msg));
257 }
258 lua_pushvalue(L, argno);
259 return luaL_ref(L, LUA_REGISTRYINDEX);
260}
261
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200262/* Return the string that is of the top of the stack. */
263const char *hlua_get_top_error_string(lua_State *L)
264{
265 if (lua_gettop(L) < 1)
266 return "unknown error";
267 if (lua_type(L, -1) != LUA_TSTRING)
268 return "unknown error";
269 return lua_tostring(L, -1);
270}
271
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100272/* This function check the number of arguments available in the
273 * stack. If the number of arguments available is not the same
274 * then <nb> an error is throwed.
275 */
276__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
277{
278 if (lua_gettop(L) == nb)
279 return;
280 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
281}
282
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100283/* This fucntion push an error string prefixed by the file name
284 * and the line number where the error is encountered.
285 */
286static int hlua_pusherror(lua_State *L, const char *fmt, ...)
287{
288 va_list argp;
289 va_start(argp, fmt);
290 luaL_where(L, 1);
291 lua_pushvfstring(L, fmt, argp);
292 va_end(argp);
293 lua_concat(L, 2);
294 return 1;
295}
296
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100297/* This function register a new signal. "lua" is the current lua
298 * execution context. It contains a pointer to the associated task.
299 * "link" is a list head attached to an other task that must be wake
300 * the lua task if an event occurs. This is useful with external
301 * events like TCP I/O or sleep functions. This funcion allocate
302 * memory for the signal.
303 */
Thierry FOURNIER847ca662016-12-16 13:07:22 +0100304static struct hlua_com *hlua_com_new(struct list *purge, struct list *event, struct task *wakeup)
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100305{
306 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
307 if (!com)
Thierry FOURNIER847ca662016-12-16 13:07:22 +0100308 return NULL;
309 LIST_ADDQ(purge, &com->purge_me);
310 LIST_ADDQ(event, &com->wake_me);
311 com->task = wakeup;
312 return com;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100313}
314
315/* This function purge all the pending signals when the LUA execution
316 * is finished. This prevent than a coprocess try to wake a deleted
317 * task. This function remove the memory associated to the signal.
318 */
Thierry FOURNIER847ca662016-12-16 13:07:22 +0100319static void hlua_com_purge(struct list *purge)
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100320{
321 struct hlua_com *com, *back;
322
323 /* Delete all pending communication signals. */
Thierry FOURNIER847ca662016-12-16 13:07:22 +0100324 list_for_each_entry_safe(com, back, purge, purge_me) {
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100325 LIST_DEL(&com->purge_me);
326 LIST_DEL(&com->wake_me);
327 pool_free2(pool2_hlua_com, com);
328 }
329}
330
331/* This function sends signals. It wakes all the tasks attached
332 * to a list head, and remove the signal, and free the used
333 * memory.
334 */
335static void hlua_com_wake(struct list *wake)
336{
337 struct hlua_com *com, *back;
338
339 /* Wake task and delete all pending communication signals. */
340 list_for_each_entry_safe(com, back, wake, wake_me) {
341 LIST_DEL(&com->purge_me);
342 LIST_DEL(&com->wake_me);
343 task_wakeup(com->task, TASK_WOKEN_MSG);
344 pool_free2(pool2_hlua_com, com);
345 }
346}
347
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100348/* This functions is used with sample fetch and converters. It
349 * converts the HAProxy configuration argument in a lua stack
350 * values.
351 *
352 * It takes an array of "arg", and each entry of the array is
353 * converted and pushed in the LUA stack.
354 */
355static int hlua_arg2lua(lua_State *L, const struct arg *arg)
356{
357 switch (arg->type) {
358 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100359 case ARGT_TIME:
360 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100361 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100362 break;
363
364 case ARGT_STR:
365 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
366 break;
367
368 case ARGT_IPV4:
369 case ARGT_IPV6:
370 case ARGT_MSK4:
371 case ARGT_MSK6:
372 case ARGT_FE:
373 case ARGT_BE:
374 case ARGT_TAB:
375 case ARGT_SRV:
376 case ARGT_USR:
377 case ARGT_MAP:
378 default:
379 lua_pushnil(L);
380 break;
381 }
382 return 1;
383}
384
385/* This function take one entrie in an LUA stack at the index "ud",
386 * and try to convert it in an HAProxy argument entry. This is useful
387 * with sample fetch wrappers. The input arguments are gived to the
388 * lua wrapper and converted as arg list by thi function.
389 */
390static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
391{
392 switch (lua_type(L, ud)) {
393
394 case LUA_TNUMBER:
395 case LUA_TBOOLEAN:
396 arg->type = ARGT_SINT;
397 arg->data.sint = lua_tointeger(L, ud);
398 break;
399
400 case LUA_TSTRING:
401 arg->type = ARGT_STR;
402 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
403 break;
404
405 case LUA_TUSERDATA:
406 case LUA_TNIL:
407 case LUA_TTABLE:
408 case LUA_TFUNCTION:
409 case LUA_TTHREAD:
410 case LUA_TLIGHTUSERDATA:
411 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200412 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100413 break;
414 }
415 return 1;
416}
417
418/* the following functions are used to convert a struct sample
419 * in Lua type. This useful to convert the return of the
420 * fetchs or converters.
421 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100422static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100423{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200424 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100425 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100426 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200427 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100428 break;
429
430 case SMP_T_BIN:
431 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200432 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100433 break;
434
435 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200436 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100437 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
438 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
439 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
440 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
441 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
442 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
443 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
444 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
445 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200446 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100447 break;
448 default:
449 lua_pushnil(L);
450 break;
451 }
452 break;
453
454 case SMP_T_IPV4:
455 case SMP_T_IPV6:
456 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200457 if (sample_casts[smp->data.type][SMP_T_STR] &&
458 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200459 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100460 else
461 lua_pushnil(L);
462 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100463 default:
464 lua_pushnil(L);
465 break;
466 }
467 return 1;
468}
469
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100470/* the following functions are used to convert a struct sample
471 * in Lua strings. This is useful to convert the return of the
472 * fetchs or converters.
473 */
474static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
475{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200476 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100477
478 case SMP_T_BIN:
479 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200480 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100481 break;
482
483 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200484 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100485 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
486 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
487 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
488 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
489 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
490 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
491 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
492 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
493 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200494 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100495 break;
496 default:
497 lua_pushstring(L, "");
498 break;
499 }
500 break;
501
502 case SMP_T_SINT:
503 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100504 case SMP_T_IPV4:
505 case SMP_T_IPV6:
506 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200507 if (sample_casts[smp->data.type][SMP_T_STR] &&
508 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200509 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100510 else
511 lua_pushstring(L, "");
512 break;
513 default:
514 lua_pushstring(L, "");
515 break;
516 }
517 return 1;
518}
519
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100520/* the following functions are used to convert an Lua type in a
521 * struct sample. This is useful to provide data from a converter
522 * to the LUA code.
523 */
524static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
525{
526 switch (lua_type(L, ud)) {
527
528 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200529 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200530 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100531 break;
532
533
534 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200535 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200536 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100537 break;
538
539 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200540 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100541 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200542 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100543 break;
544
545 case LUA_TUSERDATA:
546 case LUA_TNIL:
547 case LUA_TTABLE:
548 case LUA_TFUNCTION:
549 case LUA_TTHREAD:
550 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200551 case LUA_TNONE:
552 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200553 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200554 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100555 break;
556 }
557 return 1;
558}
559
560/* This function check the "argp" builded by another conversion function
561 * is in accord with the expected argp defined by the "mask". The fucntion
562 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100563 *
564 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
565 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100566 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100567__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100568 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100569{
570 int min_arg;
571 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100572 struct proxy *px;
573 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100574
575 idx = 0;
576 min_arg = ARGM(mask);
577 mask >>= ARGM_BITS;
578
579 while (1) {
580
581 /* Check oversize. */
582 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100583 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100584 }
585
586 /* Check for mandatory arguments. */
587 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100588 if (idx < min_arg) {
589
590 /* If miss other argument than the first one, we return an error. */
591 if (idx > 0)
592 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
593
594 /* If first argument have a certain type, some default values
595 * may be used. See the function smp_resolve_args().
596 */
597 switch (mask & ARGT_MASK) {
598
599 case ARGT_FE:
600 if (!(p->cap & PR_CAP_FE))
601 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
602 argp[idx].data.prx = p;
603 argp[idx].type = ARGT_FE;
604 argp[idx+1].type = ARGT_STOP;
605 break;
606
607 case ARGT_BE:
608 if (!(p->cap & PR_CAP_BE))
609 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
610 argp[idx].data.prx = p;
611 argp[idx].type = ARGT_BE;
612 argp[idx+1].type = ARGT_STOP;
613 break;
614
615 case ARGT_TAB:
616 argp[idx].data.prx = p;
617 argp[idx].type = ARGT_TAB;
618 argp[idx+1].type = ARGT_STOP;
619 break;
620
621 default:
622 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
623 break;
624 }
625 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100626 return 0;
627 }
628
629 /* Check for exceed the number of requiered argument. */
630 if ((mask & ARGT_MASK) == ARGT_STOP &&
631 argp[idx].type != ARGT_STOP) {
632 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
633 }
634
635 if ((mask & ARGT_MASK) == ARGT_STOP &&
636 argp[idx].type == ARGT_STOP) {
637 return 0;
638 }
639
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100640 /* Convert some argument types. */
641 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100642 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100643 if (argp[idx].type != ARGT_SINT)
644 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
645 argp[idx].type = ARGT_SINT;
646 break;
647
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100648 case ARGT_TIME:
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_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100652 break;
653
654 case ARGT_SIZE:
655 if (argp[idx].type != ARGT_SINT)
656 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200657 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100658 break;
659
660 case ARGT_FE:
661 if (argp[idx].type != ARGT_STR)
662 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
663 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
664 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200665 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100666 if (!argp[idx].data.prx)
667 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
668 argp[idx].type = ARGT_FE;
669 break;
670
671 case ARGT_BE:
672 if (argp[idx].type != ARGT_STR)
673 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
674 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
675 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200676 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100677 if (!argp[idx].data.prx)
678 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
679 argp[idx].type = ARGT_BE;
680 break;
681
682 case ARGT_TAB:
683 if (argp[idx].type != ARGT_STR)
684 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
685 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
686 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200687 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100688 if (!argp[idx].data.prx)
689 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
690 argp[idx].type = ARGT_TAB;
691 break;
692
693 case ARGT_SRV:
694 if (argp[idx].type != ARGT_STR)
695 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
696 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
697 trash.str[argp[idx].data.str.len] = 0;
698 sname = strrchr(trash.str, '/');
699 if (sname) {
700 *sname++ = '\0';
701 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200702 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100703 if (!px)
704 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
705 }
706 else {
707 sname = trash.str;
708 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100709 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100710 argp[idx].data.srv = findserver(px, sname);
711 if (!argp[idx].data.srv)
712 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
713 argp[idx].type = ARGT_SRV;
714 break;
715
716 case ARGT_IPV4:
717 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
718 trash.str[argp[idx].data.str.len] = 0;
719 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
720 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
721 argp[idx].type = ARGT_IPV4;
722 break;
723
724 case ARGT_MSK4:
725 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
726 trash.str[argp[idx].data.str.len] = 0;
727 if (!str2mask(trash.str, &argp[idx].data.ipv4))
728 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
729 argp[idx].type = ARGT_MSK4;
730 break;
731
732 case ARGT_IPV6:
733 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
734 trash.str[argp[idx].data.str.len] = 0;
735 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
736 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
737 argp[idx].type = ARGT_IPV6;
738 break;
739
740 case ARGT_MSK6:
741 case ARGT_MAP:
742 case ARGT_REG:
743 case ARGT_USR:
744 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100745 break;
746 }
747
748 /* Check for type of argument. */
749 if ((mask & ARGT_MASK) != argp[idx].type) {
750 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
751 arg_type_names[(mask & ARGT_MASK)],
752 arg_type_names[argp[idx].type & ARGT_MASK]);
753 WILL_LJMP(luaL_argerror(L, first + idx, msg));
754 }
755
756 /* Next argument. */
757 mask >>= ARGT_BITS;
758 idx++;
759 }
760}
761
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100762/*
763 * The following functions are used to make correspondance between the the
764 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100765 *
766 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100767 * - hlua_sethlua : create the association between hlua context and lua_state.
768 */
769static inline struct hlua *hlua_gethlua(lua_State *L)
770{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100771 struct hlua **hlua = lua_getextraspace(L);
772 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100773}
774static inline void hlua_sethlua(struct hlua *hlua)
775{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100776 struct hlua **hlua_store = lua_getextraspace(hlua->T);
777 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100778}
779
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100780/* This function is used to send logs. It try to send on screen (stderr)
781 * and on the default syslog server.
782 */
783static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
784{
785 struct tm tm;
786 char *p;
787
788 /* Cleanup the log message. */
789 p = trash.str;
790 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200791 if (p >= trash.str + trash.size - 1) {
792 /* Break the message if exceed the buffer size. */
793 *(p-4) = ' ';
794 *(p-3) = '.';
795 *(p-2) = '.';
796 *(p-1) = '.';
797 break;
798 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100799 if (isprint(*msg))
800 *p = *msg;
801 else
802 *p = '.';
803 }
804 *p = '\0';
805
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200806 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100807 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200808 get_localtime(date.tv_sec, &tm);
809 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100810 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
811 (int)getpid(), trash.str);
812 fflush(stderr);
813 }
814}
815
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100816/* This function just ensure that the yield will be always
817 * returned with a timeout and permit to set some flags
818 */
819__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100820 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100821{
822 struct hlua *hlua = hlua_gethlua(L);
823
824 /* Set the wake timeout. If timeout is required, we set
825 * the expiration time.
826 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200827 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100828
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100829 hlua->flags |= flags;
830
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100831 /* Process the yield. */
832 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
833}
834
Willy Tarreau87b09662015-04-03 00:22:06 +0200835/* This function initialises the Lua environment stored in the stream.
836 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100837 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200838 *
839 * This function is particular. it initialises a new Lua thread. If the
840 * initialisation fails (example: out of memory error), the lua function
841 * throws an error (longjmp).
842 *
843 * This function manipulates two Lua stack: the main and the thread. Only
844 * the main stack can fail. The thread is not manipulated. This function
845 * MUST NOT manipulate the created thread stack state, because is not
846 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100847 */
848int hlua_ctx_init(struct hlua *lua, struct task *task)
849{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200850 if (!SET_SAFE_LJMP(gL.T)) {
851 lua->Tref = LUA_REFNIL;
852 return 0;
853 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100854 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100855 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100856 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100857 lua->T = lua_newthread(gL.T);
858 if (!lua->T) {
859 lua->Tref = LUA_REFNIL;
Thierry FOURNIER0a976202017-07-12 11:18:00 +0200860 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100861 return 0;
862 }
863 hlua_sethlua(lua);
864 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
865 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200866 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100867 return 1;
868}
869
Willy Tarreau87b09662015-04-03 00:22:06 +0200870/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100871 * is destroyed. The destroy also the memory context. The struct "lua"
872 * is not freed.
873 */
874void hlua_ctx_destroy(struct hlua *lua)
875{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100876 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100877 return;
878
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100879 if (!lua->T)
880 goto end;
881
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100882 /* Purge all the pending signals. */
Thierry FOURNIER847ca662016-12-16 13:07:22 +0100883 hlua_com_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100884
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200885 if (!SET_SAFE_LJMP(lua->T))
886 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100887 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200888 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200889
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200890 if (!SET_SAFE_LJMP(gL.T))
891 return;
892 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
893 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200894 /* Forces a garbage collecting process. If the Lua program is finished
895 * without error, we run the GC on the thread pointer. Its freed all
896 * the unused memory.
897 * If the thread is finnish with an error or is currently yielded,
898 * it seems that the GC applied on the thread doesn't clean anything,
899 * so e run the GC on the main thread.
900 * NOTE: maybe this action locks all the Lua threads untiml the en of
901 * the garbage collection.
902 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200903 if (lua->flags & HLUA_MUST_GC) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200904 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200905 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200906 lua_gc(gL.T, LUA_GCCOLLECT, 0);
907 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200908 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200909
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200910 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100911
912end:
913 pool_free2(pool2_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100914}
915
916/* This function is used to restore the Lua context when a coroutine
917 * fails. This function copy the common memory between old coroutine
918 * and the new coroutine. The old coroutine is destroyed, and its
919 * replaced by the new coroutine.
920 * If the flag "keep_msg" is set, the last entry of the old is assumed
921 * as string error message and it is copied in the new stack.
922 */
923static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
924{
925 lua_State *T;
926 int new_ref;
927
928 /* Renew the main LUA stack doesn't have sense. */
929 if (lua == &gL)
930 return 0;
931
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100932 /* New Lua coroutine. */
933 T = lua_newthread(gL.T);
934 if (!T)
935 return 0;
936
937 /* Copy last error message. */
938 if (keep_msg)
939 lua_xmove(lua->T, T, 1);
940
941 /* Copy data between the coroutines. */
942 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
943 lua_xmove(lua->T, T, 1);
944 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
945
946 /* Destroy old data. */
947 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
948
949 /* The thread is garbage collected by Lua. */
950 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
951
952 /* Fill the struct with the new coroutine values. */
953 lua->Mref = new_ref;
954 lua->T = T;
955 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
956
957 /* Set context. */
958 hlua_sethlua(lua);
959
960 return 1;
961}
962
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100963void hlua_hook(lua_State *L, lua_Debug *ar)
964{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100965 struct hlua *hlua = hlua_gethlua(L);
966
967 /* Lua cannot yield when its returning from a function,
968 * so, we can fix the interrupt hook to 1 instruction,
969 * expecting that the function is finnished.
970 */
971 if (lua_gethookmask(L) & LUA_MASKRET) {
972 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
973 return;
974 }
975
976 /* restore the interrupt condition. */
977 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
978
979 /* If we interrupt the Lua processing in yieldable state, we yield.
980 * If the state is not yieldable, trying yield causes an error.
981 */
982 if (lua_isyieldable(L))
983 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
984
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100985 /* If we cannot yield, update the clock and check the timeout. */
986 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200987 hlua->run_time += now_ms - hlua->start_time;
988 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100989 lua_pushfstring(L, "execution timeout");
990 WILL_LJMP(lua_error(L));
991 }
992
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200993 /* Update the start time. */
994 hlua->start_time = now_ms;
995
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100996 /* Try to interrupt the process at the end of the current
997 * unyieldable function.
998 */
999 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001000}
1001
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001002/* This function start or resumes the Lua stack execution. If the flag
1003 * "yield_allowed" if no set and the LUA stack execution returns a yield
1004 * The function return an error.
1005 *
1006 * The function can returns 4 values:
1007 * - HLUA_E_OK : The execution is terminated without any errors.
1008 * - HLUA_E_AGAIN : The execution must continue at the next associated
1009 * task wakeup.
1010 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
1011 * the top of the stack.
1012 * - HLUA_E_ERR : An error has occured without error message.
1013 *
1014 * If an error occured, the stack is renewed and it is ready to run new
1015 * LUA code.
1016 */
1017static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1018{
1019 int ret;
1020 const char *msg;
1021
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001022 /* Initialise run time counter. */
1023 if (!HLUA_IS_RUNNING(lua))
1024 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001025
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001026resume_execution:
1027
1028 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1029 * instructions. it is used for preventing infinite loops.
1030 */
1031 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1032
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001033 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001034 HLUA_SET_RUN(lua);
1035 HLUA_CLR_CTRLYIELD(lua);
1036 HLUA_CLR_WAKERESWR(lua);
1037 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001038
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001039 /* Update the start time. */
1040 lua->start_time = now_ms;
1041
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001042 /* Call the function. */
1043 ret = lua_resume(lua->T, gL.T, lua->nargs);
1044 switch (ret) {
1045
1046 case LUA_OK:
1047 ret = HLUA_E_OK;
1048 break;
1049
1050 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001051 /* Check if the execution timeout is expired. It it is the case, we
1052 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001053 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001054 tv_update_date(0, 1);
1055 lua->run_time += now_ms - lua->start_time;
1056 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001057 lua_settop(lua->T, 0); /* Empty the stack. */
1058 if (!lua_checkstack(lua->T, 1)) {
1059 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001060 break;
1061 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001062 lua_pushfstring(lua->T, "execution timeout");
1063 ret = HLUA_E_ERRMSG;
1064 break;
1065 }
1066 /* Process the forced yield. if the general yield is not allowed or
1067 * if no task were associated this the current Lua execution
1068 * coroutine, we resume the execution. Else we want to return in the
1069 * scheduler and we want to be waked up again, to continue the
1070 * current Lua execution. So we schedule our own task.
1071 */
1072 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001073 if (!yield_allowed || !lua->task)
1074 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001075 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001076 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001077 if (!yield_allowed) {
1078 lua_settop(lua->T, 0); /* Empty the stack. */
1079 if (!lua_checkstack(lua->T, 1)) {
1080 ret = HLUA_E_ERR;
1081 break;
1082 }
1083 lua_pushfstring(lua->T, "yield not allowed");
1084 ret = HLUA_E_ERRMSG;
1085 break;
1086 }
1087 ret = HLUA_E_AGAIN;
1088 break;
1089
1090 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001091
1092 /* Special exit case. The traditionnal exit is returned as an error
1093 * because the errors ares the only one mean to return immediately
1094 * from and lua execution.
1095 */
1096 if (lua->flags & HLUA_EXIT) {
1097 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001098 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001099 break;
1100 }
1101
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001102 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001103 if (!lua_checkstack(lua->T, 1)) {
1104 ret = HLUA_E_ERR;
1105 break;
1106 }
1107 msg = lua_tostring(lua->T, -1);
1108 lua_settop(lua->T, 0); /* Empty the stack. */
1109 lua_pop(lua->T, 1);
1110 if (msg)
1111 lua_pushfstring(lua->T, "runtime error: %s", msg);
1112 else
1113 lua_pushfstring(lua->T, "unknown runtime error");
1114 ret = HLUA_E_ERRMSG;
1115 break;
1116
1117 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001118 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001119 lua_settop(lua->T, 0); /* Empty the stack. */
1120 if (!lua_checkstack(lua->T, 1)) {
1121 ret = HLUA_E_ERR;
1122 break;
1123 }
1124 lua_pushfstring(lua->T, "out of memory error");
1125 ret = HLUA_E_ERRMSG;
1126 break;
1127
1128 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001129 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001130 if (!lua_checkstack(lua->T, 1)) {
1131 ret = HLUA_E_ERR;
1132 break;
1133 }
1134 msg = lua_tostring(lua->T, -1);
1135 lua_settop(lua->T, 0); /* Empty the stack. */
1136 lua_pop(lua->T, 1);
1137 if (msg)
1138 lua_pushfstring(lua->T, "message handler error: %s", msg);
1139 else
1140 lua_pushfstring(lua->T, "message handler error");
1141 ret = HLUA_E_ERRMSG;
1142 break;
1143
1144 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001145 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001146 lua_settop(lua->T, 0); /* Empty the stack. */
1147 if (!lua_checkstack(lua->T, 1)) {
1148 ret = HLUA_E_ERR;
1149 break;
1150 }
1151 lua_pushfstring(lua->T, "unknonwn error");
1152 ret = HLUA_E_ERRMSG;
1153 break;
1154 }
1155
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001156 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001157 if (lua->flags & HLUA_MUST_GC &&
1158 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001159 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1160
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001161 switch (ret) {
1162 case HLUA_E_AGAIN:
1163 break;
1164
1165 case HLUA_E_ERRMSG:
Thierry FOURNIER847ca662016-12-16 13:07:22 +01001166 hlua_com_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001167 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001168 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001169 break;
1170
1171 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001172 HLUA_CLR_RUN(lua);
Thierry FOURNIER847ca662016-12-16 13:07:22 +01001173 hlua_com_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001174 hlua_ctx_renew(lua, 0);
1175 break;
1176
1177 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001178 HLUA_CLR_RUN(lua);
Thierry FOURNIER847ca662016-12-16 13:07:22 +01001179 hlua_com_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001180 break;
1181 }
1182
1183 return ret;
1184}
1185
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001186/* This function exit the current code. */
1187__LJMP static int hlua_done(lua_State *L)
1188{
1189 struct hlua *hlua = hlua_gethlua(L);
1190
1191 hlua->flags |= HLUA_EXIT;
1192 WILL_LJMP(lua_error(L));
1193
1194 return 0;
1195}
1196
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001197/* This function is an LUA binding. It provides a function
1198 * for deleting ACL from a referenced ACL file.
1199 */
1200__LJMP static int hlua_del_acl(lua_State *L)
1201{
1202 const char *name;
1203 const char *key;
1204 struct pat_ref *ref;
1205
1206 MAY_LJMP(check_args(L, 2, "del_acl"));
1207
1208 name = MAY_LJMP(luaL_checkstring(L, 1));
1209 key = MAY_LJMP(luaL_checkstring(L, 2));
1210
1211 ref = pat_ref_lookup(name);
1212 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001213 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001214
1215 pat_ref_delete(ref, key);
1216 return 0;
1217}
1218
1219/* This function is an LUA binding. It provides a function
1220 * for deleting map entry from a referenced map file.
1221 */
1222static int hlua_del_map(lua_State *L)
1223{
1224 const char *name;
1225 const char *key;
1226 struct pat_ref *ref;
1227
1228 MAY_LJMP(check_args(L, 2, "del_map"));
1229
1230 name = MAY_LJMP(luaL_checkstring(L, 1));
1231 key = MAY_LJMP(luaL_checkstring(L, 2));
1232
1233 ref = pat_ref_lookup(name);
1234 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001235 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001236
1237 pat_ref_delete(ref, key);
1238 return 0;
1239}
1240
1241/* This function is an LUA binding. It provides a function
1242 * for adding ACL pattern from a referenced ACL file.
1243 */
1244static int hlua_add_acl(lua_State *L)
1245{
1246 const char *name;
1247 const char *key;
1248 struct pat_ref *ref;
1249
1250 MAY_LJMP(check_args(L, 2, "add_acl"));
1251
1252 name = MAY_LJMP(luaL_checkstring(L, 1));
1253 key = MAY_LJMP(luaL_checkstring(L, 2));
1254
1255 ref = pat_ref_lookup(name);
1256 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001257 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001258
1259 if (pat_ref_find_elt(ref, key) == NULL)
1260 pat_ref_add(ref, key, NULL, NULL);
1261 return 0;
1262}
1263
1264/* This function is an LUA binding. It provides a function
1265 * for setting map pattern and sample from a referenced map
1266 * file.
1267 */
1268static int hlua_set_map(lua_State *L)
1269{
1270 const char *name;
1271 const char *key;
1272 const char *value;
1273 struct pat_ref *ref;
1274
1275 MAY_LJMP(check_args(L, 3, "set_map"));
1276
1277 name = MAY_LJMP(luaL_checkstring(L, 1));
1278 key = MAY_LJMP(luaL_checkstring(L, 2));
1279 value = MAY_LJMP(luaL_checkstring(L, 3));
1280
1281 ref = pat_ref_lookup(name);
1282 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001283 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001284
1285 if (pat_ref_find_elt(ref, key) != NULL)
1286 pat_ref_set(ref, key, value, NULL);
1287 else
1288 pat_ref_add(ref, key, value, NULL);
1289 return 0;
1290}
1291
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001292/* A class is a lot of memory that contain data. This data can be a table,
1293 * an integer or user data. This data is associated with a metatable. This
1294 * metatable have an original version registred in the global context with
1295 * the name of the object (_G[<name>] = <metable> ).
1296 *
1297 * A metable is a table that modify the standard behavior of a standard
1298 * access to the associated data. The entries of this new metatable are
1299 * defined as is:
1300 *
1301 * http://lua-users.org/wiki/MetatableEvents
1302 *
1303 * __index
1304 *
1305 * we access an absent field in a table, the result is nil. This is
1306 * true, but it is not the whole truth. Actually, such access triggers
1307 * the interpreter to look for an __index metamethod: If there is no
1308 * such method, as usually happens, then the access results in nil;
1309 * otherwise, the metamethod will provide the result.
1310 *
1311 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1312 * the key does not appear in the table, but the metatable has an __index
1313 * property:
1314 *
1315 * - if the value is a function, the function is called, passing in the
1316 * table and the key; the return value of that function is returned as
1317 * the result.
1318 *
1319 * - if the value is another table, the value of the key in that table is
1320 * asked for and returned (and if it doesn't exist in that table, but that
1321 * table's metatable has an __index property, then it continues on up)
1322 *
1323 * - Use "rawget(myTable,key)" to skip this metamethod.
1324 *
1325 * http://www.lua.org/pil/13.4.1.html
1326 *
1327 * __newindex
1328 *
1329 * Like __index, but control property assignment.
1330 *
1331 * __mode - Control weak references. A string value with one or both
1332 * of the characters 'k' and 'v' which specifies that the the
1333 * keys and/or values in the table are weak references.
1334 *
1335 * __call - Treat a table like a function. When a table is followed by
1336 * parenthesis such as "myTable( 'foo' )" and the metatable has
1337 * a __call key pointing to a function, that function is invoked
1338 * (passing any specified arguments) and the return value is
1339 * returned.
1340 *
1341 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1342 * called, if the metatable for myTable has a __metatable
1343 * key, the value of that key is returned instead of the
1344 * actual metatable.
1345 *
1346 * __tostring - Control string representation. When the builtin
1347 * "tostring( myTable )" function is called, if the metatable
1348 * for myTable has a __tostring property set to a function,
1349 * that function is invoked (passing myTable to it) and the
1350 * return value is used as the string representation.
1351 *
1352 * __len - Control table length. When the table length is requested using
1353 * the length operator ( '#' ), if the metatable for myTable has
1354 * a __len key pointing to a function, that function is invoked
1355 * (passing myTable to it) and the return value used as the value
1356 * of "#myTable".
1357 *
1358 * __gc - Userdata finalizer code. When userdata is set to be garbage
1359 * collected, if the metatable has a __gc field pointing to a
1360 * function, that function is first invoked, passing the userdata
1361 * to it. The __gc metamethod is not called for tables.
1362 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1363 *
1364 * Special metamethods for redefining standard operators:
1365 * http://www.lua.org/pil/13.1.html
1366 *
1367 * __add "+"
1368 * __sub "-"
1369 * __mul "*"
1370 * __div "/"
1371 * __unm "!"
1372 * __pow "^"
1373 * __concat ".."
1374 *
1375 * Special methods for redfining standar relations
1376 * http://www.lua.org/pil/13.2.html
1377 *
1378 * __eq "=="
1379 * __lt "<"
1380 * __le "<="
1381 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001382
1383/*
1384 *
1385 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001386 * Class Map
1387 *
1388 *
1389 */
1390
1391/* Returns a struct hlua_map if the stack entry "ud" is
1392 * a class session, otherwise it throws an error.
1393 */
1394__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1395{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001396 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001397}
1398
1399/* This function is the map constructor. It don't need
1400 * the class Map object. It creates and return a new Map
1401 * object. It must be called only during "body" or "init"
1402 * context because it process some filesystem accesses.
1403 */
1404__LJMP static int hlua_map_new(struct lua_State *L)
1405{
1406 const char *fn;
1407 int match = PAT_MATCH_STR;
1408 struct sample_conv conv;
1409 const char *file = "";
1410 int line = 0;
1411 lua_Debug ar;
1412 char *err = NULL;
1413 struct arg args[2];
1414
1415 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1416 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1417
1418 fn = MAY_LJMP(luaL_checkstring(L, 1));
1419
1420 if (lua_gettop(L) >= 2) {
1421 match = MAY_LJMP(luaL_checkinteger(L, 2));
1422 if (match < 0 || match >= PAT_MATCH_NUM)
1423 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1424 }
1425
1426 /* Get Lua filename and line number. */
1427 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1428 lua_getinfo(L, "Sl", &ar); /* get info about it */
1429 if (ar.currentline > 0) { /* is there info? */
1430 file = ar.short_src;
1431 line = ar.currentline;
1432 }
1433 }
1434
1435 /* fill fake sample_conv struct. */
1436 conv.kw = ""; /* unused. */
1437 conv.process = NULL; /* unused. */
1438 conv.arg_mask = 0; /* unused. */
1439 conv.val_args = NULL; /* unused. */
1440 conv.out_type = SMP_T_STR;
1441 conv.private = (void *)(long)match;
1442 switch (match) {
1443 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1444 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1445 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1446 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1447 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1448 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1449 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001450 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001451 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1452 default:
1453 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1454 }
1455
1456 /* fill fake args. */
1457 args[0].type = ARGT_STR;
1458 args[0].data.str.str = (char *)fn;
1459 args[1].type = ARGT_STOP;
1460
1461 /* load the map. */
1462 if (!sample_load_map(args, &conv, file, line, &err)) {
1463 /* error case: we cant use luaL_error because we must
1464 * free the err variable.
1465 */
1466 luaL_where(L, 1);
1467 lua_pushfstring(L, "'new': %s.", err);
1468 lua_concat(L, 2);
1469 free(err);
1470 WILL_LJMP(lua_error(L));
1471 }
1472
1473 /* create the lua object. */
1474 lua_newtable(L);
1475 lua_pushlightuserdata(L, args[0].data.map);
1476 lua_rawseti(L, -2, 0);
1477
1478 /* Pop a class Map metatable and affect it to the userdata. */
1479 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1480 lua_setmetatable(L, -2);
1481
1482
1483 return 1;
1484}
1485
1486__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1487{
1488 struct map_descriptor *desc;
1489 struct pattern *pat;
1490 struct sample smp;
1491
1492 MAY_LJMP(check_args(L, 2, "lookup"));
1493 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001494 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001495 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001496 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001497 }
1498 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001499 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001500 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001501 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 +02001502 }
1503
1504 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001505 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001506 if (str)
1507 lua_pushstring(L, "");
1508 else
1509 lua_pushnil(L);
1510 return 1;
1511 }
1512
1513 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001514 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001515 return 1;
1516}
1517
1518__LJMP static int hlua_map_lookup(struct lua_State *L)
1519{
1520 return _hlua_map_lookup(L, 0);
1521}
1522
1523__LJMP static int hlua_map_slookup(struct lua_State *L)
1524{
1525 return _hlua_map_lookup(L, 1);
1526}
1527
1528/*
1529 *
1530 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001531 * Class Socket
1532 *
1533 *
1534 */
1535
1536__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1537{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001538 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001539}
1540
1541/* This function is the handler called for each I/O on the established
1542 * connection. It is used for notify space avalaible to send or data
1543 * received.
1544 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001545static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001546{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001547 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001548 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001549
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001550 if (appctx->ctx.hlua_cosocket.die) {
1551 si_shutw(si);
1552 si_shutr(si);
1553 si_ic(si)->flags |= CF_READ_NULL;
1554 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1555 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
1556 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1557 }
1558
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001559 /* If the connection object is not avalaible, close all the
1560 * streams and wakeup everithing waiting for.
1561 */
1562 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001563 si_shutw(si);
1564 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001565 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001566 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1567 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001568 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001569 }
1570
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001571 /* If we cant write, wakeup the pending write signals. */
1572 if (channel_output_closed(si_ic(si)))
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001573 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001574
1575 /* If we cant read, wakeup the pending read signals. */
1576 if (channel_input_closed(si_oc(si)))
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001577 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001578
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001579 /* if the connection is not estabkished, inform the stream that we want
1580 * to be notified whenever the connection completes.
1581 */
1582 if (!(c->flags & CO_FL_CONNECTED)) {
1583 si_applet_cant_get(si);
1584 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001585 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001586 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001587
1588 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001589 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001590
1591 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001592 if (channel_may_recv(si_ic(si)))
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001593 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001594
1595 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001596 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001597 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001598}
1599
Willy Tarreau87b09662015-04-03 00:22:06 +02001600/* This function is called when the "struct stream" is destroyed.
1601 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001602 * Wake all the pending signals.
1603 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001604static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001605{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001606 /* Remove my link in the original object. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001607 if (appctx->ctx.hlua_cosocket.socket)
1608 appctx->ctx.hlua_cosocket.socket->s = NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001609
1610 /* Wake all the task waiting for me. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001611 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1612 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001613}
1614
1615/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001616 * uses this object. If the stream does not exists, just quit.
1617 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001618 * pending signal can rest in the read and write lists. destroy
1619 * it.
1620 */
1621__LJMP static int hlua_socket_gc(lua_State *L)
1622{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001623 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001624 struct appctx *appctx;
1625
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001626 MAY_LJMP(check_args(L, 1, "__gc"));
1627
1628 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001629 if (!socket->s)
1630 return 0;
1631
Willy Tarreau87b09662015-04-03 00:22:06 +02001632 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001633 appctx = objt_appctx(socket->s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001634 socket->s = NULL;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001635 appctx->ctx.hlua_cosocket.socket = NULL;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001636 appctx->ctx.hlua_cosocket.die = 1;
1637 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001638
1639 return 0;
1640}
1641
1642/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001643 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001644 */
1645__LJMP static int hlua_socket_close(lua_State *L)
1646{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001647 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001648 struct appctx *appctx;
1649
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001650 MAY_LJMP(check_args(L, 1, "close"));
1651
1652 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001653 if (!socket->s)
1654 return 0;
1655
Willy Tarreau87b09662015-04-03 00:22:06 +02001656 /* Close the stream and remove the associated stop task. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001657 appctx = objt_appctx(socket->s->si[0].end);
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001658 appctx->ctx.hlua_cosocket.socket = NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001659 socket->s = NULL;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001660 appctx->ctx.hlua_cosocket.die = 1;
1661 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001662
1663 return 0;
1664}
1665
1666/* This Lua function assumes that the stack contain three parameters.
1667 * 1 - USERDATA containing a struct socket
1668 * 2 - INTEGER with values of the macro defined below
1669 * If the integer is -1, we must read at most one line.
1670 * If the integer is -2, we ust read all the data until the
1671 * end of the stream.
1672 * If the integer is positive value, we must read a number of
1673 * bytes corresponding to this value.
1674 */
1675#define HLSR_READ_LINE (-1)
1676#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001677__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001678{
1679 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1680 int wanted = lua_tointeger(L, 2);
1681 struct hlua *hlua = hlua_gethlua(L);
1682 struct appctx *appctx;
1683 int len;
1684 int nblk;
1685 char *blk1;
1686 int len1;
1687 char *blk2;
1688 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001689 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001690 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001691
1692 /* Check if this lua stack is schedulable. */
1693 if (!hlua || !hlua->task)
1694 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1695 "'frontend', 'backend' or 'task'"));
1696
1697 /* check for connection closed. If some data where read, return it. */
1698 if (!socket->s)
1699 goto connection_closed;
1700
Willy Tarreau94aa6172015-03-13 14:19:06 +01001701 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001702 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001703 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001704 nblk = bo_getline_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;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001709
1710 /* remove final \r\n. */
1711 if (nblk == 1) {
1712 if (blk1[len1-1] == '\n') {
1713 len1--;
1714 skip_at_end++;
1715 if (blk1[len1-1] == '\r') {
1716 len1--;
1717 skip_at_end++;
1718 }
1719 }
1720 }
1721 else {
1722 if (blk2[len2-1] == '\n') {
1723 len2--;
1724 skip_at_end++;
1725 if (blk2[len2-1] == '\r') {
1726 len2--;
1727 skip_at_end++;
1728 }
1729 }
1730 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001731 }
1732
1733 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001734 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001735 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001736 if (nblk < 0) /* Connection close. */
1737 goto connection_closed;
1738 if (nblk == 0) /* No data avalaible. */
1739 goto connection_empty;
1740 }
1741
1742 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001743 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001744 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001745 if (nblk < 0) /* Connection close. */
1746 goto connection_closed;
1747 if (nblk == 0) /* No data avalaible. */
1748 goto connection_empty;
1749
1750 if (len1 > wanted) {
1751 nblk = 1;
1752 len1 = wanted;
1753 } if (nblk == 2 && len1 + len2 > wanted)
1754 len2 = wanted - len1;
1755 }
1756
1757 len = len1;
1758
1759 luaL_addlstring(&socket->b, blk1, len1);
1760 if (nblk == 2) {
1761 len += len2;
1762 luaL_addlstring(&socket->b, blk2, len2);
1763 }
1764
1765 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001766 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001767
1768 /* Don't wait anything. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001769 stream_int_notify(&socket->s->si[0]);
1770 stream_int_update_applet(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001771
1772 /* If the pattern reclaim to read all the data
1773 * in the connection, got out.
1774 */
1775 if (wanted == HLSR_READ_ALL)
1776 goto connection_empty;
1777 else if (wanted >= 0 && len < wanted)
1778 goto connection_empty;
1779
1780 /* Return result. */
1781 luaL_pushresult(&socket->b);
1782 return 1;
1783
1784connection_closed:
1785
1786 /* If the buffer containds data. */
1787 if (socket->b.n > 0) {
1788 luaL_pushresult(&socket->b);
1789 return 1;
1790 }
1791 lua_pushnil(L);
1792 lua_pushstring(L, "connection closed.");
1793 return 2;
1794
1795connection_empty:
1796
1797 appctx = objt_appctx(socket->s->si[0].end);
Thierry FOURNIER847ca662016-12-16 13:07:22 +01001798 if (!hlua_com_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001799 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001800 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001801 return 0;
1802}
1803
1804/* This Lus function gets two parameters. The first one can be string
1805 * or a number. If the string is "*l", the user require one line. If
1806 * the string is "*a", the user require all the content of the stream.
1807 * If the value is a number, the user require a number of bytes equal
1808 * to the value. The default value is "*l" (a line).
1809 *
1810 * This paraeter with a variable type is converted in integer. This
1811 * integer takes this values:
1812 * -1 : read a line
1813 * -2 : read all the stream
1814 * >0 : amount if bytes.
1815 *
1816 * The second parameter is optinal. It contains a string that must be
1817 * concatenated with the read data.
1818 */
1819__LJMP static int hlua_socket_receive(struct lua_State *L)
1820{
1821 int wanted = HLSR_READ_LINE;
1822 const char *pattern;
1823 int type;
1824 char *error;
1825 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001826 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001827
1828 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1829 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1830
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001831 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001832
1833 /* check for pattern. */
1834 if (lua_gettop(L) >= 2) {
1835 type = lua_type(L, 2);
1836 if (type == LUA_TSTRING) {
1837 pattern = lua_tostring(L, 2);
1838 if (strcmp(pattern, "*a") == 0)
1839 wanted = HLSR_READ_ALL;
1840 else if (strcmp(pattern, "*l") == 0)
1841 wanted = HLSR_READ_LINE;
1842 else {
1843 wanted = strtoll(pattern, &error, 10);
1844 if (*error != '\0')
1845 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1846 }
1847 }
1848 else if (type == LUA_TNUMBER) {
1849 wanted = lua_tointeger(L, 2);
1850 if (wanted < 0)
1851 WILL_LJMP(luaL_error(L, "Unsupported size."));
1852 }
1853 }
1854
1855 /* Set pattern. */
1856 lua_pushinteger(L, wanted);
1857 lua_replace(L, 2);
1858
1859 /* init bufffer, and fiil it wih prefix. */
1860 luaL_buffinit(L, &socket->b);
1861
1862 /* Check prefix. */
1863 if (lua_gettop(L) >= 3) {
1864 if (lua_type(L, 3) != LUA_TSTRING)
1865 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1866 pattern = lua_tolstring(L, 3, &len);
1867 luaL_addlstring(&socket->b, pattern, len);
1868 }
1869
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001870 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001871}
1872
1873/* Write the Lua input string in the output buffer.
1874 * This fucntion returns a yield if no space are available.
1875 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001876static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001877{
1878 struct hlua_socket *socket;
1879 struct hlua *hlua = hlua_gethlua(L);
1880 struct appctx *appctx;
1881 size_t buf_len;
1882 const char *buf;
1883 int len;
1884 int send_len;
1885 int sent;
1886
1887 /* Check if this lua stack is schedulable. */
1888 if (!hlua || !hlua->task)
1889 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1890 "'frontend', 'backend' or 'task'"));
1891
1892 /* Get object */
1893 socket = MAY_LJMP(hlua_checksocket(L, 1));
1894 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001895 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001896
1897 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001898 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001899 lua_pushinteger(L, -1);
1900 return 1;
1901 }
1902
1903 /* Update the input buffer data. */
1904 buf += sent;
1905 send_len = buf_len - sent;
1906
1907 /* All the data are sent. */
1908 if (sent >= buf_len)
1909 return 1; /* Implicitly return the length sent. */
1910
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001911 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1912 * the request buffer if its not required.
1913 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001914 if (socket->s->req.buf->size == 0) {
Christopher Faulet33834b12016-12-19 09:29:06 +01001915 appctx = hlua->task->context;
1916 if (!channel_alloc_buffer(&socket->s->req, &appctx->buffer_wait))
1917 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001918 }
1919
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001920 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001921 len = buffer_total_space(socket->s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01001922 if (len <= 0) {
1923 appctx = objt_appctx(socket->s->si[0].end);
1924 if (!hlua_com_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task))
1925 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001926 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01001927 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001928
1929 /* send data */
1930 if (len < send_len)
1931 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001932 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001933
1934 /* "Not enough space" (-1), "Buffer too little to contain
1935 * the data" (-2) are not expected because the available length
1936 * is tested.
1937 * Other unknown error are also not expected.
1938 */
1939 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001940 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001941 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001942
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001943 MAY_LJMP(hlua_socket_close(L));
1944 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001945 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001946 return 1;
1947 }
1948
1949 /* update buffers. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001950 stream_int_notify(&socket->s->si[0]);
1951 stream_int_update_applet(&socket->s->si[0]);
1952
Willy Tarreau94aa6172015-03-13 14:19:06 +01001953 socket->s->req.rex = TICK_ETERNITY;
1954 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001955
1956 /* Update length sent. */
1957 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001958 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001959
1960 /* All the data buffer is sent ? */
1961 if (sent + len >= buf_len)
1962 return 1;
1963
1964hlua_socket_write_yield_return:
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001965 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001966 return 0;
1967}
1968
1969/* This function initiate the send of data. It just check the input
1970 * parameters and push an integer in the Lua stack that contain the
1971 * amount of data writed in the buffer. This is used by the function
1972 * "hlua_socket_write_yield" that can yield.
1973 *
1974 * The Lua function gets between 3 and 4 parameters. The first one is
1975 * the associated object. The second is a string buffer. The third is
1976 * a facultative integer that represents where is the buffer position
1977 * of the start of the data that can send. The first byte is the
1978 * position "1". The default value is "1". The fourth argument is a
1979 * facultative integer that represents where is the buffer position
1980 * of the end of the data that can send. The default is the last byte.
1981 */
1982static int hlua_socket_send(struct lua_State *L)
1983{
1984 int i;
1985 int j;
1986 const char *buf;
1987 size_t buf_len;
1988
1989 /* Check number of arguments. */
1990 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1991 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1992
1993 /* Get the string. */
1994 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1995
1996 /* Get and check j. */
1997 if (lua_gettop(L) == 4) {
1998 j = MAY_LJMP(luaL_checkinteger(L, 4));
1999 if (j < 0)
2000 j = buf_len + j + 1;
2001 if (j > buf_len)
2002 j = buf_len + 1;
2003 lua_pop(L, 1);
2004 }
2005 else
2006 j = buf_len;
2007
2008 /* Get and check i. */
2009 if (lua_gettop(L) == 3) {
2010 i = MAY_LJMP(luaL_checkinteger(L, 3));
2011 if (i < 0)
2012 i = buf_len + i + 1;
2013 if (i > buf_len)
2014 i = buf_len + 1;
2015 lua_pop(L, 1);
2016 } else
2017 i = 1;
2018
2019 /* Check bth i and j. */
2020 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002021 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002022 return 1;
2023 }
2024 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002025 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002026 return 1;
2027 }
2028 if (i == 0)
2029 i = 1;
2030 if (j == 0)
2031 j = 1;
2032
2033 /* Pop the string. */
2034 lua_pop(L, 1);
2035
2036 /* Update the buffer length. */
2037 buf += i - 1;
2038 buf_len = j - i + 1;
2039 lua_pushlstring(L, buf, buf_len);
2040
2041 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002042 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002043
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002044 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002045}
2046
Willy Tarreau22b0a682015-06-17 19:43:49 +02002047#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002048__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2049{
2050 static char buffer[SOCKET_INFO_MAX_LEN];
2051 int ret;
2052 int len;
2053 char *p;
2054
2055 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2056 if (ret <= 0) {
2057 lua_pushnil(L);
2058 return 1;
2059 }
2060
2061 if (ret == AF_UNIX) {
2062 lua_pushstring(L, buffer+1);
2063 return 1;
2064 }
2065 else if (ret == AF_INET6) {
2066 buffer[0] = '[';
2067 len = strlen(buffer);
2068 buffer[len] = ']';
2069 len++;
2070 buffer[len] = ':';
2071 len++;
2072 p = buffer;
2073 }
2074 else if (ret == AF_INET) {
2075 p = buffer + 1;
2076 len = strlen(p);
2077 p[len] = ':';
2078 len++;
2079 }
2080 else {
2081 lua_pushnil(L);
2082 return 1;
2083 }
2084
2085 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2086 lua_pushnil(L);
2087 return 1;
2088 }
2089
2090 lua_pushstring(L, p);
2091 return 1;
2092}
2093
2094/* Returns information about the peer of the connection. */
2095__LJMP static int hlua_socket_getpeername(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, "getpeername"));
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_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002117 if (!(conn->flags & CO_FL_ADDR_TO_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 MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2123}
2124
2125/* Returns information about my connection side. */
2126static int hlua_socket_getsockname(struct lua_State *L)
2127{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002128 struct hlua_socket *socket;
2129 struct connection *conn;
2130
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002131 MAY_LJMP(check_args(L, 1, "getsockname"));
2132
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002133 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002134
2135 /* Check if the tcp object is avalaible. */
2136 if (!socket->s) {
2137 lua_pushnil(L);
2138 return 1;
2139 }
2140
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002141 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002142 if (!conn) {
2143 lua_pushnil(L);
2144 return 1;
2145 }
2146
Willy Tarreaua71f6422016-11-16 17:00:14 +01002147 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002148 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Willy Tarreaua71f6422016-11-16 17:00:14 +01002149 lua_pushnil(L);
2150 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002151 }
2152
2153 return hlua_socket_info(L, &conn->addr.from);
2154}
2155
2156/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002157static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002158 .obj_type = OBJ_TYPE_APPLET,
2159 .name = "<LUA_TCP>",
2160 .fct = hlua_socket_handler,
2161 .release = hlua_socket_release,
2162};
2163
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002164__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002165{
2166 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2167 struct hlua *hlua = hlua_gethlua(L);
2168 struct appctx *appctx;
2169
2170 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002171 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002172 lua_pushnil(L);
2173 lua_pushstring(L, "Can't connect");
2174 return 2;
2175 }
2176
2177 appctx = objt_appctx(socket->s->si[0].end);
2178
2179 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002180 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002181 lua_pushinteger(L, 1);
2182 return 1;
2183 }
2184
Thierry FOURNIER847ca662016-12-16 13:07:22 +01002185 if (!hlua_com_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002187 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002188 return 0;
2189}
2190
2191/* This function fail or initite the connection. */
2192__LJMP static int hlua_socket_connect(struct lua_State *L)
2193{
2194 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002195 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002196 const char *ip;
2197 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002198 struct hlua *hlua;
2199 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002200 int low, high;
2201 struct sockaddr_storage *addr;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002202
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002203 if (lua_gettop(L) < 2)
2204 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002205
2206 /* Get args. */
2207 socket = MAY_LJMP(hlua_checksocket(L, 1));
2208 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002209 if (lua_gettop(L) >= 3)
2210 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002211
Willy Tarreau973a5422015-08-05 21:47:23 +02002212 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002213 if (!conn)
2214 WILL_LJMP(luaL_error(L, "connect: internal error"));
2215
Willy Tarreau3adac082015-09-26 17:51:09 +02002216 /* needed for the connection not to be closed */
2217 conn->target = socket->s->target;
2218
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002219 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002220 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002221 if (!addr)
2222 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
2223 if (low != high)
2224 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
2225 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226
2227 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002228 if (low == 0) {
2229 if (conn->addr.to.ss_family == AF_INET) {
2230 if (port == -1)
2231 WILL_LJMP(luaL_error(L, "connect: port missing"));
2232 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2233 } else if (conn->addr.to.ss_family == AF_INET6) {
2234 if (port == -1)
2235 WILL_LJMP(luaL_error(L, "connect: port missing"));
2236 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2237 }
2238 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002239
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002240 hlua = hlua_gethlua(L);
2241 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002242
2243 /* inform the stream that we want to be notified whenever the
2244 * connection completes.
2245 */
2246 si_applet_cant_get(&socket->s->si[0]);
2247 si_applet_cant_put(&socket->s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002248 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002249
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002250 hlua->flags |= HLUA_MUST_GC;
2251
Thierry FOURNIER847ca662016-12-16 13:07:22 +01002252 if (!hlua_com_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task))
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002253 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002254 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002255
2256 return 0;
2257}
2258
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002259#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002260__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2261{
2262 struct hlua_socket *socket;
2263
2264 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2265 socket = MAY_LJMP(hlua_checksocket(L, 1));
2266 socket->s->target = &socket_ssl.obj_type;
2267 return MAY_LJMP(hlua_socket_connect(L));
2268}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002269#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002270
2271__LJMP static int hlua_socket_setoption(struct lua_State *L)
2272{
2273 return 0;
2274}
2275
2276__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2277{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002278 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002279 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002280
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002281 MAY_LJMP(check_args(L, 2, "settimeout"));
2282
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002283 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002284 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002285
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002286 socket->s->req.rto = tmout;
2287 socket->s->req.wto = tmout;
2288 socket->s->res.rto = tmout;
2289 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002290
2291 return 0;
2292}
2293
2294__LJMP static int hlua_socket_new(lua_State *L)
2295{
2296 struct hlua_socket *socket;
2297 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002298 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002299 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002300 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002301
2302 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002303 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002304 hlua_pusherror(L, "socket: full stack");
2305 goto out_fail_conf;
2306 }
2307
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002308 /* Create the object: obj[0] = userdata. */
2309 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002310 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002311 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002312 memset(socket, 0, sizeof(*socket));
2313
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002314 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002315 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002316 hlua_pusherror(L, "socket: uninitialized pools.");
2317 goto out_fail_conf;
2318 }
2319
Willy Tarreau87b09662015-04-03 00:22:06 +02002320 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2322 lua_setmetatable(L, -2);
2323
Willy Tarreaud420a972015-04-06 00:39:18 +02002324 /* Create the applet context */
2325 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002326 if (!appctx) {
2327 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002328 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002329 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002330
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002331 appctx->ctx.hlua_cosocket.socket = socket;
2332 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002333 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002334 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2335 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002336
Willy Tarreaud420a972015-04-06 00:39:18 +02002337 /* Now create a session, task and stream for this applet */
2338 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2339 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002340 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002341 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002342 }
2343
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002344 task = task_new();
2345 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002346 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002347 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002348 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002349 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002350
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002351 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002352 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002353 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002354 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002355 }
2356
Willy Tarreaud420a972015-04-06 00:39:18 +02002357 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002358 socket->s = strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002359
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002360 /* Configure "right" stream interface. this "si" is used to connect
2361 * and retrieve data from the server. The connection is initialized
2362 * with the "struct server".
2363 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002364 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002365
2366 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002367 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2368 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002369
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002370 /* Update statistics counters. */
2371 socket_proxy.feconn++; /* beconn will be increased later */
2372 jobs++;
2373 totalconn++;
2374
Emeric Brun5f77fef2017-05-29 15:26:51 +02002375 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002376 /* Return yield waiting for connection. */
2377 return 1;
2378
Willy Tarreaud420a972015-04-06 00:39:18 +02002379 out_fail_stream:
2380 task_free(task);
2381 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002382 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002383 out_fail_sess:
2384 appctx_free(appctx);
2385 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002386 WILL_LJMP(lua_error(L));
2387 return 0;
2388}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002389
2390/*
2391 *
2392 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002393 * Class Channel
2394 *
2395 *
2396 */
2397
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002398/* The state between the channel data and the HTTP parser state can be
2399 * unconsistent, so reset the parser and call it again. Warning, this
2400 * action not revalidate the request and not send a 400 if the modified
2401 * resuest is not valid.
2402 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002403 * This function never fails. The direction is set using dir, which equals
2404 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002405 */
2406static void hlua_resynchonize_proto(struct stream *stream, int dir)
2407{
2408 /* Protocol HTTP. */
2409 if (stream->be->mode == PR_MODE_HTTP) {
2410
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002411 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002412 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002413 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002414 http_txn_reset_res(stream->txn);
2415
2416 if (stream->txn->hdr_idx.v)
2417 hdr_idx_init(&stream->txn->hdr_idx);
2418
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002419 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002420 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002421 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002422 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2423 }
2424}
2425
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002426/* This function is called before the Lua execution. It stores
2427 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002428 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002429static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002430{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002431 c->mode = stream->be->mode;
2432 switch (c->mode) {
2433 case PR_MODE_HTTP:
2434 c->data.http.dir = opt & SMP_OPT_DIR;
2435 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2436 c->data.http.state = stream->txn->req.msg_state;
2437 else
2438 c->data.http.state = stream->txn->rsp.msg_state;
2439 break;
2440 default:
2441 break;
2442 }
2443}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002444
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002445/* This function is called after the Lua execution. it
2446 * returns true if the parser state is consistent, otherwise,
2447 * it return false.
2448 *
2449 * In HTTP mode, the parser state must be in the same state
2450 * or greater when we exit the function. Even if we do a
2451 * control yield. This prevent to break the HTTP message
2452 * from the Lua code.
2453 */
2454static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2455{
2456 if (c->mode != stream->be->mode)
2457 return 0;
2458
2459 switch (c->mode) {
2460 case PR_MODE_HTTP:
2461 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002462 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002463 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2464 return stream->txn->req.msg_state >= c->data.http.state;
2465 else
2466 return stream->txn->rsp.msg_state >= c->data.http.state;
2467 default:
2468 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002469 }
2470 return 1;
2471}
2472
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002473/* Returns the struct hlua_channel join to the class channel in the
2474 * stack entry "ud" or throws an argument error.
2475 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002476__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002477{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002478 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002479}
2480
Willy Tarreau47860ed2015-03-10 14:07:50 +01002481/* Pushes the channel onto the top of the stack. If the stask does not have a
2482 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002483 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002484static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002485{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002486 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002487 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002488 return 0;
2489
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002490 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002491 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002492 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002493
2494 /* Pop a class sesison metatable and affect it to the userdata. */
2495 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2496 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002497 return 1;
2498}
2499
2500/* Duplicate all the data present in the input channel and put it
2501 * in a string LUA variables. Returns -1 and push a nil value in
2502 * the stack if the channel is closed and all the data are consumed,
2503 * returns 0 if no data are available, otherwise it returns the length
2504 * of the builded string.
2505 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002506static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002507{
2508 char *blk1;
2509 char *blk2;
2510 int len1;
2511 int len2;
2512 int ret;
2513 luaL_Buffer b;
2514
Willy Tarreau47860ed2015-03-10 14:07:50 +01002515 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002516 if (unlikely(ret == 0))
2517 return 0;
2518
2519 if (unlikely(ret < 0)) {
2520 lua_pushnil(L);
2521 return -1;
2522 }
2523
2524 luaL_buffinit(L, &b);
2525 luaL_addlstring(&b, blk1, len1);
2526 if (unlikely(ret == 2))
2527 luaL_addlstring(&b, blk2, len2);
2528 luaL_pushresult(&b);
2529
2530 if (unlikely(ret == 2))
2531 return len1 + len2;
2532 return len1;
2533}
2534
2535/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2536 * a yield. This function keep the data in the buffer.
2537 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002538__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002539{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002540 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002541
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002542 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2543
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002544 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002545 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002546 return 1;
2547}
2548
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002549/* Check arguments for the function "hlua_channel_dup_yield". */
2550__LJMP static int hlua_channel_dup(lua_State *L)
2551{
2552 MAY_LJMP(check_args(L, 1, "dup"));
2553 MAY_LJMP(hlua_checkchannel(L, 1));
2554 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2555}
2556
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002557/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2558 * a yield. This function consumes the data in the buffer. It returns
2559 * a string containing the data or a nil pointer if no data are available
2560 * and the channel is closed.
2561 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002562__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002563{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002564 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002565 int ret;
2566
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002567 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002568
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002569 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002570 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002571 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002572
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002573 if (unlikely(ret == -1))
2574 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002575
Willy Tarreau47860ed2015-03-10 14:07:50 +01002576 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002577 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002578 return 1;
2579}
2580
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002581/* Check arguments for the fucntion "hlua_channel_get_yield". */
2582__LJMP static int hlua_channel_get(lua_State *L)
2583{
2584 MAY_LJMP(check_args(L, 1, "get"));
2585 MAY_LJMP(hlua_checkchannel(L, 1));
2586 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2587}
2588
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002589/* This functions consumes and returns one line. If the channel is closed,
2590 * and the last data does not contains a final '\n', the data are returned
2591 * without the final '\n'. When no more data are avalaible, it returns nil
2592 * value.
2593 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002594__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002595{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002596 char *blk1;
2597 char *blk2;
2598 int len1;
2599 int len2;
2600 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002601 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002602 int ret;
2603 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002604
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002605 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2606
Willy Tarreau47860ed2015-03-10 14:07:50 +01002607 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002608 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002609 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002610
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002611 if (ret == -1) {
2612 lua_pushnil(L);
2613 return 1;
2614 }
2615
2616 luaL_buffinit(L, &b);
2617 luaL_addlstring(&b, blk1, len1);
2618 len = len1;
2619 if (unlikely(ret == 2)) {
2620 luaL_addlstring(&b, blk2, len2);
2621 len += len2;
2622 }
2623 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002624 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002625 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002626 return 1;
2627}
2628
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002629/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2630__LJMP static int hlua_channel_getline(lua_State *L)
2631{
2632 MAY_LJMP(check_args(L, 1, "getline"));
2633 MAY_LJMP(hlua_checkchannel(L, 1));
2634 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2635}
2636
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002637/* This function takes a string as input, and append it at the
2638 * input side of channel. If the data is too big, but a space
2639 * is probably available after sending some data, the function
2640 * yield. If the data is bigger than the buffer, or if the
2641 * channel is closed, it returns -1. otherwise, it returns the
2642 * amount of data writed.
2643 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002644__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002645{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002646 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002647 size_t len;
2648 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2649 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2650 int ret;
2651 int max;
2652
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002653 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2654 * the request buffer if its not required.
2655 */
2656 if (chn->buf->size == 0) {
2657 si_applet_cant_put(chn_prod(chn));
2658 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2659 }
2660
Willy Tarreau47860ed2015-03-10 14:07:50 +01002661 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002662 if (max > len - l)
2663 max = len - l;
2664
Willy Tarreau47860ed2015-03-10 14:07:50 +01002665 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002666 if (ret == -2 || ret == -3) {
2667 lua_pushinteger(L, -1);
2668 return 1;
2669 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002670 if (ret == -1) {
2671 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002672 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002673 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002674 l += ret;
2675 lua_pop(L, 1);
2676 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002677 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002678
Willy Tarreau47860ed2015-03-10 14:07:50 +01002679 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2680 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002681 /* There are no space avalaible, and the output buffer is empty.
2682 * in this case, we cannot add more data, so we cannot yield,
2683 * we return the amount of copyied data.
2684 */
2685 return 1;
2686 }
2687 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002688 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002689 return 1;
2690}
2691
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002692/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002693 * of the writed string, or -1 if the channel is closed or if the
2694 * buffer size is too little for the data.
2695 */
2696__LJMP static int hlua_channel_append(lua_State *L)
2697{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002698 size_t len;
2699
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002700 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002701 MAY_LJMP(hlua_checkchannel(L, 1));
2702 MAY_LJMP(luaL_checklstring(L, 2, &len));
2703 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002704 lua_pushinteger(L, 0);
2705
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002706 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002707}
2708
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002709/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002710 * his process by cleaning the buffer. The result is a replacement
2711 * of the current data. It returns the length of the writed string,
2712 * or -1 if the channel is closed or if the buffer size is too
2713 * little for the data.
2714 */
2715__LJMP static int hlua_channel_set(lua_State *L)
2716{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002717 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002718
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002719 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002720 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002721 lua_pushinteger(L, 0);
2722
Willy Tarreau47860ed2015-03-10 14:07:50 +01002723 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002724
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002725 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002726}
2727
2728/* Append data in the output side of the buffer. This data is immediatly
2729 * sent. The fcuntion returns the ammount of data writed. If the buffer
2730 * cannot contains the data, the function yield. The function returns -1
2731 * if the channel is closed.
2732 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002733__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002734{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002735 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002736 size_t len;
2737 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2738 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2739 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002740 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002741
Willy Tarreau47860ed2015-03-10 14:07:50 +01002742 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002743 lua_pushinteger(L, -1);
2744 return 1;
2745 }
2746
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002747 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2748 * the request buffer if its not required.
2749 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002750 if (chn->buf->size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002751 si_applet_cant_put(chn_prod(chn));
2752 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002753 }
2754
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002755 /* the writed data will be immediatly sent, so we can check
2756 * the avalaible space without taking in account the reserve.
2757 * The reserve is guaranted for the processing of incoming
2758 * data, because the buffer will be flushed.
2759 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002760 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002761
2762 /* If there are no space avalaible, and the output buffer is empty.
2763 * in this case, we cannot add more data, so we cannot yield,
2764 * we return the amount of copyied data.
2765 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002766 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002767 return 1;
2768
2769 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002770 if (max > len - l)
2771 max = len - l;
2772
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002773 /* The buffer avalaible size may be not contiguous. This test
2774 * detects a non contiguous buffer and realign it.
2775 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002776 if (bi_space_for_replace(chn->buf) < max)
2777 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002778
2779 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002780 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002781
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002782 /* buffer replace considers that the input part is filled.
2783 * so, I must forward these new data in the output part.
2784 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002785 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002786
2787 l += max;
2788 lua_pop(L, 1);
2789 lua_pushinteger(L, l);
2790
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002791 /* If there are no space avalaible, and the output buffer is empty.
2792 * in this case, we cannot add more data, so we cannot yield,
2793 * we return the amount of copyied data.
2794 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002795 max = chn->buf->size - buffer_len(chn->buf);
2796 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002797 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002798
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002799 if (l < len) {
2800 /* If we are waiting for space in the response buffer, we
2801 * must set the flag WAKERESWR. This flag required the task
2802 * wake up if any activity is detected on the response buffer.
2803 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002804 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002805 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002806 else
2807 HLUA_SET_WAKEREQWR(hlua);
2808 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002809 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002810
2811 return 1;
2812}
2813
2814/* Just a wraper of "_hlua_channel_send". This wrapper permits
2815 * yield the LUA process, and resume it without checking the
2816 * input arguments.
2817 */
2818__LJMP static int hlua_channel_send(lua_State *L)
2819{
2820 MAY_LJMP(check_args(L, 2, "send"));
2821 lua_pushinteger(L, 0);
2822
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002823 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002824}
2825
2826/* This function forward and amount of butes. The data pass from
2827 * the input side of the buffer to the output side, and can be
2828 * forwarded. This function never fails.
2829 *
2830 * The Lua function takes an amount of bytes to be forwarded in
2831 * imput. It returns the number of bytes forwarded.
2832 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002833__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002834{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002835 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002836 int len;
2837 int l;
2838 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002839 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002840
2841 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2842 len = MAY_LJMP(luaL_checkinteger(L, 2));
2843 l = MAY_LJMP(luaL_checkinteger(L, -1));
2844
2845 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002846 if (max > chn->buf->i)
2847 max = chn->buf->i;
2848 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002849 l += max;
2850
2851 lua_pop(L, 1);
2852 lua_pushinteger(L, l);
2853
2854 /* Check if it miss bytes to forward. */
2855 if (l < len) {
2856 /* The the input channel or the output channel are closed, we
2857 * must return the amount of data forwarded.
2858 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002859 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002860 return 1;
2861
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002862 /* If we are waiting for space data in the response buffer, we
2863 * must set the flag WAKERESWR. This flag required the task
2864 * wake up if any activity is detected on the response buffer.
2865 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002866 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002867 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002868 else
2869 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002870
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002871 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002872 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002873 }
2874
2875 return 1;
2876}
2877
2878/* Just check the input and prepare the stack for the previous
2879 * function "hlua_channel_forward_yield"
2880 */
2881__LJMP static int hlua_channel_forward(lua_State *L)
2882{
2883 MAY_LJMP(check_args(L, 2, "forward"));
2884 MAY_LJMP(hlua_checkchannel(L, 1));
2885 MAY_LJMP(luaL_checkinteger(L, 2));
2886
2887 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002888 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002889}
2890
2891/* Just returns the number of bytes available in the input
2892 * side of the buffer. This function never fails.
2893 */
2894__LJMP static int hlua_channel_get_in_len(lua_State *L)
2895{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002896 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002897
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002898 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002899 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002900 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002901 return 1;
2902}
2903
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01002904/* Returns true if the channel is full. */
2905__LJMP static int hlua_channel_is_full(lua_State *L)
2906{
2907 struct channel *chn;
2908 int rem;
2909
2910 MAY_LJMP(check_args(L, 1, "is_full"));
2911 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2912
2913 rem = chn->buf->size;
2914 rem -= chn->buf->o; /* Output size */
2915 rem -= chn->buf->i; /* Input size */
2916 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
2917
2918 lua_pushboolean(L, rem <= 0);
2919 return 1;
2920}
2921
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002922/* Just returns the number of bytes available in the output
2923 * side of the buffer. This function never fails.
2924 */
2925__LJMP static int hlua_channel_get_out_len(lua_State *L)
2926{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002927 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002928
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002929 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002930 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002931 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002932 return 1;
2933}
2934
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002935/*
2936 *
2937 *
2938 * Class Fetches
2939 *
2940 *
2941 */
2942
2943/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002944 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002945 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002946__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002947{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002948 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002949}
2950
2951/* This function creates and push in the stack a fetch object according
2952 * with a current TXN.
2953 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002954static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002955{
Willy Tarreau7073c472015-04-06 11:15:40 +02002956 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002957
2958 /* Check stack size. */
2959 if (!lua_checkstack(L, 3))
2960 return 0;
2961
2962 /* Create the object: obj[0] = userdata.
2963 * Note that the base of the Fetches object is the
2964 * transaction object.
2965 */
2966 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002967 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002968 lua_rawseti(L, -2, 0);
2969
Willy Tarreau7073c472015-04-06 11:15:40 +02002970 hsmp->s = txn->s;
2971 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01002972 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002973 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002974
2975 /* Pop a class sesison metatable and affect it to the userdata. */
2976 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2977 lua_setmetatable(L, -2);
2978
2979 return 1;
2980}
2981
2982/* This function is an LUA binding. It is called with each sample-fetch.
2983 * It uses closure argument to store the associated sample-fetch. It
2984 * returns only one argument or throws an error. An error is thrown
2985 * only if an error is encountered during the argument parsing. If
2986 * the "sample-fetch" function fails, nil is returned.
2987 */
2988__LJMP static int hlua_run_sample_fetch(lua_State *L)
2989{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002990 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002991 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002992 struct arg args[ARGM_NBARGS + 1];
2993 int i;
2994 struct sample smp;
2995
2996 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002997 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002998
2999 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003000 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003001
Thierry FOURNIERca988662015-12-20 18:43:03 +01003002 /* Check execution authorization. */
3003 if (f->use & SMP_USE_HTTP_ANY &&
3004 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3005 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3006 "is not available in Lua services", f->kw);
3007 WILL_LJMP(lua_error(L));
3008 }
3009
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003010 /* Get extra arguments. */
3011 for (i = 0; i < lua_gettop(L) - 1; i++) {
3012 if (i >= ARGM_NBARGS)
3013 break;
3014 hlua_lua2arg(L, i + 2, &args[i]);
3015 }
3016 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003017 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003018
3019 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003020 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003021
3022 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003023 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003024 lua_pushfstring(L, "error in arguments");
3025 WILL_LJMP(lua_error(L));
3026 }
3027
3028 /* Initialise the sample. */
3029 memset(&smp, 0, sizeof(smp));
3030
3031 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003032 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003033 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003034 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003035 lua_pushstring(L, "");
3036 else
3037 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003038 return 1;
3039 }
3040
3041 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003042 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003043 hlua_smp2lua_str(L, &smp);
3044 else
3045 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003046 return 1;
3047}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003048
3049/*
3050 *
3051 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003052 * Class Converters
3053 *
3054 *
3055 */
3056
3057/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003058 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003059 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003060__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003061{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003062 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003063}
3064
3065/* This function creates and push in the stack a Converters object
3066 * according with a current TXN.
3067 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003068static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003069{
Willy Tarreau7073c472015-04-06 11:15:40 +02003070 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003071
3072 /* Check stack size. */
3073 if (!lua_checkstack(L, 3))
3074 return 0;
3075
3076 /* Create the object: obj[0] = userdata.
3077 * Note that the base of the Converters object is the
3078 * same than the TXN object.
3079 */
3080 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003081 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003082 lua_rawseti(L, -2, 0);
3083
Willy Tarreau7073c472015-04-06 11:15:40 +02003084 hsmp->s = txn->s;
3085 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003086 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003087 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003088
Willy Tarreau87b09662015-04-03 00:22:06 +02003089 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003090 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3091 lua_setmetatable(L, -2);
3092
3093 return 1;
3094}
3095
3096/* This function is an LUA binding. It is called with each converter.
3097 * It uses closure argument to store the associated converter. It
3098 * returns only one argument or throws an error. An error is thrown
3099 * only if an error is encountered during the argument parsing. If
3100 * the converter function function fails, nil is returned.
3101 */
3102__LJMP static int hlua_run_sample_conv(lua_State *L)
3103{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003104 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003105 struct sample_conv *conv;
3106 struct arg args[ARGM_NBARGS + 1];
3107 int i;
3108 struct sample smp;
3109
3110 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003111 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003112
3113 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003114 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003115
3116 /* Get extra arguments. */
3117 for (i = 0; i < lua_gettop(L) - 2; i++) {
3118 if (i >= ARGM_NBARGS)
3119 break;
3120 hlua_lua2arg(L, i + 3, &args[i]);
3121 }
3122 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003123 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003124
3125 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003126 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003127
3128 /* Run the special args checker. */
3129 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3130 hlua_pusherror(L, "error in arguments");
3131 WILL_LJMP(lua_error(L));
3132 }
3133
3134 /* Initialise the sample. */
3135 if (!hlua_lua2smp(L, 2, &smp)) {
3136 hlua_pusherror(L, "error in the input argument");
3137 WILL_LJMP(lua_error(L));
3138 }
3139
Willy Tarreau1777ea62016-03-10 16:15:46 +01003140 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3141
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003142 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003143 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003144 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003145 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003146 WILL_LJMP(lua_error(L));
3147 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003148 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3149 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003150 hlua_pusherror(L, "error during the input argument casting");
3151 WILL_LJMP(lua_error(L));
3152 }
3153
3154 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003155 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003156 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003157 lua_pushstring(L, "");
3158 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003159 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003160 return 1;
3161 }
3162
3163 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003164 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003165 hlua_smp2lua_str(L, &smp);
3166 else
3167 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003168 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003169}
3170
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003171/*
3172 *
3173 *
3174 * Class AppletTCP
3175 *
3176 *
3177 */
3178
3179/* Returns a struct hlua_txn if the stack entry "ud" is
3180 * a class stream, otherwise it throws an error.
3181 */
3182__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3183{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003184 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003185}
3186
3187/* This function creates and push in the stack an Applet object
3188 * according with a current TXN.
3189 */
3190static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3191{
3192 struct hlua_appctx *appctx;
3193 struct stream_interface *si = ctx->owner;
3194 struct stream *s = si_strm(si);
3195 struct proxy *p = s->be;
3196
3197 /* Check stack size. */
3198 if (!lua_checkstack(L, 3))
3199 return 0;
3200
3201 /* Create the object: obj[0] = userdata.
3202 * Note that the base of the Converters object is the
3203 * same than the TXN object.
3204 */
3205 lua_newtable(L);
3206 appctx = lua_newuserdata(L, sizeof(*appctx));
3207 lua_rawseti(L, -2, 0);
3208 appctx->appctx = ctx;
3209 appctx->htxn.s = s;
3210 appctx->htxn.p = p;
3211
3212 /* Create the "f" field that contains a list of fetches. */
3213 lua_pushstring(L, "f");
3214 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3215 return 0;
3216 lua_settable(L, -3);
3217
3218 /* Create the "sf" field that contains a list of stringsafe fetches. */
3219 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003220 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003221 return 0;
3222 lua_settable(L, -3);
3223
3224 /* Create the "c" field that contains a list of converters. */
3225 lua_pushstring(L, "c");
3226 if (!hlua_converters_new(L, &appctx->htxn, 0))
3227 return 0;
3228 lua_settable(L, -3);
3229
3230 /* Create the "sc" field that contains a list of stringsafe converters. */
3231 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003232 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003233 return 0;
3234 lua_settable(L, -3);
3235
3236 /* Pop a class stream metatable and affect it to the table. */
3237 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3238 lua_setmetatable(L, -2);
3239
3240 return 1;
3241}
3242
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003243__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3244{
3245 struct hlua_appctx *appctx;
3246 struct stream *s;
3247 const char *name;
3248 size_t len;
3249 struct sample smp;
3250
3251 MAY_LJMP(check_args(L, 3, "set_var"));
3252
3253 /* It is useles to retrieve the stream, but this function
3254 * runs only in a stream context.
3255 */
3256 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3257 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3258 s = appctx->htxn.s;
3259
3260 /* Converts the third argument in a sample. */
3261 hlua_lua2smp(L, 3, &smp);
3262
3263 /* Store the sample in a variable. */
3264 smp_set_owner(&smp, s->be, s->sess, s, 0);
3265 vars_set_by_name(name, len, &smp);
3266 return 0;
3267}
3268
3269__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3270{
3271 struct hlua_appctx *appctx;
3272 struct stream *s;
3273 const char *name;
3274 size_t len;
3275 struct sample smp;
3276
3277 MAY_LJMP(check_args(L, 2, "unset_var"));
3278
3279 /* It is useles to retrieve the stream, but this function
3280 * runs only in a stream context.
3281 */
3282 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3283 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3284 s = appctx->htxn.s;
3285
3286 /* Unset the variable. */
3287 smp_set_owner(&smp, s->be, s->sess, s, 0);
3288 vars_unset_by_name(name, len, &smp);
3289 return 0;
3290}
3291
3292__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3293{
3294 struct hlua_appctx *appctx;
3295 struct stream *s;
3296 const char *name;
3297 size_t len;
3298 struct sample smp;
3299
3300 MAY_LJMP(check_args(L, 2, "get_var"));
3301
3302 /* It is useles to retrieve the stream, but this function
3303 * runs only in a stream context.
3304 */
3305 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3306 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3307 s = appctx->htxn.s;
3308
3309 smp_set_owner(&smp, s->be, s->sess, s, 0);
3310 if (!vars_get_by_name(name, len, &smp)) {
3311 lua_pushnil(L);
3312 return 1;
3313 }
3314
3315 return hlua_smp2lua(L, &smp);
3316}
3317
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003318__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3319{
3320 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3321 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003322 struct hlua *hlua;
3323
3324 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003325 if (!s->hlua)
3326 return 0;
3327 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003328
3329 MAY_LJMP(check_args(L, 2, "set_priv"));
3330
3331 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003332 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003333
3334 /* Get and store new value. */
3335 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3336 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3337
3338 return 0;
3339}
3340
3341__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3342{
3343 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3344 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003345 struct hlua *hlua;
3346
3347 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003348 if (!s->hlua) {
3349 lua_pushnil(L);
3350 return 1;
3351 }
3352 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003353
3354 /* Push configuration index in the stack. */
3355 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3356
3357 return 1;
3358}
3359
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003360/* If expected data not yet available, it returns a yield. This function
3361 * consumes the data in the buffer. It returns a string containing the
3362 * data. This string can be empty.
3363 */
3364__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3365{
3366 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3367 struct stream_interface *si = appctx->appctx->owner;
3368 int ret;
3369 char *blk1;
3370 int len1;
3371 char *blk2;
3372 int len2;
3373
3374 /* Read the maximum amount of data avalaible. */
3375 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3376
3377 /* Data not yet avalaible. return yield. */
3378 if (ret == 0) {
3379 si_applet_cant_get(si);
3380 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3381 }
3382
3383 /* End of data: commit the total strings and return. */
3384 if (ret < 0) {
3385 luaL_pushresult(&appctx->b);
3386 return 1;
3387 }
3388
3389 /* Ensure that the block 2 length is usable. */
3390 if (ret == 1)
3391 len2 = 0;
3392
3393 /* dont check the max length read and dont check. */
3394 luaL_addlstring(&appctx->b, blk1, len1);
3395 luaL_addlstring(&appctx->b, blk2, len2);
3396
3397 /* Consume input channel output buffer data. */
3398 bo_skip(si_oc(si), len1 + len2);
3399 luaL_pushresult(&appctx->b);
3400 return 1;
3401}
3402
3403/* Check arguments for the fucntion "hlua_channel_get_yield". */
3404__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3405{
3406 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3407
3408 /* Initialise the string catenation. */
3409 luaL_buffinit(L, &appctx->b);
3410
3411 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3412}
3413
3414/* If expected data not yet available, it returns a yield. This function
3415 * consumes the data in the buffer. It returns a string containing the
3416 * data. This string can be empty.
3417 */
3418__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3419{
3420 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3421 struct stream_interface *si = appctx->appctx->owner;
3422 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3423 int ret;
3424 char *blk1;
3425 int len1;
3426 char *blk2;
3427 int len2;
3428
3429 /* Read the maximum amount of data avalaible. */
3430 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3431
3432 /* Data not yet avalaible. return yield. */
3433 if (ret == 0) {
3434 si_applet_cant_get(si);
3435 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3436 }
3437
3438 /* End of data: commit the total strings and return. */
3439 if (ret < 0) {
3440 luaL_pushresult(&appctx->b);
3441 return 1;
3442 }
3443
3444 /* Ensure that the block 2 length is usable. */
3445 if (ret == 1)
3446 len2 = 0;
3447
3448 if (len == -1) {
3449
3450 /* If len == -1, catenate all the data avalaile and
3451 * yield because we want to get all the data until
3452 * the end of data stream.
3453 */
3454 luaL_addlstring(&appctx->b, blk1, len1);
3455 luaL_addlstring(&appctx->b, blk2, len2);
3456 bo_skip(si_oc(si), len1 + len2);
3457 si_applet_cant_get(si);
3458 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3459
3460 } else {
3461
3462 /* Copy the fisrt block caping to the length required. */
3463 if (len1 > len)
3464 len1 = len;
3465 luaL_addlstring(&appctx->b, blk1, len1);
3466 len -= len1;
3467
3468 /* Copy the second block. */
3469 if (len2 > len)
3470 len2 = len;
3471 luaL_addlstring(&appctx->b, blk2, len2);
3472 len -= len2;
3473
3474 /* Consume input channel output buffer data. */
3475 bo_skip(si_oc(si), len1 + len2);
3476
3477 /* If we are no other data avalaible, yield waiting for new data. */
3478 if (len > 0) {
3479 lua_pushinteger(L, len);
3480 lua_replace(L, 2);
3481 si_applet_cant_get(si);
3482 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3483 }
3484
3485 /* return the result. */
3486 luaL_pushresult(&appctx->b);
3487 return 1;
3488 }
3489
3490 /* we never executes this */
3491 hlua_pusherror(L, "Lua: internal error");
3492 WILL_LJMP(lua_error(L));
3493 return 0;
3494}
3495
3496/* Check arguments for the fucntion "hlua_channel_get_yield". */
3497__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3498{
3499 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3500 int len = -1;
3501
3502 if (lua_gettop(L) > 2)
3503 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3504 if (lua_gettop(L) >= 2) {
3505 len = MAY_LJMP(luaL_checkinteger(L, 2));
3506 lua_pop(L, 1);
3507 }
3508
3509 /* Confirm or set the required length */
3510 lua_pushinteger(L, len);
3511
3512 /* Initialise the string catenation. */
3513 luaL_buffinit(L, &appctx->b);
3514
3515 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3516}
3517
3518/* Append data in the output side of the buffer. This data is immediatly
3519 * sent. The fcuntion returns the ammount of data writed. If the buffer
3520 * cannot contains the data, the function yield. The function returns -1
3521 * if the channel is closed.
3522 */
3523__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3524{
3525 size_t len;
3526 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3527 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3528 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3529 struct stream_interface *si = appctx->appctx->owner;
3530 struct channel *chn = si_ic(si);
3531 int max;
3532
3533 /* Get the max amount of data which can write as input in the channel. */
3534 max = channel_recv_max(chn);
3535 if (max > (len - l))
3536 max = len - l;
3537
3538 /* Copy data. */
3539 bi_putblk(chn, str + l, max);
3540
3541 /* update counters. */
3542 l += max;
3543 lua_pop(L, 1);
3544 lua_pushinteger(L, l);
3545
3546 /* If some data is not send, declares the situation to the
3547 * applet, and returns a yield.
3548 */
3549 if (l < len) {
3550 si_applet_cant_put(si);
3551 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3552 }
3553
3554 return 1;
3555}
3556
3557/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3558 * yield the LUA process, and resume it without checking the
3559 * input arguments.
3560 */
3561__LJMP static int hlua_applet_tcp_send(lua_State *L)
3562{
3563 MAY_LJMP(check_args(L, 2, "send"));
3564 lua_pushinteger(L, 0);
3565
3566 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3567}
3568
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003569/*
3570 *
3571 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003572 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003573 *
3574 *
3575 */
3576
3577/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003578 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003579 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003580__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003581{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003582 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003583}
3584
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003585/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003586 * according with a current TXN.
3587 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003588static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003589{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003590 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003591 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003592 struct stream_interface *si = ctx->owner;
3593 struct stream *s = si_strm(si);
3594 struct proxy *px = s->be;
3595 struct http_txn *txn = s->txn;
3596 const char *path;
3597 const char *end;
3598 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003599
3600 /* Check stack size. */
3601 if (!lua_checkstack(L, 3))
3602 return 0;
3603
3604 /* Create the object: obj[0] = userdata.
3605 * Note that the base of the Converters object is the
3606 * same than the TXN object.
3607 */
3608 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003609 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003610 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003611 appctx->appctx = ctx;
3612 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003613 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003614 appctx->htxn.s = s;
3615 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003616
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003617 /* Create the "f" field that contains a list of fetches. */
3618 lua_pushstring(L, "f");
3619 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3620 return 0;
3621 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003622
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003623 /* Create the "sf" field that contains a list of stringsafe fetches. */
3624 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003625 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003626 return 0;
3627 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003628
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003629 /* Create the "c" field that contains a list of converters. */
3630 lua_pushstring(L, "c");
3631 if (!hlua_converters_new(L, &appctx->htxn, 0))
3632 return 0;
3633 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003634
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003635 /* Create the "sc" field that contains a list of stringsafe converters. */
3636 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003637 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003638 return 0;
3639 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003640
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003641 /* Stores the request method. */
3642 lua_pushstring(L, "method");
3643 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3644 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003645
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003646 /* Stores the http version. */
3647 lua_pushstring(L, "version");
3648 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3649 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003650
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003651 /* creates an array of headers. hlua_http_get_headers() crates and push
3652 * the array on the top of the stack.
3653 */
3654 lua_pushstring(L, "headers");
3655 htxn.s = s;
3656 htxn.p = px;
3657 htxn.dir = SMP_OPT_DIR_REQ;
3658 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3659 return 0;
3660 lua_settable(L, -3);
3661
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003662 /* Get path and qs */
3663 path = http_get_path(txn);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003664 if (path) {
3665 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3666 p = path;
3667 while (p < end && *p != '?')
3668 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003669
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003670 /* Stores the request path. */
3671 lua_pushstring(L, "path");
3672 lua_pushlstring(L, path, p - path);
3673 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003674
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003675 /* Stores the query string. */
3676 lua_pushstring(L, "qs");
3677 if (*p == '?')
3678 p++;
3679 lua_pushlstring(L, p, end - p);
3680 lua_settable(L, -3);
3681 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003682
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003683 /* Stores the request path. */
3684 lua_pushstring(L, "length");
3685 lua_pushinteger(L, txn->req.body_len);
3686 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003687
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003688 /* Create an array of HTTP request headers. */
3689 lua_pushstring(L, "headers");
3690 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3691 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003692
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003693 /* Create an empty array of HTTP request headers. */
3694 lua_pushstring(L, "response");
3695 lua_newtable(L);
3696 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003697
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003698 /* Pop a class stream metatable and affect it to the table. */
3699 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3700 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003701
3702 return 1;
3703}
3704
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003705__LJMP static int hlua_applet_http_set_var(lua_State *L)
3706{
3707 struct hlua_appctx *appctx;
3708 struct stream *s;
3709 const char *name;
3710 size_t len;
3711 struct sample smp;
3712
3713 MAY_LJMP(check_args(L, 3, "set_var"));
3714
3715 /* It is useles to retrieve the stream, but this function
3716 * runs only in a stream context.
3717 */
3718 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3719 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3720 s = appctx->htxn.s;
3721
3722 /* Converts the third argument in a sample. */
3723 hlua_lua2smp(L, 3, &smp);
3724
3725 /* Store the sample in a variable. */
3726 smp_set_owner(&smp, s->be, s->sess, s, 0);
3727 vars_set_by_name(name, len, &smp);
3728 return 0;
3729}
3730
3731__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3732{
3733 struct hlua_appctx *appctx;
3734 struct stream *s;
3735 const char *name;
3736 size_t len;
3737 struct sample smp;
3738
3739 MAY_LJMP(check_args(L, 2, "unset_var"));
3740
3741 /* It is useles to retrieve the stream, but this function
3742 * runs only in a stream context.
3743 */
3744 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3745 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3746 s = appctx->htxn.s;
3747
3748 /* Unset the variable. */
3749 smp_set_owner(&smp, s->be, s->sess, s, 0);
3750 vars_unset_by_name(name, len, &smp);
3751 return 0;
3752}
3753
3754__LJMP static int hlua_applet_http_get_var(lua_State *L)
3755{
3756 struct hlua_appctx *appctx;
3757 struct stream *s;
3758 const char *name;
3759 size_t len;
3760 struct sample smp;
3761
3762 MAY_LJMP(check_args(L, 2, "get_var"));
3763
3764 /* It is useles to retrieve the stream, but this function
3765 * runs only in a stream context.
3766 */
3767 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3768 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3769 s = appctx->htxn.s;
3770
3771 smp_set_owner(&smp, s->be, s->sess, s, 0);
3772 if (!vars_get_by_name(name, len, &smp)) {
3773 lua_pushnil(L);
3774 return 1;
3775 }
3776
3777 return hlua_smp2lua(L, &smp);
3778}
3779
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003780__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3781{
3782 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3783 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003784 struct hlua *hlua;
3785
3786 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003787 if (!s->hlua)
3788 return 0;
3789 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003790
3791 MAY_LJMP(check_args(L, 2, "set_priv"));
3792
3793 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003794 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003795
3796 /* Get and store new value. */
3797 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3798 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3799
3800 return 0;
3801}
3802
3803__LJMP static int hlua_applet_http_get_priv(lua_State *L)
3804{
3805 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3806 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003807 struct hlua *hlua;
3808
3809 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003810 if (!s->hlua) {
3811 lua_pushnil(L);
3812 return 1;
3813 }
3814 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003815
3816 /* Push configuration index in the stack. */
3817 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3818
3819 return 1;
3820}
3821
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003822/* If expected data not yet available, it returns a yield. This function
3823 * consumes the data in the buffer. It returns a string containing the
3824 * data. This string can be empty.
3825 */
3826__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003827{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003828 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3829 struct stream_interface *si = appctx->appctx->owner;
3830 struct channel *chn = si_ic(si);
3831 int ret;
3832 char *blk1;
3833 int len1;
3834 char *blk2;
3835 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003836
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003837 /* Maybe we cant send a 100-continue ? */
3838 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3839 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3840 /* if ret == -2 or -3 the channel closed or the message si too
3841 * big for the buffers. We cant send anything. So, we ignoring
3842 * the error, considers that the 100-continue is sent, and try
3843 * to receive.
3844 * If ret is -1, we dont have room in the buffer, so we yield.
3845 */
3846 if (ret == -1) {
3847 si_applet_cant_put(si);
3848 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3849 }
3850 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3851 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003852
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003853 /* Check for the end of the data. */
3854 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3855 luaL_pushresult(&appctx->b);
3856 return 1;
3857 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003858
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003859 /* Read the maximum amount of data avalaible. */
3860 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003861
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003862 /* Data not yet avalaible. return yield. */
3863 if (ret == 0) {
3864 si_applet_cant_get(si);
3865 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3866 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003867
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003868 /* End of data: commit the total strings and return. */
3869 if (ret < 0) {
3870 luaL_pushresult(&appctx->b);
3871 return 1;
3872 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003873
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003874 /* Ensure that the block 2 length is usable. */
3875 if (ret == 1)
3876 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003877
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003878 /* Copy the fisrt block caping to the length required. */
3879 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3880 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3881 luaL_addlstring(&appctx->b, blk1, len1);
3882 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003883
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003884 /* Copy the second block. */
3885 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3886 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3887 luaL_addlstring(&appctx->b, blk2, len2);
3888 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003889
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003890 /* Consume input channel output buffer data. */
3891 bo_skip(si_oc(si), len1 + len2);
3892 luaL_pushresult(&appctx->b);
3893 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003894}
3895
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003896/* Check arguments for the fucntion "hlua_channel_get_yield". */
3897__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003898{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003899 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003900
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003901 /* Initialise the string catenation. */
3902 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003903
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003904 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003905}
3906
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003907/* If expected data not yet available, it returns a yield. This function
3908 * consumes the data in the buffer. It returns a string containing the
3909 * data. This string can be empty.
3910 */
3911__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003912{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003913 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3914 struct stream_interface *si = appctx->appctx->owner;
3915 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3916 struct channel *chn = si_ic(si);
3917 int ret;
3918 char *blk1;
3919 int len1;
3920 char *blk2;
3921 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003922
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003923 /* Maybe we cant send a 100-continue ? */
3924 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3925 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3926 /* if ret == -2 or -3 the channel closed or the message si too
3927 * big for the buffers. We cant send anything. So, we ignoring
3928 * the error, considers that the 100-continue is sent, and try
3929 * to receive.
3930 * If ret is -1, we dont have room in the buffer, so we yield.
3931 */
3932 if (ret == -1) {
3933 si_applet_cant_put(si);
3934 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3935 }
3936 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3937 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003938
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003939 /* Read the maximum amount of data avalaible. */
3940 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003941
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003942 /* Data not yet avalaible. return yield. */
3943 if (ret == 0) {
3944 si_applet_cant_get(si);
3945 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3946 }
3947
3948 /* End of data: commit the total strings and return. */
3949 if (ret < 0) {
3950 luaL_pushresult(&appctx->b);
3951 return 1;
3952 }
3953
3954 /* Ensure that the block 2 length is usable. */
3955 if (ret == 1)
3956 len2 = 0;
3957
3958 /* Copy the fisrt block caping to the length required. */
3959 if (len1 > len)
3960 len1 = len;
3961 luaL_addlstring(&appctx->b, blk1, len1);
3962 len -= len1;
3963
3964 /* Copy the second block. */
3965 if (len2 > len)
3966 len2 = len;
3967 luaL_addlstring(&appctx->b, blk2, len2);
3968 len -= len2;
3969
3970 /* Consume input channel output buffer data. */
3971 bo_skip(si_oc(si), len1 + len2);
3972 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
3973 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
3974
3975 /* If we are no other data avalaible, yield waiting for new data. */
3976 if (len > 0) {
3977 lua_pushinteger(L, len);
3978 lua_replace(L, 2);
3979 si_applet_cant_get(si);
3980 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3981 }
3982
3983 /* return the result. */
3984 luaL_pushresult(&appctx->b);
3985 return 1;
3986}
3987
3988/* Check arguments for the fucntion "hlua_channel_get_yield". */
3989__LJMP static int hlua_applet_http_recv(lua_State *L)
3990{
3991 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3992 int len = -1;
3993
3994 /* Check arguments. */
3995 if (lua_gettop(L) > 2)
3996 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3997 if (lua_gettop(L) >= 2) {
3998 len = MAY_LJMP(luaL_checkinteger(L, 2));
3999 lua_pop(L, 1);
4000 }
4001
4002 /* Check the required length */
4003 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4004 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4005 lua_pushinteger(L, len);
4006
4007 /* Initialise the string catenation. */
4008 luaL_buffinit(L, &appctx->b);
4009
4010 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4011}
4012
4013/* Append data in the output side of the buffer. This data is immediatly
4014 * sent. The fcuntion returns the ammount of data writed. If the buffer
4015 * cannot contains the data, the function yield. The function returns -1
4016 * if the channel is closed.
4017 */
4018__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4019{
4020 size_t len;
4021 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4022 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4023 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4024 struct stream_interface *si = appctx->appctx->owner;
4025 struct channel *chn = si_ic(si);
4026 int max;
4027
4028 /* Get the max amount of data which can write as input in the channel. */
4029 max = channel_recv_max(chn);
4030 if (max > (len - l))
4031 max = len - l;
4032
4033 /* Copy data. */
4034 bi_putblk(chn, str + l, max);
4035
4036 /* update counters. */
4037 l += max;
4038 lua_pop(L, 1);
4039 lua_pushinteger(L, l);
4040
4041 /* If some data is not send, declares the situation to the
4042 * applet, and returns a yield.
4043 */
4044 if (l < len) {
4045 si_applet_cant_put(si);
4046 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
4047 }
4048
4049 return 1;
4050}
4051
4052/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4053 * yield the LUA process, and resume it without checking the
4054 * input arguments.
4055 */
4056__LJMP static int hlua_applet_http_send(lua_State *L)
4057{
4058 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4059 size_t len;
4060 char hex[10];
4061
4062 MAY_LJMP(luaL_checklstring(L, 2, &len));
4063
4064 /* If transfer encoding chunked is selected, we surround the data
4065 * by chunk data.
4066 */
4067 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4068 snprintf(hex, 9, "%x", (unsigned int)len);
4069 lua_pushfstring(L, "%s\r\n", hex);
4070 lua_insert(L, 2); /* swap the last 2 entries. */
4071 lua_pushstring(L, "\r\n");
4072 lua_concat(L, 3);
4073 }
4074
4075 /* This interger is used for followinf the amount of data sent. */
4076 lua_pushinteger(L, 0);
4077
4078 /* We want to send some data. Headers must be sent. */
4079 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4080 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4081 WILL_LJMP(lua_error(L));
4082 }
4083
4084 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4085}
4086
4087__LJMP static int hlua_applet_http_addheader(lua_State *L)
4088{
4089 const char *name;
4090 int ret;
4091
4092 MAY_LJMP(hlua_checkapplet_http(L, 1));
4093 name = MAY_LJMP(luaL_checkstring(L, 2));
4094 MAY_LJMP(luaL_checkstring(L, 3));
4095
4096 /* Push in the stack the "response" entry. */
4097 ret = lua_getfield(L, 1, "response");
4098 if (ret != LUA_TTABLE) {
4099 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4100 "is expected as an array. %s found", lua_typename(L, ret));
4101 WILL_LJMP(lua_error(L));
4102 }
4103
4104 /* check if the header is already registered if it is not
4105 * the case, register it.
4106 */
4107 ret = lua_getfield(L, -1, name);
4108 if (ret == LUA_TNIL) {
4109
4110 /* Entry not found. */
4111 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4112
4113 /* Insert the new header name in the array in the top of the stack.
4114 * It left the new array in the top of the stack.
4115 */
4116 lua_newtable(L);
4117 lua_pushvalue(L, 2);
4118 lua_pushvalue(L, -2);
4119 lua_settable(L, -4);
4120
4121 } else if (ret != LUA_TTABLE) {
4122
4123 /* corruption error. */
4124 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4125 "is expected as an array. %s found", name, lua_typename(L, ret));
4126 WILL_LJMP(lua_error(L));
4127 }
4128
4129 /* Now the top od thestack is an array of values. We push
4130 * the header value as new entry.
4131 */
4132 lua_pushvalue(L, 3);
4133 ret = lua_rawlen(L, -2);
4134 lua_rawseti(L, -2, ret + 1);
4135 lua_pushboolean(L, 1);
4136 return 1;
4137}
4138
4139__LJMP static int hlua_applet_http_status(lua_State *L)
4140{
4141 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4142 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004143 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004144
4145 if (status < 100 || status > 599) {
4146 lua_pushboolean(L, 0);
4147 return 1;
4148 }
4149
4150 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004151 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004152 lua_pushboolean(L, 1);
4153 return 1;
4154}
4155
4156/* We will build the status line and the headers of the HTTP response.
4157 * We will try send at once if its not possible, we give back the hand
4158 * waiting for more room.
4159 */
4160__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4161{
4162 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4163 struct stream_interface *si = appctx->appctx->owner;
4164 struct channel *chn = si_ic(si);
4165 int ret;
4166 size_t len;
4167 const char *msg;
4168
4169 /* Get the message as the first argument on the stack. */
4170 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4171
4172 /* Send the message at once. */
4173 ret = bi_putblk(chn, msg, len);
4174
4175 /* if ret == -2 or -3 the channel closed or the message si too
4176 * big for the buffers.
4177 */
4178 if (ret == -2 || ret == -3) {
4179 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4180 WILL_LJMP(lua_error(L));
4181 }
4182
4183 /* If ret is -1, we dont have room in the buffer, so we yield. */
4184 if (ret == -1) {
4185 si_applet_cant_put(si);
4186 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4187 }
4188
4189 /* Headers sent, set the flag. */
4190 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4191 return 0;
4192}
4193
4194__LJMP static int hlua_applet_http_start_response(lua_State *L)
4195{
4196 struct chunk *tmp = get_trash_chunk();
4197 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004198 const char *name;
4199 const char *value;
4200 int id;
4201 int hdr_connection = 0;
4202 int hdr_contentlength = -1;
4203 int hdr_chunked = 0;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004204 const char *reason = appctx->appctx->ctx.hlua_apphttp.reason;
4205
4206 if (reason == NULL)
4207 reason = get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004208
4209 /* Use the same http version than the request. */
4210 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004211 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004212 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004213 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004214
4215 /* Get the array associated to the field "response" in the object AppletHTTP. */
4216 lua_pushvalue(L, 0);
4217 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4218 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4219 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4220 WILL_LJMP(lua_error(L));
4221 }
4222
4223 /* Browse the list of headers. */
4224 lua_pushnil(L);
4225 while(lua_next(L, -2) != 0) {
4226
4227 /* We expect a string as -2. */
4228 if (lua_type(L, -2) != LUA_TSTRING) {
4229 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4230 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4231 lua_typename(L, lua_type(L, -2)));
4232 WILL_LJMP(lua_error(L));
4233 }
4234 name = lua_tostring(L, -2);
4235
4236 /* We expect an array as -1. */
4237 if (lua_type(L, -1) != LUA_TTABLE) {
4238 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4239 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4240 name,
4241 lua_typename(L, lua_type(L, -1)));
4242 WILL_LJMP(lua_error(L));
4243 }
4244
4245 /* Browse the table who is on the top of the stack. */
4246 lua_pushnil(L);
4247 while(lua_next(L, -2) != 0) {
4248
4249 /* We expect a number as -2. */
4250 if (lua_type(L, -2) != LUA_TNUMBER) {
4251 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4252 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4253 name,
4254 lua_typename(L, lua_type(L, -2)));
4255 WILL_LJMP(lua_error(L));
4256 }
4257 id = lua_tointeger(L, -2);
4258
4259 /* We expect a string as -2. */
4260 if (lua_type(L, -1) != LUA_TSTRING) {
4261 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4262 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4263 name, id,
4264 lua_typename(L, lua_type(L, -1)));
4265 WILL_LJMP(lua_error(L));
4266 }
4267 value = lua_tostring(L, -1);
4268
4269 /* Catenate a new header. */
4270 chunk_appendf(tmp, "%s: %s\r\n", name, value);
4271
4272 /* Protocol checks. */
4273
4274 /* Check if the header conneciton is present. */
4275 if (strcasecmp("connection", name) == 0)
4276 hdr_connection = 1;
4277
4278 /* Copy the header content length. The length conversion
4279 * is done without control. If it contains a ad value, this
4280 * is not our problem.
4281 */
4282 if (strcasecmp("content-length", name) == 0)
4283 hdr_contentlength = atoi(value);
4284
4285 /* Check if the client annouces a transfer-encoding chunked it self. */
4286 if (strcasecmp("transfer-encoding", name) == 0 &&
4287 strcasecmp("chunked", value) == 0)
4288 hdr_chunked = 1;
4289
4290 /* Remove the array from the stack, and get next element with a remaining string. */
4291 lua_pop(L, 1);
4292 }
4293
4294 /* Remove the array from the stack, and get next element with a remaining string. */
4295 lua_pop(L, 1);
4296 }
4297
4298 /* If the http protocol version is 1.1, we expect an header "connection" set
4299 * to "close" to be HAProxy/keeplive compliant. Otherwise, we expect nothing.
4300 * If the header conneciton is present, don't change it, if it is not present,
4301 * we must set.
4302 *
4303 * we set a "connection: close" header for ensuring that the keepalive will be
4304 * respected by haproxy. HAProcy considers that the application cloe the connection
4305 * and it keep the connection from the client open.
4306 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004307 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 && !hdr_connection)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004308 chunk_appendf(tmp, "Connection: close\r\n");
4309
4310 /* If we dont have a content-length set, we must announce a transfer enconding
4311 * chunked. This is required by haproxy for the keepalive compliance.
4312 * If the applet annouce a transfer-encoding chunked itslef, don't
4313 * do anything.
4314 */
4315 if (hdr_contentlength == -1 && hdr_chunked == 0) {
4316 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4317 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4318 }
4319
4320 /* Finalize headers. */
4321 chunk_appendf(tmp, "\r\n");
4322
4323 /* Remove the last entry and the array of headers */
4324 lua_pop(L, 2);
4325
4326 /* Push the headers block. */
4327 lua_pushlstring(L, tmp->str, tmp->len);
4328
4329 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4330}
4331
4332/*
4333 *
4334 *
4335 * Class HTTP
4336 *
4337 *
4338 */
4339
4340/* Returns a struct hlua_txn if the stack entry "ud" is
4341 * a class stream, otherwise it throws an error.
4342 */
4343__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4344{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004345 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004346}
4347
4348/* This function creates and push in the stack a HTTP object
4349 * according with a current TXN.
4350 */
4351static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4352{
4353 struct hlua_txn *htxn;
4354
4355 /* Check stack size. */
4356 if (!lua_checkstack(L, 3))
4357 return 0;
4358
4359 /* Create the object: obj[0] = userdata.
4360 * Note that the base of the Converters object is the
4361 * same than the TXN object.
4362 */
4363 lua_newtable(L);
4364 htxn = lua_newuserdata(L, sizeof(*htxn));
4365 lua_rawseti(L, -2, 0);
4366
4367 htxn->s = txn->s;
4368 htxn->p = txn->p;
4369
4370 /* Pop a class stream metatable and affect it to the table. */
4371 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4372 lua_setmetatable(L, -2);
4373
4374 return 1;
4375}
4376
4377/* This function creates ans returns an array of HTTP headers.
4378 * This function does not fails. It is used as wrapper with the
4379 * 2 following functions.
4380 */
4381__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4382{
4383 const char *cur_ptr, *cur_next, *p;
4384 int old_idx, cur_idx;
4385 struct hdr_idx_elem *cur_hdr;
4386 const char *hn, *hv;
4387 int hnl, hvl;
4388 int type;
4389 const char *in;
4390 char *out;
4391 int len;
4392
4393 /* Create the table. */
4394 lua_newtable(L);
4395
4396 if (!htxn->s->txn)
4397 return 1;
4398
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004399 /* Check if a valid response is parsed */
4400 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4401 return 1;
4402
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004403 /* Build array of headers. */
4404 old_idx = 0;
4405 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4406
4407 while (1) {
4408 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4409 if (!cur_idx)
4410 break;
4411 old_idx = cur_idx;
4412
4413 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4414 cur_ptr = cur_next;
4415 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4416
4417 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4418 * and the next header starts at cur_next. We'll check
4419 * this header in the list as well as against the default
4420 * rule.
4421 */
4422
4423 /* look for ': *'. */
4424 hn = cur_ptr;
4425 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4426 if (p >= cur_ptr+cur_hdr->len)
4427 continue;
4428 hnl = p - hn;
4429 p++;
4430 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4431 p++;
4432 if (p >= cur_ptr+cur_hdr->len)
4433 continue;
4434 hv = p;
4435 hvl = cur_ptr+cur_hdr->len-p;
4436
4437 /* Lowercase the key. Don't check the size of trash, it have
4438 * the size of one buffer and the input data contains in one
4439 * buffer.
4440 */
4441 out = trash.str;
4442 for (in=hn; in<hn+hnl; in++, out++)
4443 *out = tolower(*in);
4444 *out = '\0';
4445
4446 /* Check for existing entry:
4447 * assume that the table is on the top of the stack, and
4448 * push the key in the stack, the function lua_gettable()
4449 * perform the lookup.
4450 */
4451 lua_pushlstring(L, trash.str, hnl);
4452 lua_gettable(L, -2);
4453 type = lua_type(L, -1);
4454
4455 switch (type) {
4456 case LUA_TNIL:
4457 /* Table not found, create it. */
4458 lua_pop(L, 1); /* remove the nil value. */
4459 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4460 lua_newtable(L); /* create and push empty table. */
4461 lua_pushlstring(L, hv, hvl); /* push header value. */
4462 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4463 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4464 break;
4465
4466 case LUA_TTABLE:
4467 /* Entry found: push the value in the table. */
4468 len = lua_rawlen(L, -1);
4469 lua_pushlstring(L, hv, hvl); /* push header value. */
4470 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4471 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4472 break;
4473
4474 default:
4475 /* Other cases are errors. */
4476 hlua_pusherror(L, "internal error during the parsing of headers.");
4477 WILL_LJMP(lua_error(L));
4478 }
4479 }
4480
4481 return 1;
4482}
4483
4484__LJMP static int hlua_http_req_get_headers(lua_State *L)
4485{
4486 struct hlua_txn *htxn;
4487
4488 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4489 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4490
4491 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4492}
4493
4494__LJMP static int hlua_http_res_get_headers(lua_State *L)
4495{
4496 struct hlua_txn *htxn;
4497
4498 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4499 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4500
4501 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4502}
4503
4504/* This function replace full header, or just a value in
4505 * the request or in the response. It is a wrapper fir the
4506 * 4 following functions.
4507 */
4508__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4509 struct http_msg *msg, int action)
4510{
4511 size_t name_len;
4512 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4513 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4514 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4515 struct my_regex re;
4516
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004517 /* Check if a valid response is parsed */
4518 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4519 return 0;
4520
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004521 if (!regex_comp(reg, &re, 1, 1, NULL))
4522 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4523
4524 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4525 regex_free(&re);
4526 return 0;
4527}
4528
4529__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4530{
4531 struct hlua_txn *htxn;
4532
4533 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4534 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4535
4536 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4537}
4538
4539__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4540{
4541 struct hlua_txn *htxn;
4542
4543 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4544 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4545
4546 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4547}
4548
4549__LJMP static int hlua_http_req_rep_val(lua_State *L)
4550{
4551 struct hlua_txn *htxn;
4552
4553 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4554 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4555
4556 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4557}
4558
4559__LJMP static int hlua_http_res_rep_val(lua_State *L)
4560{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004561 struct hlua_txn *htxn;
4562
4563 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4564 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4565
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004566 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004567}
4568
4569/* This function deletes all the occurences of an header.
4570 * It is a wrapper for the 2 following functions.
4571 */
4572__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4573{
4574 size_t len;
4575 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4576 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004577 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004578
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004579 /* Check if a valid response is parsed */
4580 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4581 return 0;
4582
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004583 ctx.idx = 0;
4584 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4585 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4586 return 0;
4587}
4588
4589__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4590{
4591 struct hlua_txn *htxn;
4592
4593 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4594 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4595
Willy Tarreaueee5b512015-04-03 23:46:31 +02004596 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004597}
4598
4599__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4600{
4601 struct hlua_txn *htxn;
4602
4603 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4604 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4605
Willy Tarreaueee5b512015-04-03 23:46:31 +02004606 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004607}
4608
4609/* This function adds an header. It is a wrapper used by
4610 * the 2 following functions.
4611 */
4612__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4613{
4614 size_t name_len;
4615 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4616 size_t value_len;
4617 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4618 char *p;
4619
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004620 /* Check if a valid message is parsed */
4621 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4622 return 0;
4623
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004624 /* Check length. */
4625 trash.len = value_len + name_len + 2;
4626 if (trash.len > trash.size)
4627 return 0;
4628
4629 /* Creates the header string. */
4630 p = trash.str;
4631 memcpy(p, name, name_len);
4632 p += name_len;
4633 *p = ':';
4634 p++;
4635 *p = ' ';
4636 p++;
4637 memcpy(p, value, value_len);
4638
Willy Tarreaueee5b512015-04-03 23:46:31 +02004639 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004640 trash.str, trash.len) != 0);
4641
4642 return 0;
4643}
4644
4645__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4646{
4647 struct hlua_txn *htxn;
4648
4649 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4650 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4651
Willy Tarreaueee5b512015-04-03 23:46:31 +02004652 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004653}
4654
4655__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4656{
4657 struct hlua_txn *htxn;
4658
4659 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4660 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4661
Willy Tarreaueee5b512015-04-03 23:46:31 +02004662 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004663}
4664
4665static int hlua_http_req_set_hdr(lua_State *L)
4666{
4667 struct hlua_txn *htxn;
4668
4669 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4670 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4671
Willy Tarreaueee5b512015-04-03 23:46:31 +02004672 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4673 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004674}
4675
4676static int hlua_http_res_set_hdr(lua_State *L)
4677{
4678 struct hlua_txn *htxn;
4679
4680 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4681 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4682
Willy Tarreaueee5b512015-04-03 23:46:31 +02004683 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4684 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004685}
4686
4687/* This function set the method. */
4688static int hlua_http_req_set_meth(lua_State *L)
4689{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004690 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004691 size_t name_len;
4692 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004693
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004694 /* Check if a valid request is parsed */
4695 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4696 lua_pushboolean(L, 0);
4697 return 1;
4698 }
4699
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004700 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004701 return 1;
4702}
4703
4704/* This function set the method. */
4705static int hlua_http_req_set_path(lua_State *L)
4706{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004707 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004708 size_t name_len;
4709 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004710
4711 /* Check if a valid request is parsed */
4712 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4713 lua_pushboolean(L, 0);
4714 return 1;
4715 }
4716
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004717 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004718 return 1;
4719}
4720
4721/* This function set the query-string. */
4722static int hlua_http_req_set_query(lua_State *L)
4723{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004724 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004725 size_t name_len;
4726 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004727
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004728 /* Check if a valid request is parsed */
4729 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4730 lua_pushboolean(L, 0);
4731 return 1;
4732 }
4733
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004734 /* Check length. */
4735 if (name_len > trash.size - 1) {
4736 lua_pushboolean(L, 0);
4737 return 1;
4738 }
4739
4740 /* Add the mark question as prefix. */
4741 chunk_reset(&trash);
4742 trash.str[trash.len++] = '?';
4743 memcpy(trash.str + trash.len, name, name_len);
4744 trash.len += name_len;
4745
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004746 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004747 return 1;
4748}
4749
4750/* This function set the uri. */
4751static int hlua_http_req_set_uri(lua_State *L)
4752{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004753 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004754 size_t name_len;
4755 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004756
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004757 /* Check if a valid request is parsed */
4758 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4759 lua_pushboolean(L, 0);
4760 return 1;
4761 }
4762
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004763 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004764 return 1;
4765}
4766
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004767/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004768static int hlua_http_res_set_status(lua_State *L)
4769{
4770 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4771 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004772 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004773
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004774 /* Check if a valid response is parsed */
4775 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4776 return 0;
4777
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004778 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004779 return 0;
4780}
4781
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004782/*
4783 *
4784 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004785 * Class TXN
4786 *
4787 *
4788 */
4789
4790/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004791 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004792 */
4793__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4794{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004795 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004796}
4797
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004798__LJMP static int hlua_set_var(lua_State *L)
4799{
4800 struct hlua_txn *htxn;
4801 const char *name;
4802 size_t len;
4803 struct sample smp;
4804
4805 MAY_LJMP(check_args(L, 3, "set_var"));
4806
4807 /* It is useles to retrieve the stream, but this function
4808 * runs only in a stream context.
4809 */
4810 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4811 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4812
4813 /* Converts the third argument in a sample. */
4814 hlua_lua2smp(L, 3, &smp);
4815
4816 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01004817 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004818 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004819 return 0;
4820}
4821
Christopher Faulet85d79c92016-11-09 16:54:56 +01004822__LJMP static int hlua_unset_var(lua_State *L)
4823{
4824 struct hlua_txn *htxn;
4825 const char *name;
4826 size_t len;
4827 struct sample smp;
4828
4829 MAY_LJMP(check_args(L, 2, "unset_var"));
4830
4831 /* It is useles to retrieve the stream, but this function
4832 * runs only in a stream context.
4833 */
4834 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4835 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4836
4837 /* Unset the variable. */
4838 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
4839 vars_unset_by_name(name, len, &smp);
4840 return 0;
4841}
4842
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004843__LJMP static int hlua_get_var(lua_State *L)
4844{
4845 struct hlua_txn *htxn;
4846 const char *name;
4847 size_t len;
4848 struct sample smp;
4849
4850 MAY_LJMP(check_args(L, 2, "get_var"));
4851
4852 /* It is useles to retrieve the stream, but this function
4853 * runs only in a stream context.
4854 */
4855 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4856 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4857
Willy Tarreau7560dd42016-03-10 16:28:58 +01004858 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004859 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004860 lua_pushnil(L);
4861 return 1;
4862 }
4863
4864 return hlua_smp2lua(L, &smp);
4865}
4866
Willy Tarreau59551662015-03-10 14:23:13 +01004867__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004868{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004869 struct hlua *hlua;
4870
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004871 MAY_LJMP(check_args(L, 2, "set_priv"));
4872
Willy Tarreau87b09662015-04-03 00:22:06 +02004873 /* It is useles to retrieve the stream, but this function
4874 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004875 */
4876 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004877 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004878
4879 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004880 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004881
4882 /* Get and store new value. */
4883 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4884 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4885
4886 return 0;
4887}
4888
Willy Tarreau59551662015-03-10 14:23:13 +01004889__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004890{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004891 struct hlua *hlua;
4892
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004893 MAY_LJMP(check_args(L, 1, "get_priv"));
4894
Willy Tarreau87b09662015-04-03 00:22:06 +02004895 /* It is useles to retrieve the stream, but this function
4896 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004897 */
4898 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004899 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004900
4901 /* Push configuration index in the stack. */
4902 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4903
4904 return 1;
4905}
4906
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004907/* Create stack entry containing a class TXN. This function
4908 * return 0 if the stack does not contains free slots,
4909 * otherwise it returns 1.
4910 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004911static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004912{
Willy Tarreaude491382015-04-06 11:04:28 +02004913 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004914
4915 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004916 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004917 return 0;
4918
4919 /* NOTE: The allocation never fails. The failure
4920 * throw an error, and the function never returns.
4921 * if the throw is not avalaible, the process is aborted.
4922 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004923 /* Create the object: obj[0] = userdata. */
4924 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004925 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004926 lua_rawseti(L, -2, 0);
4927
Willy Tarreaude491382015-04-06 11:04:28 +02004928 htxn->s = s;
4929 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004930 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004931 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004932
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004933 /* Create the "f" field that contains a list of fetches. */
4934 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004935 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004936 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004937 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004938
4939 /* Create the "sf" field that contains a list of stringsafe fetches. */
4940 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004941 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004942 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004943 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004944
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004945 /* Create the "c" field that contains a list of converters. */
4946 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004947 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004948 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004949 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004950
4951 /* Create the "sc" field that contains a list of stringsafe converters. */
4952 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004953 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004954 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004955 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004956
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004957 /* Create the "req" field that contains the request channel object. */
4958 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004959 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004960 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004961 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004962
4963 /* Create the "res" field that contains the response channel object. */
4964 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004965 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004966 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004967 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004968
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004969 /* Creates the HTTP object is the current proxy allows http. */
4970 lua_pushstring(L, "http");
4971 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02004972 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004973 return 0;
4974 }
4975 else
4976 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004977 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004978
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004979 /* Pop a class sesison metatable and affect it to the userdata. */
4980 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
4981 lua_setmetatable(L, -2);
4982
4983 return 1;
4984}
4985
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004986__LJMP static int hlua_txn_deflog(lua_State *L)
4987{
4988 const char *msg;
4989 struct hlua_txn *htxn;
4990
4991 MAY_LJMP(check_args(L, 2, "deflog"));
4992 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4993 msg = MAY_LJMP(luaL_checkstring(L, 2));
4994
4995 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
4996 return 0;
4997}
4998
4999__LJMP static int hlua_txn_log(lua_State *L)
5000{
5001 int level;
5002 const char *msg;
5003 struct hlua_txn *htxn;
5004
5005 MAY_LJMP(check_args(L, 3, "log"));
5006 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5007 level = MAY_LJMP(luaL_checkinteger(L, 2));
5008 msg = MAY_LJMP(luaL_checkstring(L, 3));
5009
5010 if (level < 0 || level >= NB_LOG_LEVELS)
5011 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5012
5013 hlua_sendlog(htxn->s->be, level, msg);
5014 return 0;
5015}
5016
5017__LJMP static int hlua_txn_log_debug(lua_State *L)
5018{
5019 const char *msg;
5020 struct hlua_txn *htxn;
5021
5022 MAY_LJMP(check_args(L, 2, "Debug"));
5023 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5024 msg = MAY_LJMP(luaL_checkstring(L, 2));
5025 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5026 return 0;
5027}
5028
5029__LJMP static int hlua_txn_log_info(lua_State *L)
5030{
5031 const char *msg;
5032 struct hlua_txn *htxn;
5033
5034 MAY_LJMP(check_args(L, 2, "Info"));
5035 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5036 msg = MAY_LJMP(luaL_checkstring(L, 2));
5037 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5038 return 0;
5039}
5040
5041__LJMP static int hlua_txn_log_warning(lua_State *L)
5042{
5043 const char *msg;
5044 struct hlua_txn *htxn;
5045
5046 MAY_LJMP(check_args(L, 2, "Warning"));
5047 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5048 msg = MAY_LJMP(luaL_checkstring(L, 2));
5049 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5050 return 0;
5051}
5052
5053__LJMP static int hlua_txn_log_alert(lua_State *L)
5054{
5055 const char *msg;
5056 struct hlua_txn *htxn;
5057
5058 MAY_LJMP(check_args(L, 2, "Alert"));
5059 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5060 msg = MAY_LJMP(luaL_checkstring(L, 2));
5061 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5062 return 0;
5063}
5064
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005065__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5066{
5067 struct hlua_txn *htxn;
5068 int ll;
5069
5070 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5071 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5072 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5073
5074 if (ll < 0 || ll > 7)
5075 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5076
5077 htxn->s->logs.level = ll;
5078 return 0;
5079}
5080
5081__LJMP static int hlua_txn_set_tos(lua_State *L)
5082{
5083 struct hlua_txn *htxn;
5084 struct connection *cli_conn;
5085 int tos;
5086
5087 MAY_LJMP(check_args(L, 2, "set_tos"));
5088 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5089 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5090
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005091 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Vincent Bernat6e615892016-05-18 16:17:44 +02005092 inet_set_tos(cli_conn->t.sock.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005093
5094 return 0;
5095}
5096
5097__LJMP static int hlua_txn_set_mark(lua_State *L)
5098{
5099#ifdef SO_MARK
5100 struct hlua_txn *htxn;
5101 struct connection *cli_conn;
5102 int mark;
5103
5104 MAY_LJMP(check_args(L, 2, "set_mark"));
5105 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5106 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5107
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005108 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02005109 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005110#endif
5111 return 0;
5112}
5113
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005114/* This function is an Lua binding that send pending data
5115 * to the client, and close the stream interface.
5116 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005117__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005118{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005119 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005120 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005121 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005122
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005123 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005124 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005125 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005126
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005127 /* If the flags NOTERM is set, we cannot terminate the http
5128 * session, so we just end the execution of the current
5129 * lua code.
5130 */
5131 if (htxn->flags & HLUA_TXN_NOTERM) {
5132 WILL_LJMP(hlua_done(L));
5133 return 0;
5134 }
5135
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005136 ic = &htxn->s->req;
5137 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005138
Willy Tarreau630ef452015-08-28 10:06:15 +02005139 if (htxn->s->txn) {
5140 /* HTTP mode, let's stay in sync with the stream */
5141 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
5142 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5143 htxn->s->txn->req.sov = 0;
5144 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5145 oc->analysers = AN_RES_HTTP_XFER_BODY;
5146 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5147 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5148
Willy Tarreau630ef452015-08-28 10:06:15 +02005149 /* Note that if we want to support keep-alive, we need
5150 * to bypass the close/shutr_now calls below, but that
5151 * may only be done if the HTTP request was already
5152 * processed and the connection header is known (ie
5153 * not during TCP rules).
5154 */
5155 }
5156
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005157 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005158 channel_abort(ic);
5159 channel_auto_close(ic);
5160 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005161
5162 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005163 channel_auto_read(oc);
5164 channel_auto_close(oc);
5165 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005166
Willy Tarreau0458b082015-08-28 09:40:04 +02005167 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005168
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005169 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005170 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005171 return 0;
5172}
5173
5174__LJMP static int hlua_log(lua_State *L)
5175{
5176 int level;
5177 const char *msg;
5178
5179 MAY_LJMP(check_args(L, 2, "log"));
5180 level = MAY_LJMP(luaL_checkinteger(L, 1));
5181 msg = MAY_LJMP(luaL_checkstring(L, 2));
5182
5183 if (level < 0 || level >= NB_LOG_LEVELS)
5184 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5185
5186 hlua_sendlog(NULL, level, msg);
5187 return 0;
5188}
5189
5190__LJMP static int hlua_log_debug(lua_State *L)
5191{
5192 const char *msg;
5193
5194 MAY_LJMP(check_args(L, 1, "debug"));
5195 msg = MAY_LJMP(luaL_checkstring(L, 1));
5196 hlua_sendlog(NULL, LOG_DEBUG, msg);
5197 return 0;
5198}
5199
5200__LJMP static int hlua_log_info(lua_State *L)
5201{
5202 const char *msg;
5203
5204 MAY_LJMP(check_args(L, 1, "info"));
5205 msg = MAY_LJMP(luaL_checkstring(L, 1));
5206 hlua_sendlog(NULL, LOG_INFO, msg);
5207 return 0;
5208}
5209
5210__LJMP static int hlua_log_warning(lua_State *L)
5211{
5212 const char *msg;
5213
5214 MAY_LJMP(check_args(L, 1, "warning"));
5215 msg = MAY_LJMP(luaL_checkstring(L, 1));
5216 hlua_sendlog(NULL, LOG_WARNING, msg);
5217 return 0;
5218}
5219
5220__LJMP static int hlua_log_alert(lua_State *L)
5221{
5222 const char *msg;
5223
5224 MAY_LJMP(check_args(L, 1, "alert"));
5225 msg = MAY_LJMP(luaL_checkstring(L, 1));
5226 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005227 return 0;
5228}
5229
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005230__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005231{
5232 int wakeup_ms = lua_tointeger(L, -1);
5233 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005234 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005235 return 0;
5236}
5237
5238__LJMP static int hlua_sleep(lua_State *L)
5239{
5240 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005241 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005242
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005243 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005244
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005245 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005246 wakeup_ms = tick_add(now_ms, delay);
5247 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005248
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005249 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5250 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005251}
5252
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005253__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005254{
5255 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005256 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005257
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005258 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005259
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005260 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005261 wakeup_ms = tick_add(now_ms, delay);
5262 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005263
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005264 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5265 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005266}
5267
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005268/* This functionis an LUA binding. it permits to give back
5269 * the hand at the HAProxy scheduler. It is used when the
5270 * LUA processing consumes a lot of time.
5271 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005272__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005273{
5274 return 0;
5275}
5276
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005277__LJMP static int hlua_yield(lua_State *L)
5278{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005279 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5280 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005281}
5282
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005283/* This function change the nice of the currently executed
5284 * task. It is used set low or high priority at the current
5285 * task.
5286 */
Willy Tarreau59551662015-03-10 14:23:13 +01005287__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005288{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005289 struct hlua *hlua;
5290 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005291
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005292 MAY_LJMP(check_args(L, 1, "set_nice"));
5293 hlua = hlua_gethlua(L);
5294 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005295
5296 /* If he task is not set, I'm in a start mode. */
5297 if (!hlua || !hlua->task)
5298 return 0;
5299
5300 if (nice < -1024)
5301 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005302 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005303 nice = 1024;
5304
5305 hlua->task->nice = nice;
5306 return 0;
5307}
5308
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005309/* This function is used as a calback of a task. It is called by the
5310 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5311 * return an E_AGAIN signal, the emmiter of this signal must set a
5312 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005313 *
5314 * Task wrapper are longjmp safe because the only one Lua code
5315 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005316 */
5317static struct task *hlua_process_task(struct task *task)
5318{
5319 struct hlua *hlua = task->context;
5320 enum hlua_exec status;
5321
5322 /* We need to remove the task from the wait queue before executing
5323 * the Lua code because we don't know if it needs to wait for
5324 * another timer or not in the case of E_AGAIN.
5325 */
5326 task_delete(task);
5327
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005328 /* If it is the first call to the task, we must initialize the
5329 * execution timeouts.
5330 */
5331 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005332 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005333
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005334 /* Execute the Lua code. */
5335 status = hlua_ctx_resume(hlua, 1);
5336
5337 switch (status) {
5338 /* finished or yield */
5339 case HLUA_E_OK:
5340 hlua_ctx_destroy(hlua);
5341 task_delete(task);
5342 task_free(task);
5343 break;
5344
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005345 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5346 if (hlua->wake_time != TICK_ETERNITY)
5347 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005348 break;
5349
5350 /* finished with error. */
5351 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005352 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005353 hlua_ctx_destroy(hlua);
5354 task_delete(task);
5355 task_free(task);
5356 break;
5357
5358 case HLUA_E_ERR:
5359 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005360 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005361 hlua_ctx_destroy(hlua);
5362 task_delete(task);
5363 task_free(task);
5364 break;
5365 }
5366 return NULL;
5367}
5368
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005369/* This function is an LUA binding that register LUA function to be
5370 * executed after the HAProxy configuration parsing and before the
5371 * HAProxy scheduler starts. This function expect only one LUA
5372 * argument that is a function. This function returns nothing, but
5373 * throws if an error is encountered.
5374 */
5375__LJMP static int hlua_register_init(lua_State *L)
5376{
5377 struct hlua_init_function *init;
5378 int ref;
5379
5380 MAY_LJMP(check_args(L, 1, "register_init"));
5381
5382 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5383
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005384 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005385 if (!init)
5386 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5387
5388 init->function_ref = ref;
5389 LIST_ADDQ(&hlua_init_functions, &init->l);
5390 return 0;
5391}
5392
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005393/* This functio is an LUA binding. It permits to register a task
5394 * executed in parallel of the main HAroxy activity. The task is
5395 * created and it is set in the HAProxy scheduler. It can be called
5396 * from the "init" section, "post init" or during the runtime.
5397 *
5398 * Lua prototype:
5399 *
5400 * <none> core.register_task(<function>)
5401 */
5402static int hlua_register_task(lua_State *L)
5403{
5404 struct hlua *hlua;
5405 struct task *task;
5406 int ref;
5407
5408 MAY_LJMP(check_args(L, 1, "register_task"));
5409
5410 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5411
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005412 hlua = pool_alloc2(pool2_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005413 if (!hlua)
5414 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5415
5416 task = task_new();
5417 task->context = hlua;
5418 task->process = hlua_process_task;
5419
5420 if (!hlua_ctx_init(hlua, task))
5421 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5422
5423 /* Restore the function in the stack. */
5424 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5425 hlua->nargs = 0;
5426
5427 /* Schedule task. */
5428 task_schedule(task, now_ms);
5429
5430 return 0;
5431}
5432
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005433/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5434 * doesn't allow "yield" functions because the HAProxy engine cannot
5435 * resume converters.
5436 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005437static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005438{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005439 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005440 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005441 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005442
Willy Tarreaube508f12016-03-10 11:47:01 +01005443 if (!stream)
5444 return 0;
5445
Willy Tarreau87b09662015-04-03 00:22:06 +02005446 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005447 * Lua context can be not initialized. This behavior
5448 * permits to save performances because a systematic
5449 * Lua initialization cause 5% performances loss.
5450 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005451 if (!stream->hlua) {
5452 stream->hlua = pool_alloc2(pool2_hlua);
5453 if (!stream->hlua) {
5454 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5455 return 0;
5456 }
5457 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5458 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5459 return 0;
5460 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005461 }
5462
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005463 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005464 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005465
5466 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005467 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5468 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5469 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005470 else
5471 error = "critical error";
5472 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005473 return 0;
5474 }
5475
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005476 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005477 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005478 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005479 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005480 return 0;
5481 }
5482
5483 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005484 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005485
5486 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005487 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005488 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005489 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005490 return 0;
5491 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005492 hlua_smp2lua(stream->hlua->T, smp);
5493 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005494
5495 /* push keywords in the stack. */
5496 if (arg_p) {
5497 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005498 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005499 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005500 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005501 return 0;
5502 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005503 hlua_arg2lua(stream->hlua->T, arg_p);
5504 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005505 }
5506 }
5507
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005508 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005509 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005510
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005511 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005512 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005513 }
5514
5515 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005516 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005517 /* finished. */
5518 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005519 /* If the stack is empty, the function fails. */
5520 if (lua_gettop(stream->hlua->T) <= 0)
5521 return 0;
5522
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005523 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005524 hlua_lua2smp(stream->hlua->T, -1, smp);
5525 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005526 return 1;
5527
5528 /* yield. */
5529 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005530 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005531 return 0;
5532
5533 /* finished with error. */
5534 case HLUA_E_ERRMSG:
5535 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005536 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005537 fcn->name, lua_tostring(stream->hlua->T, -1));
5538 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005539 return 0;
5540
5541 case HLUA_E_ERR:
5542 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005543 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005544
5545 default:
5546 return 0;
5547 }
5548}
5549
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005550/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5551 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005552 * resume sample-fetches. This function will be called by the sample
5553 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005554 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005555static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5556 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005557{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005558 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005559 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005560 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005561 const struct chunk msg = { .len = 0 };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005562
Willy Tarreaube508f12016-03-10 11:47:01 +01005563 if (!stream)
5564 return 0;
5565
Willy Tarreau87b09662015-04-03 00:22:06 +02005566 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005567 * Lua context can be not initialized. This behavior
5568 * permits to save performances because a systematic
5569 * Lua initialization cause 5% performances loss.
5570 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005571 if (!stream->hlua) {
5572 stream->hlua = pool_alloc2(pool2_hlua);
5573 if (!stream->hlua) {
5574 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5575 return 0;
5576 }
5577 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5578 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5579 return 0;
5580 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005581 }
5582
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005583 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005584
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005585 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005586 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005587
5588 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005589 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5590 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5591 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005592 else
5593 error = "critical error";
5594 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005595 return 0;
5596 }
5597
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005598 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005599 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005600 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005601 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005602 return 0;
5603 }
5604
5605 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005606 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005607
5608 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005609 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005610 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005611 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005612 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005613 return 0;
5614 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005615 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005616
5617 /* push keywords in the stack. */
5618 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5619 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005620 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005621 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005622 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005623 return 0;
5624 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005625 hlua_arg2lua(stream->hlua->T, arg_p);
5626 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005627 }
5628
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005629 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005630 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005631
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005632 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005633 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005634 }
5635
5636 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005637 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005638 /* finished. */
5639 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005640 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005641 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005642 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005643 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005644 /* If the stack is empty, the function fails. */
5645 if (lua_gettop(stream->hlua->T) <= 0)
5646 return 0;
5647
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005648 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005649 hlua_lua2smp(stream->hlua->T, -1, smp);
5650 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005651
5652 /* Set the end of execution flag. */
5653 smp->flags &= ~SMP_F_MAY_CHANGE;
5654 return 1;
5655
5656 /* yield. */
5657 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005658 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005659 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005660 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005661 return 0;
5662
5663 /* finished with error. */
5664 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005665 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005666 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005667 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005668 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005669 fcn->name, lua_tostring(stream->hlua->T, -1));
5670 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005671 return 0;
5672
5673 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005674 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005675 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005676 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005677 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005678
5679 default:
5680 return 0;
5681 }
5682}
5683
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005684/* This function is an LUA binding used for registering
5685 * "sample-conv" functions. It expects a converter name used
5686 * in the haproxy configuration file, and an LUA function.
5687 */
5688__LJMP static int hlua_register_converters(lua_State *L)
5689{
5690 struct sample_conv_kw_list *sck;
5691 const char *name;
5692 int ref;
5693 int len;
5694 struct hlua_function *fcn;
5695
5696 MAY_LJMP(check_args(L, 2, "register_converters"));
5697
5698 /* First argument : converter name. */
5699 name = MAY_LJMP(luaL_checkstring(L, 1));
5700
5701 /* Second argument : lua function. */
5702 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5703
5704 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005705 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005706 if (!sck)
5707 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005708 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005709 if (!fcn)
5710 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5711
5712 /* Fill fcn. */
5713 fcn->name = strdup(name);
5714 if (!fcn->name)
5715 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5716 fcn->function_ref = ref;
5717
5718 /* List head */
5719 sck->list.n = sck->list.p = NULL;
5720
5721 /* converter keyword. */
5722 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005723 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005724 if (!sck->kw[0].kw)
5725 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5726
5727 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5728 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005729 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 +01005730 sck->kw[0].val_args = NULL;
5731 sck->kw[0].in_type = SMP_T_STR;
5732 sck->kw[0].out_type = SMP_T_STR;
5733 sck->kw[0].private = fcn;
5734
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005735 /* Register this new converter */
5736 sample_register_convs(sck);
5737
5738 return 0;
5739}
5740
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005741/* This fucntion is an LUA binding used for registering
5742 * "sample-fetch" functions. It expects a converter name used
5743 * in the haproxy configuration file, and an LUA function.
5744 */
5745__LJMP static int hlua_register_fetches(lua_State *L)
5746{
5747 const char *name;
5748 int ref;
5749 int len;
5750 struct sample_fetch_kw_list *sfk;
5751 struct hlua_function *fcn;
5752
5753 MAY_LJMP(check_args(L, 2, "register_fetches"));
5754
5755 /* First argument : sample-fetch name. */
5756 name = MAY_LJMP(luaL_checkstring(L, 1));
5757
5758 /* Second argument : lua function. */
5759 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5760
5761 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005762 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005763 if (!sfk)
5764 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005765 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005766 if (!fcn)
5767 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5768
5769 /* Fill fcn. */
5770 fcn->name = strdup(name);
5771 if (!fcn->name)
5772 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5773 fcn->function_ref = ref;
5774
5775 /* List head */
5776 sfk->list.n = sfk->list.p = NULL;
5777
5778 /* sample-fetch keyword. */
5779 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005780 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005781 if (!sfk->kw[0].kw)
5782 return luaL_error(L, "lua out of memory error.");
5783
5784 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5785 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005786 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 +01005787 sfk->kw[0].val_args = NULL;
5788 sfk->kw[0].out_type = SMP_T_STR;
5789 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5790 sfk->kw[0].val = 0;
5791 sfk->kw[0].private = fcn;
5792
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005793 /* Register this new fetch. */
5794 sample_register_fetches(sfk);
5795
5796 return 0;
5797}
5798
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005799/* This function is a wrapper to execute each LUA function declared
5800 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005801 * return ACT_RET_CONT if the processing is finished (with or without
5802 * error) and return ACT_RET_YIELD if the function must be called again
5803 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005804 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005805static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005806 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005807{
5808 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005809 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005810 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005811 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005812 const struct chunk msg = { .len = 0 };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005813
5814 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01005815 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
5816 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
5817 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
5818 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005819 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005820 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005821 return ACT_RET_CONT;
5822 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005823
Willy Tarreau87b09662015-04-03 00:22:06 +02005824 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005825 * Lua context can be not initialized. This behavior
5826 * permits to save performances because a systematic
5827 * Lua initialization cause 5% performances loss.
5828 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005829 if (!s->hlua) {
5830 s->hlua = pool_alloc2(pool2_hlua);
5831 if (!s->hlua) {
5832 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
5833 rule->arg.hlua_rule->fcn.name);
5834 return ACT_RET_CONT;
5835 }
5836 if (!hlua_ctx_init(s->hlua, s->task)) {
5837 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
5838 rule->arg.hlua_rule->fcn.name);
5839 return ACT_RET_CONT;
5840 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005841 }
5842
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005843 consistency_set(s, dir, &s->hlua->cons);
5844
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005845 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005846 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005847
5848 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005849 if (!SET_SAFE_LJMP(s->hlua->T)) {
5850 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
5851 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005852 else
5853 error = "critical error";
5854 SEND_ERR(px, "Lua function '%s': %s.\n",
5855 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005856 return ACT_RET_CONT;
5857 }
5858
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005859 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005860 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005861 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005862 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005863 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005864 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005865 }
5866
5867 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005868 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005869
Willy Tarreau87b09662015-04-03 00:22:06 +02005870 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005871 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005872 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005873 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005874 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005875 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005876 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005877 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005878
5879 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005880 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005881 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005882 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005883 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005884 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005885 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005886 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005887 lua_pushstring(s->hlua->T, *arg);
5888 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005889 }
5890
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005891 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005892 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005893
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005894 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005895 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005896 }
5897
5898 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005899 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005900 /* finished. */
5901 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005902 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005903 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005904 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005905 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005906 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005907 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005908 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005909
5910 /* yield. */
5911 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005912 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005913 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005914 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005915 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005916 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005917 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005918 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005919 /* Some actions can be wake up when a "write" event
5920 * is detected on a response channel. This is useful
5921 * only for actions targetted on the requests.
5922 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005923 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005924 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005925 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005926 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005927 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005928 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005929 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005930 /* We can quit the fcuntion without consistency check
5931 * because HAProxy is not able to manipulate data, it
5932 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005933 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005934
5935 /* finished with error. */
5936 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005937 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005938 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005939 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005940 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005941 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005942 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005943 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
5944 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005945 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005946
5947 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005948 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005949 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005950 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005951 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005952 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005953 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005954 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005955
5956 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005957 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005958 }
5959}
5960
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005961struct task *hlua_applet_wakeup(struct task *t)
5962{
5963 struct appctx *ctx = t->context;
5964 struct stream_interface *si = ctx->owner;
5965
5966 /* If the applet is wake up without any expected work, the sheduler
5967 * remove it from the run queue. This flag indicate that the applet
5968 * is waiting for write. If the buffer is full, the main processing
5969 * will send some data and after call the applet, otherwise it call
5970 * the applet ASAP.
5971 */
5972 si_applet_cant_put(si);
5973 appctx_wakeup(ctx);
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02005974 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005975}
5976
5977static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5978{
5979 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01005980 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005981 struct task *task;
5982 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005983 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005984
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01005985 hlua = pool_alloc2(pool2_hlua);
5986 if (!hlua) {
5987 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5988 ctx->rule->arg.hlua_rule->fcn.name);
5989 return 0;
5990 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005991 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01005992 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005993 ctx->ctx.hlua_apptcp.flags = 0;
5994
5995 /* Create task used by signal to wakeup applets. */
5996 task = task_new();
5997 if (!task) {
5998 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5999 ctx->rule->arg.hlua_rule->fcn.name);
6000 return 0;
6001 }
6002 task->nice = 0;
6003 task->context = ctx;
6004 task->process = hlua_applet_wakeup;
6005 ctx->ctx.hlua_apptcp.task = task;
6006
6007 /* In the execution wrappers linked with a stream, the
6008 * Lua context can be not initialized. This behavior
6009 * permits to save performances because a systematic
6010 * Lua initialization cause 5% performances loss.
6011 */
6012 if (!hlua_ctx_init(hlua, task)) {
6013 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6014 ctx->rule->arg.hlua_rule->fcn.name);
6015 return 0;
6016 }
6017
6018 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006019 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006020
6021 /* The following Lua calls can fail. */
6022 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006023 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6024 error = lua_tostring(hlua->T, -1);
6025 else
6026 error = "critical error";
6027 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6028 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006029 RESET_SAFE_LJMP(hlua->T);
6030 return 0;
6031 }
6032
6033 /* Check stack available size. */
6034 if (!lua_checkstack(hlua->T, 1)) {
6035 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6036 ctx->rule->arg.hlua_rule->fcn.name);
6037 RESET_SAFE_LJMP(hlua->T);
6038 return 0;
6039 }
6040
6041 /* Restore the function in the stack. */
6042 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6043
6044 /* Create and and push object stream in the stack. */
6045 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6046 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6047 ctx->rule->arg.hlua_rule->fcn.name);
6048 RESET_SAFE_LJMP(hlua->T);
6049 return 0;
6050 }
6051 hlua->nargs = 1;
6052
6053 /* push keywords in the stack. */
6054 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6055 if (!lua_checkstack(hlua->T, 1)) {
6056 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6057 ctx->rule->arg.hlua_rule->fcn.name);
6058 RESET_SAFE_LJMP(hlua->T);
6059 return 0;
6060 }
6061 lua_pushstring(hlua->T, *arg);
6062 hlua->nargs++;
6063 }
6064
6065 RESET_SAFE_LJMP(hlua->T);
6066
6067 /* Wakeup the applet ASAP. */
6068 si_applet_cant_get(si);
6069 si_applet_cant_put(si);
6070
6071 return 1;
6072}
6073
6074static void hlua_applet_tcp_fct(struct appctx *ctx)
6075{
6076 struct stream_interface *si = ctx->owner;
6077 struct stream *strm = si_strm(si);
6078 struct channel *res = si_ic(si);
6079 struct act_rule *rule = ctx->rule;
6080 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006081 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006082
6083 /* The applet execution is already done. */
6084 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
6085 return;
6086
6087 /* If the stream is disconnect or closed, ldo nothing. */
6088 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6089 return;
6090
6091 /* Execute the function. */
6092 switch (hlua_ctx_resume(hlua, 1)) {
6093 /* finished. */
6094 case HLUA_E_OK:
6095 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6096
6097 /* log time */
6098 strm->logs.tv_request = now;
6099
6100 /* eat the whole request */
6101 bo_skip(si_oc(si), si_ob(si)->o);
6102 res->flags |= CF_READ_NULL;
6103 si_shutr(si);
6104 return;
6105
6106 /* yield. */
6107 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006108 if (hlua->wake_time != TICK_ETERNITY)
6109 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006110 return;
6111
6112 /* finished with error. */
6113 case HLUA_E_ERRMSG:
6114 /* Display log. */
6115 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6116 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6117 lua_pop(hlua->T, 1);
6118 goto error;
6119
6120 case HLUA_E_ERR:
6121 /* Display log. */
6122 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6123 rule->arg.hlua_rule->fcn.name);
6124 goto error;
6125
6126 default:
6127 goto error;
6128 }
6129
6130error:
6131
6132 /* For all other cases, just close the stream. */
6133 si_shutw(si);
6134 si_shutr(si);
6135 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6136}
6137
6138static void hlua_applet_tcp_release(struct appctx *ctx)
6139{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006140 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006141 task_free(ctx->ctx.hlua_apptcp.task);
6142 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006143 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006144 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006145}
6146
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006147/* The function returns 1 if the initialisation is complete, 0 if
6148 * an errors occurs and -1 if more data are required for initializing
6149 * the applet.
6150 */
6151static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6152{
6153 struct stream_interface *si = ctx->owner;
6154 struct channel *req = si_oc(si);
6155 struct http_msg *msg;
6156 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006157 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006158 char **arg;
6159 struct hdr_ctx hdr;
6160 struct task *task;
6161 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006162 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006163
6164 /* Wait for a full HTTP request. */
6165 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6166 if (smp.flags & SMP_F_MAY_CHANGE)
6167 return -1;
6168 return 0;
6169 }
6170 txn = strm->txn;
6171 msg = &txn->req;
6172
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006173 /* We want two things in HTTP mode :
6174 * - enforce server-close mode if we were in keep-alive, so that the
6175 * applet is released after each response ;
6176 * - enable request body transfer to the applet in order to resync
6177 * with the response body.
6178 */
6179 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6180 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006181
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006182 hlua = pool_alloc2(pool2_hlua);
6183 if (!hlua) {
6184 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6185 ctx->rule->arg.hlua_rule->fcn.name);
6186 return 0;
6187 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006188 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006189 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006190 ctx->ctx.hlua_apphttp.left_bytes = -1;
6191 ctx->ctx.hlua_apphttp.flags = 0;
6192
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006193 if (txn->req.flags & HTTP_MSGF_VER_11)
6194 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6195
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006196 /* Create task used by signal to wakeup applets. */
6197 task = task_new();
6198 if (!task) {
6199 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6200 ctx->rule->arg.hlua_rule->fcn.name);
6201 return 0;
6202 }
6203 task->nice = 0;
6204 task->context = ctx;
6205 task->process = hlua_applet_wakeup;
6206 ctx->ctx.hlua_apphttp.task = task;
6207
6208 /* In the execution wrappers linked with a stream, the
6209 * Lua context can be not initialized. This behavior
6210 * permits to save performances because a systematic
6211 * Lua initialization cause 5% performances loss.
6212 */
6213 if (!hlua_ctx_init(hlua, task)) {
6214 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6215 ctx->rule->arg.hlua_rule->fcn.name);
6216 return 0;
6217 }
6218
6219 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006220 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006221
6222 /* The following Lua calls can fail. */
6223 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006224 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6225 error = lua_tostring(hlua->T, -1);
6226 else
6227 error = "critical error";
6228 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6229 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006230 return 0;
6231 }
6232
6233 /* Check stack available size. */
6234 if (!lua_checkstack(hlua->T, 1)) {
6235 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6236 ctx->rule->arg.hlua_rule->fcn.name);
6237 RESET_SAFE_LJMP(hlua->T);
6238 return 0;
6239 }
6240
6241 /* Restore the function in the stack. */
6242 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6243
6244 /* Create and and push object stream in the stack. */
6245 if (!hlua_applet_http_new(hlua->T, ctx)) {
6246 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6247 ctx->rule->arg.hlua_rule->fcn.name);
6248 RESET_SAFE_LJMP(hlua->T);
6249 return 0;
6250 }
6251 hlua->nargs = 1;
6252
6253 /* Look for a 100-continue expected. */
6254 if (msg->flags & HTTP_MSGF_VER_11) {
6255 hdr.idx = 0;
6256 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
6257 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6258 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6259 }
6260
6261 /* push keywords in the stack. */
6262 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6263 if (!lua_checkstack(hlua->T, 1)) {
6264 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6265 ctx->rule->arg.hlua_rule->fcn.name);
6266 RESET_SAFE_LJMP(hlua->T);
6267 return 0;
6268 }
6269 lua_pushstring(hlua->T, *arg);
6270 hlua->nargs++;
6271 }
6272
6273 RESET_SAFE_LJMP(hlua->T);
6274
6275 /* Wakeup the applet when data is ready for read. */
6276 si_applet_cant_get(si);
6277
6278 return 1;
6279}
6280
6281static void hlua_applet_http_fct(struct appctx *ctx)
6282{
6283 struct stream_interface *si = ctx->owner;
6284 struct stream *strm = si_strm(si);
6285 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006286 struct act_rule *rule = ctx->rule;
6287 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006288 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006289 char *blk1;
6290 int len1;
6291 char *blk2;
6292 int len2;
6293 int ret;
6294
6295 /* If the stream is disconnect or closed, ldo nothing. */
6296 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6297 return;
6298
6299 /* Set the currently running flag. */
6300 if (!HLUA_IS_RUNNING(hlua) &&
6301 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6302
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006303 /* Wait for full HTTP analysys. */
6304 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6305 si_applet_cant_get(si);
6306 return;
6307 }
6308
6309 /* Store the max amount of bytes that we can read. */
6310 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6311
6312 /* We need to flush the request header. This left the body
6313 * for the Lua.
6314 */
6315
6316 /* Read the maximum amount of data avalaible. */
6317 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
6318 if (ret == -1)
6319 return;
6320
6321 /* No data available, ask for more data. */
6322 if (ret == 1)
6323 len2 = 0;
6324 if (ret == 0)
6325 len1 = 0;
6326 if (len1 + len2 < strm->txn->req.eoh + 2) {
6327 si_applet_cant_get(si);
6328 return;
6329 }
6330
6331 /* skip the requests bytes. */
6332 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
6333 }
6334
6335 /* Executes The applet if it is not done. */
6336 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6337
6338 /* Execute the function. */
6339 switch (hlua_ctx_resume(hlua, 1)) {
6340 /* finished. */
6341 case HLUA_E_OK:
6342 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6343 break;
6344
6345 /* yield. */
6346 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006347 if (hlua->wake_time != TICK_ETERNITY)
6348 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006349 return;
6350
6351 /* finished with error. */
6352 case HLUA_E_ERRMSG:
6353 /* Display log. */
6354 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6355 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6356 lua_pop(hlua->T, 1);
6357 goto error;
6358
6359 case HLUA_E_ERR:
6360 /* Display log. */
6361 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6362 rule->arg.hlua_rule->fcn.name);
6363 goto error;
6364
6365 default:
6366 goto error;
6367 }
6368 }
6369
6370 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6371
6372 /* We must send the final chunk. */
6373 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6374 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6375
6376 /* sent last chunk at once. */
6377 ret = bi_putblk(res, "0\r\n\r\n", 5);
6378
6379 /* critical error. */
6380 if (ret == -2 || ret == -3) {
6381 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6382 rule->arg.hlua_rule->fcn.name);
6383 goto error;
6384 }
6385
6386 /* no enough space error. */
6387 if (ret == -1) {
6388 si_applet_cant_put(si);
6389 return;
6390 }
6391
6392 /* set the last chunk sent. */
6393 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6394 }
6395
6396 /* close the connection. */
6397
6398 /* status / log */
6399 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6400 strm->logs.tv_request = now;
6401
6402 /* eat the whole request */
6403 bo_skip(si_oc(si), si_ob(si)->o);
6404 res->flags |= CF_READ_NULL;
6405 si_shutr(si);
6406
6407 return;
6408 }
6409
6410error:
6411
6412 /* If we are in HTTP mode, and we are not send any
6413 * data, return a 500 server error in best effort:
6414 * if there are no room avalaible in the buffer,
6415 * just close the connection.
6416 */
6417 bi_putblk(res, error_500, strlen(error_500));
6418 if (!(strm->flags & SF_ERR_MASK))
6419 strm->flags |= SF_ERR_RESOURCE;
6420 si_shutw(si);
6421 si_shutr(si);
6422 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6423}
6424
6425static void hlua_applet_http_release(struct appctx *ctx)
6426{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006427 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006428 task_free(ctx->ctx.hlua_apphttp.task);
6429 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006430 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006431 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006432}
6433
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006434/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6435 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006436 *
6437 * This function can fail with an abort() due to an Lua critical error.
6438 * We are in the configuration parsing process of HAProxy, this abort() is
6439 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006440 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006441static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6442 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006443{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006444 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006445 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006446
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006447 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006448 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006449 if (!rule->arg.hlua_rule) {
6450 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006451 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006452 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006453
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006454 /* Memory for arguments. */
6455 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6456 if (!rule->arg.hlua_rule->args) {
6457 memprintf(err, "out of memory error");
6458 return ACT_RET_PRS_ERR;
6459 }
6460
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006461 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006462 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006463
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006464 /* Expect some arguments */
6465 for (i = 0; i < fcn->nargs; i++) {
6466 if (*args[i+1] == '\0') {
6467 memprintf(err, "expect %d arguments", fcn->nargs);
6468 return ACT_RET_PRS_ERR;
6469 }
6470 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6471 if (!rule->arg.hlua_rule->args[i]) {
6472 memprintf(err, "out of memory error");
6473 return ACT_RET_PRS_ERR;
6474 }
6475 (*cur_arg)++;
6476 }
6477 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006478
Thierry FOURNIER42148732015-09-02 17:17:33 +02006479 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006480 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006481 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006482}
6483
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006484static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6485 struct act_rule *rule, char **err)
6486{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006487 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006488
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006489 /* HTTP applets are forbidden in tcp-request rules.
6490 * HTTP applet request requires everything initilized by
6491 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6492 * The applet will be immediately initilized, but its before
6493 * the call of this analyzer.
6494 */
6495 if (rule->from != ACT_F_HTTP_REQ) {
6496 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6497 return ACT_RET_PRS_ERR;
6498 }
6499
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006500 /* Memory for the rule. */
6501 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6502 if (!rule->arg.hlua_rule) {
6503 memprintf(err, "out of memory error");
6504 return ACT_RET_PRS_ERR;
6505 }
6506
6507 /* Reference the Lua function and store the reference. */
6508 rule->arg.hlua_rule->fcn = *fcn;
6509
6510 /* TODO: later accept arguments. */
6511 rule->arg.hlua_rule->args = NULL;
6512
6513 /* Add applet pointer in the rule. */
6514 rule->applet.obj_type = OBJ_TYPE_APPLET;
6515 rule->applet.name = fcn->name;
6516 rule->applet.init = hlua_applet_http_init;
6517 rule->applet.fct = hlua_applet_http_fct;
6518 rule->applet.release = hlua_applet_http_release;
6519 rule->applet.timeout = hlua_timeout_applet;
6520
6521 return ACT_RET_PRS_OK;
6522}
6523
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006524/* This function is an LUA binding used for registering
6525 * "sample-conv" functions. It expects a converter name used
6526 * in the haproxy configuration file, and an LUA function.
6527 */
6528__LJMP static int hlua_register_action(lua_State *L)
6529{
6530 struct action_kw_list *akl;
6531 const char *name;
6532 int ref;
6533 int len;
6534 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006535 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006536
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006537 /* Initialise the number of expected arguments at 0. */
6538 nargs = 0;
6539
6540 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6541 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006542
6543 /* First argument : converter name. */
6544 name = MAY_LJMP(luaL_checkstring(L, 1));
6545
6546 /* Second argument : environment. */
6547 if (lua_type(L, 2) != LUA_TTABLE)
6548 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6549
6550 /* Third argument : lua function. */
6551 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6552
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006553 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6554 if (lua_gettop(L) >= 4)
6555 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6556
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006557 /* browse the second argulent as an array. */
6558 lua_pushnil(L);
6559 while (lua_next(L, 2) != 0) {
6560 if (lua_type(L, -1) != LUA_TSTRING)
6561 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6562
6563 /* Check required environment. Only accepted "http" or "tcp". */
6564 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006565 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006566 if (!akl)
6567 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006568 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006569 if (!fcn)
6570 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6571
6572 /* Fill fcn. */
6573 fcn->name = strdup(name);
6574 if (!fcn->name)
6575 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6576 fcn->function_ref = ref;
6577
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006578 /* Set the expected number od arguments. */
6579 fcn->nargs = nargs;
6580
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006581 /* List head */
6582 akl->list.n = akl->list.p = NULL;
6583
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006584 /* action keyword. */
6585 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006586 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006587 if (!akl->kw[0].kw)
6588 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6589
6590 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6591
6592 akl->kw[0].match_pfx = 0;
6593 akl->kw[0].private = fcn;
6594 akl->kw[0].parse = action_register_lua;
6595
6596 /* select the action registering point. */
6597 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6598 tcp_req_cont_keywords_register(akl);
6599 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6600 tcp_res_cont_keywords_register(akl);
6601 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6602 http_req_keywords_register(akl);
6603 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6604 http_res_keywords_register(akl);
6605 else
6606 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6607 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6608 "are expected.", lua_tostring(L, -1)));
6609
6610 /* pop the environment string. */
6611 lua_pop(L, 1);
6612 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006613 return ACT_RET_PRS_OK;
6614}
6615
6616static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6617 struct act_rule *rule, char **err)
6618{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006619 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006620
6621 /* Memory for the rule. */
6622 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6623 if (!rule->arg.hlua_rule) {
6624 memprintf(err, "out of memory error");
6625 return ACT_RET_PRS_ERR;
6626 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006627
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006628 /* Reference the Lua function and store the reference. */
6629 rule->arg.hlua_rule->fcn = *fcn;
6630
6631 /* TODO: later accept arguments. */
6632 rule->arg.hlua_rule->args = NULL;
6633
6634 /* Add applet pointer in the rule. */
6635 rule->applet.obj_type = OBJ_TYPE_APPLET;
6636 rule->applet.name = fcn->name;
6637 rule->applet.init = hlua_applet_tcp_init;
6638 rule->applet.fct = hlua_applet_tcp_fct;
6639 rule->applet.release = hlua_applet_tcp_release;
6640 rule->applet.timeout = hlua_timeout_applet;
6641
6642 return 0;
6643}
6644
6645/* This function is an LUA binding used for registering
6646 * "sample-conv" functions. It expects a converter name used
6647 * in the haproxy configuration file, and an LUA function.
6648 */
6649__LJMP static int hlua_register_service(lua_State *L)
6650{
6651 struct action_kw_list *akl;
6652 const char *name;
6653 const char *env;
6654 int ref;
6655 int len;
6656 struct hlua_function *fcn;
6657
6658 MAY_LJMP(check_args(L, 3, "register_service"));
6659
6660 /* First argument : converter name. */
6661 name = MAY_LJMP(luaL_checkstring(L, 1));
6662
6663 /* Second argument : environment. */
6664 env = MAY_LJMP(luaL_checkstring(L, 2));
6665
6666 /* Third argument : lua function. */
6667 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6668
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006669 /* Allocate and fill the sample fetch keyword struct. */
6670 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6671 if (!akl)
6672 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6673 fcn = calloc(1, sizeof(*fcn));
6674 if (!fcn)
6675 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6676
6677 /* Fill fcn. */
6678 len = strlen("<lua.>") + strlen(name) + 1;
6679 fcn->name = calloc(1, len);
6680 if (!fcn->name)
6681 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6682 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6683 fcn->function_ref = ref;
6684
6685 /* List head */
6686 akl->list.n = akl->list.p = NULL;
6687
6688 /* converter keyword. */
6689 len = strlen("lua.") + strlen(name) + 1;
6690 akl->kw[0].kw = calloc(1, len);
6691 if (!akl->kw[0].kw)
6692 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6693
6694 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6695
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01006696 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006697 if (strcmp(env, "tcp") == 0)
6698 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006699 else if (strcmp(env, "http") == 0)
6700 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006701 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006702 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6703 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006704
6705 akl->kw[0].match_pfx = 0;
6706 akl->kw[0].private = fcn;
6707
6708 /* End of array. */
6709 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6710
6711 /* Register this new converter */
6712 service_keywords_register(akl);
6713
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006714 return 0;
6715}
6716
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006717/* This function initialises Lua cli handler. It copies the
6718 * arguments in the Lua stack and create channel IO objects.
6719 */
6720static int hlua_cli_parse_fct(char **args, struct appctx *appctx, void *private)
6721{
6722 struct hlua *hlua;
6723 struct hlua_function *fcn;
6724 int i;
6725 const char *error;
6726
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006727 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006728 appctx->ctx.hlua_cli.fcn = private;
6729
6730 hlua = pool_alloc2(pool2_hlua);
6731 if (!hlua) {
6732 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006733 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006734 }
6735 HLUA_INIT(hlua);
6736 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006737
6738 /* Create task used by signal to wakeup applets.
6739 * We use the same wakeup fonction than the Lua applet_tcp and
6740 * applet_http. It is absolutely compatible.
6741 */
6742 appctx->ctx.hlua_cli.task = task_new();
6743 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01006744 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006745 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006746 }
6747 appctx->ctx.hlua_cli.task->nice = 0;
6748 appctx->ctx.hlua_cli.task->context = appctx;
6749 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
6750
6751 /* Initialises the Lua context */
6752 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
6753 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006754 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006755 }
6756
6757 /* The following Lua calls can fail. */
6758 if (!SET_SAFE_LJMP(hlua->T)) {
6759 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6760 error = lua_tostring(hlua->T, -1);
6761 else
6762 error = "critical error";
6763 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
6764 goto error;
6765 }
6766
6767 /* Check stack available size. */
6768 if (!lua_checkstack(hlua->T, 2)) {
6769 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6770 goto error;
6771 }
6772
6773 /* Restore the function in the stack. */
6774 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
6775
6776 /* Once the arguments parsed, the CLI is like an AppletTCP,
6777 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006778 */
6779 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
6780 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6781 goto error;
6782 }
6783 hlua->nargs = 1;
6784
6785 /* push keywords in the stack. */
6786 for (i = 0; *args[i]; i++) {
6787 /* Check stack available size. */
6788 if (!lua_checkstack(hlua->T, 1)) {
6789 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6790 goto error;
6791 }
6792 lua_pushstring(hlua->T, args[i]);
6793 hlua->nargs++;
6794 }
6795
6796 /* We must initialize the execution timeouts. */
6797 hlua->max_time = hlua_timeout_session;
6798
6799 /* At this point the execution is safe. */
6800 RESET_SAFE_LJMP(hlua->T);
6801
6802 /* It's ok */
6803 return 0;
6804
6805 /* It's not ok. */
6806error:
6807 RESET_SAFE_LJMP(hlua->T);
6808 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006809 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006810 return 1;
6811}
6812
6813static int hlua_cli_io_handler_fct(struct appctx *appctx)
6814{
6815 struct hlua *hlua;
6816 struct stream_interface *si;
6817 struct hlua_function *fcn;
6818
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006819 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006820 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01006821 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006822
6823 /* If the stream is disconnect or closed, ldo nothing. */
6824 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6825 return 1;
6826
6827 /* Execute the function. */
6828 switch (hlua_ctx_resume(hlua, 1)) {
6829
6830 /* finished. */
6831 case HLUA_E_OK:
6832 return 1;
6833
6834 /* yield. */
6835 case HLUA_E_AGAIN:
6836 /* We want write. */
6837 if (HLUA_IS_WAKERESWR(hlua))
6838 si_applet_cant_put(si);
6839 /* Set the timeout. */
6840 if (hlua->wake_time != TICK_ETERNITY)
6841 task_schedule(hlua->task, hlua->wake_time);
6842 return 0;
6843
6844 /* finished with error. */
6845 case HLUA_E_ERRMSG:
6846 /* Display log. */
6847 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
6848 fcn->name, lua_tostring(hlua->T, -1));
6849 lua_pop(hlua->T, 1);
6850 return 1;
6851
6852 case HLUA_E_ERR:
6853 /* Display log. */
6854 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
6855 fcn->name);
6856 return 1;
6857
6858 default:
6859 return 1;
6860 }
6861
6862 return 1;
6863}
6864
6865static void hlua_cli_io_release_fct(struct appctx *appctx)
6866{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006867 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006868 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006869}
6870
6871/* This function is an LUA binding used for registering
6872 * new keywords in the cli. It expects a list of keywords
6873 * which are the "path". It is limited to 5 keywords. A
6874 * description of the command, a function to be executed
6875 * for the parsing and a function for io handlers.
6876 */
6877__LJMP static int hlua_register_cli(lua_State *L)
6878{
6879 struct cli_kw_list *cli_kws;
6880 const char *message;
6881 int ref_io;
6882 int len;
6883 struct hlua_function *fcn;
6884 int index;
6885 int i;
6886
6887 MAY_LJMP(check_args(L, 3, "register_cli"));
6888
6889 /* First argument : an array of maximum 5 keywords. */
6890 if (!lua_istable(L, 1))
6891 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
6892
6893 /* Second argument : string with contextual message. */
6894 message = MAY_LJMP(luaL_checkstring(L, 2));
6895
6896 /* Third and fourth argument : lua function. */
6897 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
6898
6899 /* Allocate and fill the sample fetch keyword struct. */
6900 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
6901 if (!cli_kws)
6902 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6903 fcn = calloc(1, sizeof(*fcn));
6904 if (!fcn)
6905 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6906
6907 /* Fill path. */
6908 index = 0;
6909 lua_pushnil(L);
6910 while(lua_next(L, 1) != 0) {
6911 if (index >= 5)
6912 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
6913 if (lua_type(L, -1) != LUA_TSTRING)
6914 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
6915 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
6916 if (!cli_kws->kw[0].str_kw[index])
6917 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6918 index++;
6919 lua_pop(L, 1);
6920 }
6921
6922 /* Copy help message. */
6923 cli_kws->kw[0].usage = strdup(message);
6924 if (!cli_kws->kw[0].usage)
6925 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6926
6927 /* Fill fcn io handler. */
6928 len = strlen("<lua.cli>") + 1;
6929 for (i = 0; i < index; i++)
6930 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
6931 fcn->name = calloc(1, len);
6932 if (!fcn->name)
6933 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6934 strncat((char *)fcn->name, "<lua.cli", len);
6935 for (i = 0; i < index; i++) {
6936 strncat((char *)fcn->name, ".", len);
6937 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
6938 }
6939 strncat((char *)fcn->name, ">", len);
6940 fcn->function_ref = ref_io;
6941
6942 /* Fill last entries. */
6943 cli_kws->kw[0].private = fcn;
6944 cli_kws->kw[0].parse = hlua_cli_parse_fct;
6945 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
6946 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
6947
6948 /* Register this new converter */
6949 cli_register_kw(cli_kws);
6950
6951 return 0;
6952}
6953
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006954static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
6955 struct proxy *defpx, const char *file, int line,
6956 char **err, unsigned int *timeout)
6957{
6958 const char *error;
6959
6960 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
6961 if (error && *error != '\0') {
6962 memprintf(err, "%s: invalid timeout", args[0]);
6963 return -1;
6964 }
6965 return 0;
6966}
6967
6968static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
6969 struct proxy *defpx, const char *file, int line,
6970 char **err)
6971{
6972 return hlua_read_timeout(args, section_type, curpx, defpx,
6973 file, line, err, &hlua_timeout_session);
6974}
6975
6976static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
6977 struct proxy *defpx, const char *file, int line,
6978 char **err)
6979{
6980 return hlua_read_timeout(args, section_type, curpx, defpx,
6981 file, line, err, &hlua_timeout_task);
6982}
6983
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006984static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
6985 struct proxy *defpx, const char *file, int line,
6986 char **err)
6987{
6988 return hlua_read_timeout(args, section_type, curpx, defpx,
6989 file, line, err, &hlua_timeout_applet);
6990}
6991
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006992static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
6993 struct proxy *defpx, const char *file, int line,
6994 char **err)
6995{
6996 char *error;
6997
6998 hlua_nb_instruction = strtoll(args[1], &error, 10);
6999 if (*error != '\0') {
7000 memprintf(err, "%s: invalid number", args[0]);
7001 return -1;
7002 }
7003 return 0;
7004}
7005
Willy Tarreau32f61e22015-03-18 17:54:59 +01007006static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7007 struct proxy *defpx, const char *file, int line,
7008 char **err)
7009{
7010 char *error;
7011
7012 if (*(args[1]) == 0) {
7013 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7014 return -1;
7015 }
7016 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7017 if (*error != '\0') {
7018 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7019 return -1;
7020 }
7021 return 0;
7022}
7023
7024
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007025/* This function is called by the main configuration key "lua-load". It loads and
7026 * execute an lua file during the parsing of the HAProxy configuration file. It is
7027 * the main lua entry point.
7028 *
7029 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7030 * occured, otherwise it returns 0.
7031 *
7032 * In some error case, LUA set an error message in top of the stack. This function
7033 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007034 *
7035 * This function can fail with an abort() due to an Lua critical error.
7036 * We are in the configuration parsing process of HAProxy, this abort() is
7037 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007038 */
7039static int hlua_load(char **args, int section_type, struct proxy *curpx,
7040 struct proxy *defpx, const char *file, int line,
7041 char **err)
7042{
7043 int error;
7044
7045 /* Just load and compile the file. */
7046 error = luaL_loadfile(gL.T, args[1]);
7047 if (error) {
7048 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
7049 lua_pop(gL.T, 1);
7050 return -1;
7051 }
7052
7053 /* If no syntax error where detected, execute the code. */
7054 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7055 switch (error) {
7056 case LUA_OK:
7057 break;
7058 case LUA_ERRRUN:
7059 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
7060 lua_pop(gL.T, 1);
7061 return -1;
7062 case LUA_ERRMEM:
7063 memprintf(err, "lua out of memory error\n");
7064 return -1;
7065 case LUA_ERRERR:
7066 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
7067 lua_pop(gL.T, 1);
7068 return -1;
7069 case LUA_ERRGCMM:
7070 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
7071 lua_pop(gL.T, 1);
7072 return -1;
7073 default:
7074 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
7075 lua_pop(gL.T, 1);
7076 return -1;
7077 }
7078
7079 return 0;
7080}
7081
7082/* configuration keywords declaration */
7083static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007084 { CFG_GLOBAL, "lua-load", hlua_load },
7085 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7086 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007087 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007088 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007089 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007090 { 0, NULL, NULL },
7091}};
7092
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007093/* This function can fail with an abort() due to an Lua critical error.
7094 * We are in the initialisation process of HAProxy, this abort() is
7095 * tolerated.
7096 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007097int hlua_post_init()
7098{
7099 struct hlua_init_function *init;
7100 const char *msg;
7101 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007102 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007103
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007104 /* Call post initialisation function in safe environement. */
7105 if (!SET_SAFE_LJMP(gL.T)) {
7106 if (lua_type(gL.T, -1) == LUA_TSTRING)
7107 error = lua_tostring(gL.T, -1);
7108 else
7109 error = "critical error";
7110 fprintf(stderr, "Lua post-init: %s.\n", error);
7111 exit(1);
7112 }
7113 hlua_fcn_post_init(gL.T);
7114 RESET_SAFE_LJMP(gL.T);
7115
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007116 list_for_each_entry(init, &hlua_init_functions, l) {
7117 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7118 ret = hlua_ctx_resume(&gL, 0);
7119 switch (ret) {
7120 case HLUA_E_OK:
7121 lua_pop(gL.T, -1);
7122 return 1;
7123 case HLUA_E_AGAIN:
7124 Alert("lua init: yield not allowed.\n");
7125 return 0;
7126 case HLUA_E_ERRMSG:
7127 msg = lua_tostring(gL.T, -1);
7128 Alert("lua init: %s.\n", msg);
7129 return 0;
7130 case HLUA_E_ERR:
7131 default:
7132 Alert("lua init: unknown runtime error.\n");
7133 return 0;
7134 }
7135 }
7136 return 1;
7137}
7138
Willy Tarreau32f61e22015-03-18 17:54:59 +01007139/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7140 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7141 * is the previously allocated size or the kind of object in case of a new
7142 * allocation. <nsize> is the requested new size.
7143 */
7144static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7145{
7146 struct hlua_mem_allocator *zone = ud;
7147
7148 if (nsize == 0) {
7149 /* it's a free */
7150 if (ptr)
7151 zone->allocated -= osize;
7152 free(ptr);
7153 return NULL;
7154 }
7155
7156 if (!ptr) {
7157 /* it's a new allocation */
7158 if (zone->limit && zone->allocated + nsize > zone->limit)
7159 return NULL;
7160
7161 ptr = malloc(nsize);
7162 if (ptr)
7163 zone->allocated += nsize;
7164 return ptr;
7165 }
7166
7167 /* it's a realloc */
7168 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7169 return NULL;
7170
7171 ptr = realloc(ptr, nsize);
7172 if (ptr)
7173 zone->allocated += nsize - osize;
7174 return ptr;
7175}
7176
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007177/* Ithis function can fail with an abort() due to an Lua critical error.
7178 * We are in the initialisation process of HAProxy, this abort() is
7179 * tolerated.
7180 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007181void hlua_init(void)
7182{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007183 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007184 int idx;
7185 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007186 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007187 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007188 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007189#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007190 struct srv_kw *kw;
7191 int tmp_error;
7192 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007193 char *args[] = { /* SSL client configuration. */
7194 "ssl",
7195 "verify",
7196 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007197 NULL
7198 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007199#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007200
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007201 /* Initialise struct hlua and com signals pool */
7202 pool2_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007203 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
7204
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007205 /* Register configuration keywords. */
7206 cfg_register_keywords(&cfg_kws);
7207
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007208 /* Init main lua stack. */
7209 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007210 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007211 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007212 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007213 hlua_sethlua(&gL);
7214 gL.Tref = LUA_REFNIL;
7215 gL.task = NULL;
7216
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007217 /* From this point, until the end of the initialisation fucntion,
7218 * the Lua function can fail with an abort. We are in the initialisation
7219 * process of HAProxy, this abort() is tolerated.
7220 */
7221
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007222 /* Initialise lua. */
7223 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007224
Thierry Fournier75933d42016-01-21 09:30:18 +01007225 /* Set safe environment for the initialisation. */
7226 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007227 if (lua_type(gL.T, -1) == LUA_TSTRING)
7228 error_msg = lua_tostring(gL.T, -1);
7229 else
7230 error_msg = "critical error";
7231 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007232 exit(1);
7233 }
7234
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007235 /*
7236 *
7237 * Create "core" object.
7238 *
7239 */
7240
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007241 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007242 lua_newtable(gL.T);
7243
7244 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007245 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007246 hlua_class_const_int(gL.T, log_levels[i], i);
7247
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007248 /* Register special functions. */
7249 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007250 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007251 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007252 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007253 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007254 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007255 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007256 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007257 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007258 hlua_class_function(gL.T, "sleep", hlua_sleep);
7259 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007260 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7261 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7262 hlua_class_function(gL.T, "set_map", hlua_set_map);
7263 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007264 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007265 hlua_class_function(gL.T, "log", hlua_log);
7266 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7267 hlua_class_function(gL.T, "Info", hlua_log_info);
7268 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7269 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007270 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007271 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007272
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007273 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007274
7275 /*
7276 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007277 * Register class Map
7278 *
7279 */
7280
7281 /* This table entry is the object "Map" base. */
7282 lua_newtable(gL.T);
7283
7284 /* register pattern types. */
7285 for (i=0; i<PAT_MATCH_NUM; i++)
7286 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007287 for (i=0; i<PAT_MATCH_NUM; i++) {
7288 snprintf(trash.str, trash.size, "_%s", pat_match_names[i]);
7289 hlua_class_const_int(gL.T, trash.str, i);
7290 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007291
7292 /* register constructor. */
7293 hlua_class_function(gL.T, "new", hlua_map_new);
7294
7295 /* Create and fill the metatable. */
7296 lua_newtable(gL.T);
7297
7298 /* Create and fille the __index entry. */
7299 lua_pushstring(gL.T, "__index");
7300 lua_newtable(gL.T);
7301
7302 /* Register . */
7303 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7304 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7305
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007306 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007307
Thierry Fournier45e78d72016-02-19 18:34:46 +01007308 /* Register previous table in the registry with reference and named entry.
7309 * The function hlua_register_metatable() pops the stack, so we
7310 * previously create a copy of the table.
7311 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007312 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007313 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007314
7315 /* Assign the metatable to the mai Map object. */
7316 lua_setmetatable(gL.T, -2);
7317
7318 /* Set a name to the table. */
7319 lua_setglobal(gL.T, "Map");
7320
7321 /*
7322 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007323 * Register class Channel
7324 *
7325 */
7326
7327 /* Create and fill the metatable. */
7328 lua_newtable(gL.T);
7329
7330 /* Create and fille the __index entry. */
7331 lua_pushstring(gL.T, "__index");
7332 lua_newtable(gL.T);
7333
7334 /* Register . */
7335 hlua_class_function(gL.T, "get", hlua_channel_get);
7336 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7337 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7338 hlua_class_function(gL.T, "set", hlua_channel_set);
7339 hlua_class_function(gL.T, "append", hlua_channel_append);
7340 hlua_class_function(gL.T, "send", hlua_channel_send);
7341 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7342 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7343 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007344 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007345
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007346 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007347
7348 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007349 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007350
7351 /*
7352 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007353 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007354 *
7355 */
7356
7357 /* Create and fill the metatable. */
7358 lua_newtable(gL.T);
7359
7360 /* Create and fille the __index entry. */
7361 lua_pushstring(gL.T, "__index");
7362 lua_newtable(gL.T);
7363
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007364 /* Browse existing fetches and create the associated
7365 * object method.
7366 */
7367 sf = NULL;
7368 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7369
7370 /* Dont register the keywork if the arguments check function are
7371 * not safe during the runtime.
7372 */
7373 if ((sf->val_args != NULL) &&
7374 (sf->val_args != val_payload_lv) &&
7375 (sf->val_args != val_hdr))
7376 continue;
7377
7378 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7379 * by an underscore.
7380 */
7381 strncpy(trash.str, sf->kw, trash.size);
7382 trash.str[trash.size - 1] = '\0';
7383 for (p = trash.str; *p; p++)
7384 if (*p == '.' || *p == '-' || *p == '+')
7385 *p = '_';
7386
7387 /* Register the function. */
7388 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007389 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007390 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007391 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007392 }
7393
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007394 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007395
7396 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007397 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007398
7399 /*
7400 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007401 * Register class Converters
7402 *
7403 */
7404
7405 /* Create and fill the metatable. */
7406 lua_newtable(gL.T);
7407
7408 /* Create and fill the __index entry. */
7409 lua_pushstring(gL.T, "__index");
7410 lua_newtable(gL.T);
7411
7412 /* Browse existing converters and create the associated
7413 * object method.
7414 */
7415 sc = NULL;
7416 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7417 /* Dont register the keywork if the arguments check function are
7418 * not safe during the runtime.
7419 */
7420 if (sc->val_args != NULL)
7421 continue;
7422
7423 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7424 * by an underscore.
7425 */
7426 strncpy(trash.str, sc->kw, trash.size);
7427 trash.str[trash.size - 1] = '\0';
7428 for (p = trash.str; *p; p++)
7429 if (*p == '.' || *p == '-' || *p == '+')
7430 *p = '_';
7431
7432 /* Register the function. */
7433 lua_pushstring(gL.T, trash.str);
7434 lua_pushlightuserdata(gL.T, sc);
7435 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007436 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007437 }
7438
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007439 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007440
7441 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007442 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007443
7444 /*
7445 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007446 * Register class HTTP
7447 *
7448 */
7449
7450 /* Create and fill the metatable. */
7451 lua_newtable(gL.T);
7452
7453 /* Create and fille the __index entry. */
7454 lua_pushstring(gL.T, "__index");
7455 lua_newtable(gL.T);
7456
7457 /* Register Lua functions. */
7458 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7459 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7460 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7461 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7462 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7463 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7464 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7465 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7466 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7467 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7468
7469 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7470 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7471 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7472 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7473 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7474 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007475 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007476
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007477 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007478
7479 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007480 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007481
7482 /*
7483 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007484 * Register class AppletTCP
7485 *
7486 */
7487
7488 /* Create and fill the metatable. */
7489 lua_newtable(gL.T);
7490
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007491 /* Create and fille the __index entry. */
7492 lua_pushstring(gL.T, "__index");
7493 lua_newtable(gL.T);
7494
7495 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007496 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7497 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7498 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7499 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7500 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007501 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7502 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7503 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007504
7505 lua_settable(gL.T, -3);
7506
7507 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007508 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007509
7510 /*
7511 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007512 * Register class AppletHTTP
7513 *
7514 */
7515
7516 /* Create and fill the metatable. */
7517 lua_newtable(gL.T);
7518
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007519 /* Create and fille the __index entry. */
7520 lua_pushstring(gL.T, "__index");
7521 lua_newtable(gL.T);
7522
7523 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007524 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7525 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007526 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7527 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7528 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007529 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7530 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7531 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7532 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7533 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7534 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7535
7536 lua_settable(gL.T, -3);
7537
7538 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007539 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007540
7541 /*
7542 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007543 * Register class TXN
7544 *
7545 */
7546
7547 /* Create and fill the metatable. */
7548 lua_newtable(gL.T);
7549
7550 /* Create and fille the __index entry. */
7551 lua_pushstring(gL.T, "__index");
7552 lua_newtable(gL.T);
7553
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007554 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007555 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7556 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007557 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007558 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007559 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007560 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007561 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7562 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7563 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007564 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7565 hlua_class_function(gL.T, "log", hlua_txn_log);
7566 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7567 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7568 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7569 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007570
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007571 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007572
7573 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007574 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007575
7576 /*
7577 *
7578 * Register class Socket
7579 *
7580 */
7581
7582 /* Create and fill the metatable. */
7583 lua_newtable(gL.T);
7584
7585 /* Create and fille the __index entry. */
7586 lua_pushstring(gL.T, "__index");
7587 lua_newtable(gL.T);
7588
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007589#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007590 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007591#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007592 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7593 hlua_class_function(gL.T, "send", hlua_socket_send);
7594 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7595 hlua_class_function(gL.T, "close", hlua_socket_close);
7596 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7597 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7598 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7599 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7600
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007601 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007602
7603 /* Register the garbage collector entry. */
7604 lua_pushstring(gL.T, "__gc");
7605 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007606 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007607
7608 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007609 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007610
7611 /* Proxy and server configuration initialisation. */
7612 memset(&socket_proxy, 0, sizeof(socket_proxy));
7613 init_new_proxy(&socket_proxy);
7614 socket_proxy.parent = NULL;
7615 socket_proxy.last_change = now.tv_sec;
7616 socket_proxy.id = "LUA-SOCKET";
7617 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7618 socket_proxy.maxconn = 0;
7619 socket_proxy.accept = NULL;
7620 socket_proxy.options2 |= PR_O2_INDEPSTR;
7621 socket_proxy.srv = NULL;
7622 socket_proxy.conn_retries = 0;
7623 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7624
7625 /* Init TCP server: unchanged parameters */
7626 memset(&socket_tcp, 0, sizeof(socket_tcp));
7627 socket_tcp.next = NULL;
7628 socket_tcp.proxy = &socket_proxy;
7629 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7630 LIST_INIT(&socket_tcp.actconns);
7631 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007632 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007633 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007634 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007635 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
7636 socket_tcp.last_change = 0;
7637 socket_tcp.id = "LUA-TCP-CONN";
7638 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7639 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7640 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7641
7642 /* XXX: Copy default parameter from default server,
7643 * but the default server is not initialized.
7644 */
7645 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7646 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7647 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7648 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7649 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7650 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7651 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7652 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7653 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7654 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7655
7656 socket_tcp.check.status = HCHK_STATUS_INI;
7657 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7658 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7659 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7660 socket_tcp.check.server = &socket_tcp;
7661
7662 socket_tcp.agent.status = HCHK_STATUS_INI;
7663 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7664 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7665 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7666 socket_tcp.agent.server = &socket_tcp;
7667
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007668 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007669
7670#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007671 /* Init TCP server: unchanged parameters */
7672 memset(&socket_ssl, 0, sizeof(socket_ssl));
7673 socket_ssl.next = NULL;
7674 socket_ssl.proxy = &socket_proxy;
7675 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7676 LIST_INIT(&socket_ssl.actconns);
7677 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007678 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007679 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007680 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007681 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
7682 socket_ssl.last_change = 0;
7683 socket_ssl.id = "LUA-SSL-CONN";
7684 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7685 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7686 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7687
7688 /* XXX: Copy default parameter from default server,
7689 * but the default server is not initialized.
7690 */
7691 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7692 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7693 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7694 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7695 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7696 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7697 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7698 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7699 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7700 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7701
7702 socket_ssl.check.status = HCHK_STATUS_INI;
7703 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7704 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7705 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7706 socket_ssl.check.server = &socket_ssl;
7707
7708 socket_ssl.agent.status = HCHK_STATUS_INI;
7709 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7710 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7711 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7712 socket_ssl.agent.server = &socket_ssl;
7713
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007714 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007715 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007716
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007717 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007718 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7719 /*
7720 *
7721 * If the keyword is not known, we can search in the registered
7722 * server keywords. This is usefull to configure special SSL
7723 * features like client certificates and ssl_verify.
7724 *
7725 */
7726 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7727 if (tmp_error != 0) {
7728 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7729 abort(); /* This must be never arrives because the command line
7730 not editable by the user. */
7731 }
7732 idx += kw->skip;
7733 }
7734 }
7735
7736 /* Initialize SSL server. */
Willy Tarreau17d45382016-12-22 21:16:08 +01007737 if (socket_ssl.xprt->prepare_srv)
7738 socket_ssl.xprt->prepare_srv(&socket_ssl);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007739#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007740
7741 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007742}
Willy Tarreaubb57d942016-12-21 19:04:56 +01007743
7744__attribute__((constructor))
7745static void __hlua_init(void)
7746{
7747 char *ptr = NULL;
7748 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
7749 hap_register_build_opts(ptr, 1);
7750}