blob: 594d880eda51ecd452bb39d074589ae6d5587bdb [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;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002300
2301 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002302 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002303 hlua_pusherror(L, "socket: full stack");
2304 goto out_fail_conf;
2305 }
2306
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002307 /* Create the object: obj[0] = userdata. */
2308 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002309 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002310 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311 memset(socket, 0, sizeof(*socket));
2312
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002313 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002314 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002315 hlua_pusherror(L, "socket: uninitialized pools.");
2316 goto out_fail_conf;
2317 }
2318
Willy Tarreau87b09662015-04-03 00:22:06 +02002319 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002320 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2321 lua_setmetatable(L, -2);
2322
Willy Tarreaud420a972015-04-06 00:39:18 +02002323 /* Create the applet context */
2324 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002325 if (!appctx) {
2326 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002327 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002328 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002329
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002330 appctx->ctx.hlua_cosocket.socket = socket;
2331 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002332 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002333 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2334 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002335
Willy Tarreaud420a972015-04-06 00:39:18 +02002336 /* Now create a session, task and stream for this applet */
2337 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2338 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002339 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002340 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002341 }
2342
Willy Tarreau87787ac2017-08-28 16:22:54 +02002343 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002344 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002345 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002346 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002347 }
2348
Willy Tarreaud420a972015-04-06 00:39:18 +02002349 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002350 socket->s = strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002351
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002352 /* Configure "right" stream interface. this "si" is used to connect
2353 * and retrieve data from the server. The connection is initialized
2354 * with the "struct server".
2355 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002356 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002357
2358 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002359 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2360 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002361
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002362 /* Update statistics counters. */
2363 socket_proxy.feconn++; /* beconn will be increased later */
2364 jobs++;
2365 totalconn++;
2366
Willy Tarreau87787ac2017-08-28 16:22:54 +02002367 task_wakeup(strm->task, TASK_WOKEN_INIT);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002368 /* Return yield waiting for connection. */
2369 return 1;
2370
Willy Tarreaud420a972015-04-06 00:39:18 +02002371 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002372 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002373 out_fail_sess:
2374 appctx_free(appctx);
2375 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002376 WILL_LJMP(lua_error(L));
2377 return 0;
2378}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002379
2380/*
2381 *
2382 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002383 * Class Channel
2384 *
2385 *
2386 */
2387
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002388/* The state between the channel data and the HTTP parser state can be
2389 * unconsistent, so reset the parser and call it again. Warning, this
2390 * action not revalidate the request and not send a 400 if the modified
2391 * resuest is not valid.
2392 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002393 * This function never fails. The direction is set using dir, which equals
2394 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002395 */
2396static void hlua_resynchonize_proto(struct stream *stream, int dir)
2397{
2398 /* Protocol HTTP. */
2399 if (stream->be->mode == PR_MODE_HTTP) {
2400
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002401 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002402 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002403 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002404 http_txn_reset_res(stream->txn);
2405
2406 if (stream->txn->hdr_idx.v)
2407 hdr_idx_init(&stream->txn->hdr_idx);
2408
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002409 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002410 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002411 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002412 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2413 }
2414}
2415
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002416/* This function is called before the Lua execution. It stores
2417 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002418 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002419static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002420{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002421 c->mode = stream->be->mode;
2422 switch (c->mode) {
2423 case PR_MODE_HTTP:
2424 c->data.http.dir = opt & SMP_OPT_DIR;
2425 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2426 c->data.http.state = stream->txn->req.msg_state;
2427 else
2428 c->data.http.state = stream->txn->rsp.msg_state;
2429 break;
2430 default:
2431 break;
2432 }
2433}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002434
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002435/* This function is called after the Lua execution. it
2436 * returns true if the parser state is consistent, otherwise,
2437 * it return false.
2438 *
2439 * In HTTP mode, the parser state must be in the same state
2440 * or greater when we exit the function. Even if we do a
2441 * control yield. This prevent to break the HTTP message
2442 * from the Lua code.
2443 */
2444static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2445{
2446 if (c->mode != stream->be->mode)
2447 return 0;
2448
2449 switch (c->mode) {
2450 case PR_MODE_HTTP:
2451 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002452 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002453 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2454 return stream->txn->req.msg_state >= c->data.http.state;
2455 else
2456 return stream->txn->rsp.msg_state >= c->data.http.state;
2457 default:
2458 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002459 }
2460 return 1;
2461}
2462
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002463/* Returns the struct hlua_channel join to the class channel in the
2464 * stack entry "ud" or throws an argument error.
2465 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002466__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002467{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002468 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002469}
2470
Willy Tarreau47860ed2015-03-10 14:07:50 +01002471/* Pushes the channel onto the top of the stack. If the stask does not have a
2472 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002473 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002474static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002475{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002476 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002477 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002478 return 0;
2479
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002480 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002481 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002482 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002483
2484 /* Pop a class sesison metatable and affect it to the userdata. */
2485 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2486 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002487 return 1;
2488}
2489
2490/* Duplicate all the data present in the input channel and put it
2491 * in a string LUA variables. Returns -1 and push a nil value in
2492 * the stack if the channel is closed and all the data are consumed,
2493 * returns 0 if no data are available, otherwise it returns the length
2494 * of the builded string.
2495 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002496static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002497{
2498 char *blk1;
2499 char *blk2;
2500 int len1;
2501 int len2;
2502 int ret;
2503 luaL_Buffer b;
2504
Willy Tarreau47860ed2015-03-10 14:07:50 +01002505 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002506 if (unlikely(ret == 0))
2507 return 0;
2508
2509 if (unlikely(ret < 0)) {
2510 lua_pushnil(L);
2511 return -1;
2512 }
2513
2514 luaL_buffinit(L, &b);
2515 luaL_addlstring(&b, blk1, len1);
2516 if (unlikely(ret == 2))
2517 luaL_addlstring(&b, blk2, len2);
2518 luaL_pushresult(&b);
2519
2520 if (unlikely(ret == 2))
2521 return len1 + len2;
2522 return len1;
2523}
2524
2525/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2526 * a yield. This function keep the data in the buffer.
2527 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002528__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002529{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002530 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002531
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002532 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2533
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002534 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002535 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002536 return 1;
2537}
2538
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002539/* Check arguments for the function "hlua_channel_dup_yield". */
2540__LJMP static int hlua_channel_dup(lua_State *L)
2541{
2542 MAY_LJMP(check_args(L, 1, "dup"));
2543 MAY_LJMP(hlua_checkchannel(L, 1));
2544 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2545}
2546
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002547/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2548 * a yield. This function consumes the data in the buffer. It returns
2549 * a string containing the data or a nil pointer if no data are available
2550 * and the channel is closed.
2551 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002552__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002553{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002554 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002555 int ret;
2556
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002557 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002558
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002559 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002560 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002561 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002562
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002563 if (unlikely(ret == -1))
2564 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002565
Willy Tarreau47860ed2015-03-10 14:07:50 +01002566 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002567 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002568 return 1;
2569}
2570
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002571/* Check arguments for the fucntion "hlua_channel_get_yield". */
2572__LJMP static int hlua_channel_get(lua_State *L)
2573{
2574 MAY_LJMP(check_args(L, 1, "get"));
2575 MAY_LJMP(hlua_checkchannel(L, 1));
2576 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2577}
2578
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002579/* This functions consumes and returns one line. If the channel is closed,
2580 * and the last data does not contains a final '\n', the data are returned
2581 * without the final '\n'. When no more data are avalaible, it returns nil
2582 * value.
2583 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002584__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002585{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002586 char *blk1;
2587 char *blk2;
2588 int len1;
2589 int len2;
2590 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002591 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002592 int ret;
2593 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002594
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002595 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2596
Willy Tarreau47860ed2015-03-10 14:07:50 +01002597 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002598 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002599 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002600
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002601 if (ret == -1) {
2602 lua_pushnil(L);
2603 return 1;
2604 }
2605
2606 luaL_buffinit(L, &b);
2607 luaL_addlstring(&b, blk1, len1);
2608 len = len1;
2609 if (unlikely(ret == 2)) {
2610 luaL_addlstring(&b, blk2, len2);
2611 len += len2;
2612 }
2613 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002614 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002615 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002616 return 1;
2617}
2618
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002619/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2620__LJMP static int hlua_channel_getline(lua_State *L)
2621{
2622 MAY_LJMP(check_args(L, 1, "getline"));
2623 MAY_LJMP(hlua_checkchannel(L, 1));
2624 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2625}
2626
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002627/* This function takes a string as input, and append it at the
2628 * input side of channel. If the data is too big, but a space
2629 * is probably available after sending some data, the function
2630 * yield. If the data is bigger than the buffer, or if the
2631 * channel is closed, it returns -1. otherwise, it returns the
2632 * amount of data writed.
2633 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002634__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002635{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002636 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002637 size_t len;
2638 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2639 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2640 int ret;
2641 int max;
2642
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002643 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2644 * the request buffer if its not required.
2645 */
2646 if (chn->buf->size == 0) {
2647 si_applet_cant_put(chn_prod(chn));
2648 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2649 }
2650
Willy Tarreau47860ed2015-03-10 14:07:50 +01002651 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002652 if (max > len - l)
2653 max = len - l;
2654
Willy Tarreau47860ed2015-03-10 14:07:50 +01002655 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002656 if (ret == -2 || ret == -3) {
2657 lua_pushinteger(L, -1);
2658 return 1;
2659 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002660 if (ret == -1) {
2661 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002662 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002663 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002664 l += ret;
2665 lua_pop(L, 1);
2666 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002667 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002668
Willy Tarreau47860ed2015-03-10 14:07:50 +01002669 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2670 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002671 /* There are no space avalaible, and the output buffer is empty.
2672 * in this case, we cannot add more data, so we cannot yield,
2673 * we return the amount of copyied data.
2674 */
2675 return 1;
2676 }
2677 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002678 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002679 return 1;
2680}
2681
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002682/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002683 * of the writed string, or -1 if the channel is closed or if the
2684 * buffer size is too little for the data.
2685 */
2686__LJMP static int hlua_channel_append(lua_State *L)
2687{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002688 size_t len;
2689
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002690 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002691 MAY_LJMP(hlua_checkchannel(L, 1));
2692 MAY_LJMP(luaL_checklstring(L, 2, &len));
2693 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002694 lua_pushinteger(L, 0);
2695
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002696 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002697}
2698
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002699/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002700 * his process by cleaning the buffer. The result is a replacement
2701 * of the current data. It returns the length of the writed string,
2702 * or -1 if the channel is closed or if the buffer size is too
2703 * little for the data.
2704 */
2705__LJMP static int hlua_channel_set(lua_State *L)
2706{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002707 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002708
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002709 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002710 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002711 lua_pushinteger(L, 0);
2712
Willy Tarreau47860ed2015-03-10 14:07:50 +01002713 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002714
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002715 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002716}
2717
2718/* Append data in the output side of the buffer. This data is immediatly
2719 * sent. The fcuntion returns the ammount of data writed. If the buffer
2720 * cannot contains the data, the function yield. The function returns -1
2721 * if the channel is closed.
2722 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002723__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002724{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002725 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002726 size_t len;
2727 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2728 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2729 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002730 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002731
Willy Tarreau47860ed2015-03-10 14:07:50 +01002732 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002733 lua_pushinteger(L, -1);
2734 return 1;
2735 }
2736
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002737 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2738 * the request buffer if its not required.
2739 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002740 if (chn->buf->size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002741 si_applet_cant_put(chn_prod(chn));
2742 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002743 }
2744
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002745 /* the writed data will be immediatly sent, so we can check
2746 * the avalaible space without taking in account the reserve.
2747 * The reserve is guaranted for the processing of incoming
2748 * data, because the buffer will be flushed.
2749 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002750 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002751
2752 /* If there are no space avalaible, and the output buffer is empty.
2753 * in this case, we cannot add more data, so we cannot yield,
2754 * we return the amount of copyied data.
2755 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002756 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002757 return 1;
2758
2759 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002760 if (max > len - l)
2761 max = len - l;
2762
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002763 /* The buffer avalaible size may be not contiguous. This test
2764 * detects a non contiguous buffer and realign it.
2765 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002766 if (bi_space_for_replace(chn->buf) < max)
2767 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002768
2769 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002770 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002771
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002772 /* buffer replace considers that the input part is filled.
2773 * so, I must forward these new data in the output part.
2774 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002775 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002776
2777 l += max;
2778 lua_pop(L, 1);
2779 lua_pushinteger(L, l);
2780
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002781 /* If there are no space avalaible, and the output buffer is empty.
2782 * in this case, we cannot add more data, so we cannot yield,
2783 * we return the amount of copyied data.
2784 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002785 max = chn->buf->size - buffer_len(chn->buf);
2786 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002787 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002788
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002789 if (l < len) {
2790 /* If we are waiting for space in the response buffer, we
2791 * must set the flag WAKERESWR. This flag required the task
2792 * wake up if any activity is detected on the response buffer.
2793 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002794 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002795 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002796 else
2797 HLUA_SET_WAKEREQWR(hlua);
2798 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002799 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002800
2801 return 1;
2802}
2803
2804/* Just a wraper of "_hlua_channel_send". This wrapper permits
2805 * yield the LUA process, and resume it without checking the
2806 * input arguments.
2807 */
2808__LJMP static int hlua_channel_send(lua_State *L)
2809{
2810 MAY_LJMP(check_args(L, 2, "send"));
2811 lua_pushinteger(L, 0);
2812
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002813 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002814}
2815
2816/* This function forward and amount of butes. The data pass from
2817 * the input side of the buffer to the output side, and can be
2818 * forwarded. This function never fails.
2819 *
2820 * The Lua function takes an amount of bytes to be forwarded in
2821 * imput. It returns the number of bytes forwarded.
2822 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002823__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002824{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002825 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002826 int len;
2827 int l;
2828 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002829 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002830
2831 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2832 len = MAY_LJMP(luaL_checkinteger(L, 2));
2833 l = MAY_LJMP(luaL_checkinteger(L, -1));
2834
2835 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002836 if (max > chn->buf->i)
2837 max = chn->buf->i;
2838 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002839 l += max;
2840
2841 lua_pop(L, 1);
2842 lua_pushinteger(L, l);
2843
2844 /* Check if it miss bytes to forward. */
2845 if (l < len) {
2846 /* The the input channel or the output channel are closed, we
2847 * must return the amount of data forwarded.
2848 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002849 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002850 return 1;
2851
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002852 /* If we are waiting for space data in the response buffer, we
2853 * must set the flag WAKERESWR. This flag required the task
2854 * wake up if any activity is detected on the response buffer.
2855 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002856 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002857 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002858 else
2859 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002860
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002861 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002862 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002863 }
2864
2865 return 1;
2866}
2867
2868/* Just check the input and prepare the stack for the previous
2869 * function "hlua_channel_forward_yield"
2870 */
2871__LJMP static int hlua_channel_forward(lua_State *L)
2872{
2873 MAY_LJMP(check_args(L, 2, "forward"));
2874 MAY_LJMP(hlua_checkchannel(L, 1));
2875 MAY_LJMP(luaL_checkinteger(L, 2));
2876
2877 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002878 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002879}
2880
2881/* Just returns the number of bytes available in the input
2882 * side of the buffer. This function never fails.
2883 */
2884__LJMP static int hlua_channel_get_in_len(lua_State *L)
2885{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002886 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002887
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002888 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002889 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002890 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002891 return 1;
2892}
2893
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01002894/* Returns true if the channel is full. */
2895__LJMP static int hlua_channel_is_full(lua_State *L)
2896{
2897 struct channel *chn;
2898 int rem;
2899
2900 MAY_LJMP(check_args(L, 1, "is_full"));
2901 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2902
2903 rem = chn->buf->size;
2904 rem -= chn->buf->o; /* Output size */
2905 rem -= chn->buf->i; /* Input size */
2906 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
2907
2908 lua_pushboolean(L, rem <= 0);
2909 return 1;
2910}
2911
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002912/* Just returns the number of bytes available in the output
2913 * side of the buffer. This function never fails.
2914 */
2915__LJMP static int hlua_channel_get_out_len(lua_State *L)
2916{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002917 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002918
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002919 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002920 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002921 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002922 return 1;
2923}
2924
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002925/*
2926 *
2927 *
2928 * Class Fetches
2929 *
2930 *
2931 */
2932
2933/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002934 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002935 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002936__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002937{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002938 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002939}
2940
2941/* This function creates and push in the stack a fetch object according
2942 * with a current TXN.
2943 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002944static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002945{
Willy Tarreau7073c472015-04-06 11:15:40 +02002946 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002947
2948 /* Check stack size. */
2949 if (!lua_checkstack(L, 3))
2950 return 0;
2951
2952 /* Create the object: obj[0] = userdata.
2953 * Note that the base of the Fetches object is the
2954 * transaction object.
2955 */
2956 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002957 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002958 lua_rawseti(L, -2, 0);
2959
Willy Tarreau7073c472015-04-06 11:15:40 +02002960 hsmp->s = txn->s;
2961 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01002962 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002963 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002964
2965 /* Pop a class sesison metatable and affect it to the userdata. */
2966 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2967 lua_setmetatable(L, -2);
2968
2969 return 1;
2970}
2971
2972/* This function is an LUA binding. It is called with each sample-fetch.
2973 * It uses closure argument to store the associated sample-fetch. It
2974 * returns only one argument or throws an error. An error is thrown
2975 * only if an error is encountered during the argument parsing. If
2976 * the "sample-fetch" function fails, nil is returned.
2977 */
2978__LJMP static int hlua_run_sample_fetch(lua_State *L)
2979{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002980 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002981 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002982 struct arg args[ARGM_NBARGS + 1];
2983 int i;
2984 struct sample smp;
2985
2986 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002987 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002988
2989 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002990 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002991
Thierry FOURNIERca988662015-12-20 18:43:03 +01002992 /* Check execution authorization. */
2993 if (f->use & SMP_USE_HTTP_ANY &&
2994 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
2995 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
2996 "is not available in Lua services", f->kw);
2997 WILL_LJMP(lua_error(L));
2998 }
2999
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003000 /* Get extra arguments. */
3001 for (i = 0; i < lua_gettop(L) - 1; i++) {
3002 if (i >= ARGM_NBARGS)
3003 break;
3004 hlua_lua2arg(L, i + 2, &args[i]);
3005 }
3006 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003007 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003008
3009 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003010 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003011
3012 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003013 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003014 lua_pushfstring(L, "error in arguments");
3015 WILL_LJMP(lua_error(L));
3016 }
3017
3018 /* Initialise the sample. */
3019 memset(&smp, 0, sizeof(smp));
3020
3021 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003022 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003023 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003024 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003025 lua_pushstring(L, "");
3026 else
3027 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003028 return 1;
3029 }
3030
3031 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003032 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003033 hlua_smp2lua_str(L, &smp);
3034 else
3035 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003036 return 1;
3037}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003038
3039/*
3040 *
3041 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003042 * Class Converters
3043 *
3044 *
3045 */
3046
3047/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003048 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003049 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003050__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003051{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003052 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003053}
3054
3055/* This function creates and push in the stack a Converters object
3056 * according with a current TXN.
3057 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003058static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003059{
Willy Tarreau7073c472015-04-06 11:15:40 +02003060 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003061
3062 /* Check stack size. */
3063 if (!lua_checkstack(L, 3))
3064 return 0;
3065
3066 /* Create the object: obj[0] = userdata.
3067 * Note that the base of the Converters object is the
3068 * same than the TXN object.
3069 */
3070 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003071 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003072 lua_rawseti(L, -2, 0);
3073
Willy Tarreau7073c472015-04-06 11:15:40 +02003074 hsmp->s = txn->s;
3075 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003076 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003077 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003078
Willy Tarreau87b09662015-04-03 00:22:06 +02003079 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003080 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3081 lua_setmetatable(L, -2);
3082
3083 return 1;
3084}
3085
3086/* This function is an LUA binding. It is called with each converter.
3087 * It uses closure argument to store the associated converter. It
3088 * returns only one argument or throws an error. An error is thrown
3089 * only if an error is encountered during the argument parsing. If
3090 * the converter function function fails, nil is returned.
3091 */
3092__LJMP static int hlua_run_sample_conv(lua_State *L)
3093{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003094 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003095 struct sample_conv *conv;
3096 struct arg args[ARGM_NBARGS + 1];
3097 int i;
3098 struct sample smp;
3099
3100 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003101 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003102
3103 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003104 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003105
3106 /* Get extra arguments. */
3107 for (i = 0; i < lua_gettop(L) - 2; i++) {
3108 if (i >= ARGM_NBARGS)
3109 break;
3110 hlua_lua2arg(L, i + 3, &args[i]);
3111 }
3112 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003113 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003114
3115 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003116 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003117
3118 /* Run the special args checker. */
3119 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3120 hlua_pusherror(L, "error in arguments");
3121 WILL_LJMP(lua_error(L));
3122 }
3123
3124 /* Initialise the sample. */
3125 if (!hlua_lua2smp(L, 2, &smp)) {
3126 hlua_pusherror(L, "error in the input argument");
3127 WILL_LJMP(lua_error(L));
3128 }
3129
Willy Tarreau1777ea62016-03-10 16:15:46 +01003130 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3131
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003132 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003133 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003134 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003135 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003136 WILL_LJMP(lua_error(L));
3137 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003138 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3139 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003140 hlua_pusherror(L, "error during the input argument casting");
3141 WILL_LJMP(lua_error(L));
3142 }
3143
3144 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003145 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003146 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003147 lua_pushstring(L, "");
3148 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003149 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003150 return 1;
3151 }
3152
3153 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003154 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003155 hlua_smp2lua_str(L, &smp);
3156 else
3157 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003158 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003159}
3160
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003161/*
3162 *
3163 *
3164 * Class AppletTCP
3165 *
3166 *
3167 */
3168
3169/* Returns a struct hlua_txn if the stack entry "ud" is
3170 * a class stream, otherwise it throws an error.
3171 */
3172__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3173{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003174 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003175}
3176
3177/* This function creates and push in the stack an Applet object
3178 * according with a current TXN.
3179 */
3180static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3181{
3182 struct hlua_appctx *appctx;
3183 struct stream_interface *si = ctx->owner;
3184 struct stream *s = si_strm(si);
3185 struct proxy *p = s->be;
3186
3187 /* Check stack size. */
3188 if (!lua_checkstack(L, 3))
3189 return 0;
3190
3191 /* Create the object: obj[0] = userdata.
3192 * Note that the base of the Converters object is the
3193 * same than the TXN object.
3194 */
3195 lua_newtable(L);
3196 appctx = lua_newuserdata(L, sizeof(*appctx));
3197 lua_rawseti(L, -2, 0);
3198 appctx->appctx = ctx;
3199 appctx->htxn.s = s;
3200 appctx->htxn.p = p;
3201
3202 /* Create the "f" field that contains a list of fetches. */
3203 lua_pushstring(L, "f");
3204 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3205 return 0;
3206 lua_settable(L, -3);
3207
3208 /* Create the "sf" field that contains a list of stringsafe fetches. */
3209 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003210 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003211 return 0;
3212 lua_settable(L, -3);
3213
3214 /* Create the "c" field that contains a list of converters. */
3215 lua_pushstring(L, "c");
3216 if (!hlua_converters_new(L, &appctx->htxn, 0))
3217 return 0;
3218 lua_settable(L, -3);
3219
3220 /* Create the "sc" field that contains a list of stringsafe converters. */
3221 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003222 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003223 return 0;
3224 lua_settable(L, -3);
3225
3226 /* Pop a class stream metatable and affect it to the table. */
3227 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3228 lua_setmetatable(L, -2);
3229
3230 return 1;
3231}
3232
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003233__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3234{
3235 struct hlua_appctx *appctx;
3236 struct stream *s;
3237 const char *name;
3238 size_t len;
3239 struct sample smp;
3240
3241 MAY_LJMP(check_args(L, 3, "set_var"));
3242
3243 /* It is useles to retrieve the stream, but this function
3244 * runs only in a stream context.
3245 */
3246 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3247 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3248 s = appctx->htxn.s;
3249
3250 /* Converts the third argument in a sample. */
3251 hlua_lua2smp(L, 3, &smp);
3252
3253 /* Store the sample in a variable. */
3254 smp_set_owner(&smp, s->be, s->sess, s, 0);
3255 vars_set_by_name(name, len, &smp);
3256 return 0;
3257}
3258
3259__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3260{
3261 struct hlua_appctx *appctx;
3262 struct stream *s;
3263 const char *name;
3264 size_t len;
3265 struct sample smp;
3266
3267 MAY_LJMP(check_args(L, 2, "unset_var"));
3268
3269 /* It is useles to retrieve the stream, but this function
3270 * runs only in a stream context.
3271 */
3272 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3273 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3274 s = appctx->htxn.s;
3275
3276 /* Unset the variable. */
3277 smp_set_owner(&smp, s->be, s->sess, s, 0);
3278 vars_unset_by_name(name, len, &smp);
3279 return 0;
3280}
3281
3282__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3283{
3284 struct hlua_appctx *appctx;
3285 struct stream *s;
3286 const char *name;
3287 size_t len;
3288 struct sample smp;
3289
3290 MAY_LJMP(check_args(L, 2, "get_var"));
3291
3292 /* It is useles to retrieve the stream, but this function
3293 * runs only in a stream context.
3294 */
3295 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3296 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3297 s = appctx->htxn.s;
3298
3299 smp_set_owner(&smp, s->be, s->sess, s, 0);
3300 if (!vars_get_by_name(name, len, &smp)) {
3301 lua_pushnil(L);
3302 return 1;
3303 }
3304
3305 return hlua_smp2lua(L, &smp);
3306}
3307
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003308__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3309{
3310 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3311 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003312 struct hlua *hlua;
3313
3314 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003315 if (!s->hlua)
3316 return 0;
3317 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003318
3319 MAY_LJMP(check_args(L, 2, "set_priv"));
3320
3321 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003322 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003323
3324 /* Get and store new value. */
3325 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3326 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3327
3328 return 0;
3329}
3330
3331__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3332{
3333 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3334 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003335 struct hlua *hlua;
3336
3337 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003338 if (!s->hlua) {
3339 lua_pushnil(L);
3340 return 1;
3341 }
3342 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003343
3344 /* Push configuration index in the stack. */
3345 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3346
3347 return 1;
3348}
3349
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003350/* If expected data not yet available, it returns a yield. This function
3351 * consumes the data in the buffer. It returns a string containing the
3352 * data. This string can be empty.
3353 */
3354__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3355{
3356 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3357 struct stream_interface *si = appctx->appctx->owner;
3358 int ret;
3359 char *blk1;
3360 int len1;
3361 char *blk2;
3362 int len2;
3363
3364 /* Read the maximum amount of data avalaible. */
3365 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3366
3367 /* Data not yet avalaible. return yield. */
3368 if (ret == 0) {
3369 si_applet_cant_get(si);
3370 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3371 }
3372
3373 /* End of data: commit the total strings and return. */
3374 if (ret < 0) {
3375 luaL_pushresult(&appctx->b);
3376 return 1;
3377 }
3378
3379 /* Ensure that the block 2 length is usable. */
3380 if (ret == 1)
3381 len2 = 0;
3382
3383 /* dont check the max length read and dont check. */
3384 luaL_addlstring(&appctx->b, blk1, len1);
3385 luaL_addlstring(&appctx->b, blk2, len2);
3386
3387 /* Consume input channel output buffer data. */
3388 bo_skip(si_oc(si), len1 + len2);
3389 luaL_pushresult(&appctx->b);
3390 return 1;
3391}
3392
3393/* Check arguments for the fucntion "hlua_channel_get_yield". */
3394__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3395{
3396 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3397
3398 /* Initialise the string catenation. */
3399 luaL_buffinit(L, &appctx->b);
3400
3401 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3402}
3403
3404/* If expected data not yet available, it returns a yield. This function
3405 * consumes the data in the buffer. It returns a string containing the
3406 * data. This string can be empty.
3407 */
3408__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3409{
3410 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3411 struct stream_interface *si = appctx->appctx->owner;
3412 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3413 int ret;
3414 char *blk1;
3415 int len1;
3416 char *blk2;
3417 int len2;
3418
3419 /* Read the maximum amount of data avalaible. */
3420 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3421
3422 /* Data not yet avalaible. return yield. */
3423 if (ret == 0) {
3424 si_applet_cant_get(si);
3425 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3426 }
3427
3428 /* End of data: commit the total strings and return. */
3429 if (ret < 0) {
3430 luaL_pushresult(&appctx->b);
3431 return 1;
3432 }
3433
3434 /* Ensure that the block 2 length is usable. */
3435 if (ret == 1)
3436 len2 = 0;
3437
3438 if (len == -1) {
3439
3440 /* If len == -1, catenate all the data avalaile and
3441 * yield because we want to get all the data until
3442 * the end of data stream.
3443 */
3444 luaL_addlstring(&appctx->b, blk1, len1);
3445 luaL_addlstring(&appctx->b, blk2, len2);
3446 bo_skip(si_oc(si), len1 + len2);
3447 si_applet_cant_get(si);
3448 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3449
3450 } else {
3451
3452 /* Copy the fisrt block caping to the length required. */
3453 if (len1 > len)
3454 len1 = len;
3455 luaL_addlstring(&appctx->b, blk1, len1);
3456 len -= len1;
3457
3458 /* Copy the second block. */
3459 if (len2 > len)
3460 len2 = len;
3461 luaL_addlstring(&appctx->b, blk2, len2);
3462 len -= len2;
3463
3464 /* Consume input channel output buffer data. */
3465 bo_skip(si_oc(si), len1 + len2);
3466
3467 /* If we are no other data avalaible, yield waiting for new data. */
3468 if (len > 0) {
3469 lua_pushinteger(L, len);
3470 lua_replace(L, 2);
3471 si_applet_cant_get(si);
3472 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3473 }
3474
3475 /* return the result. */
3476 luaL_pushresult(&appctx->b);
3477 return 1;
3478 }
3479
3480 /* we never executes this */
3481 hlua_pusherror(L, "Lua: internal error");
3482 WILL_LJMP(lua_error(L));
3483 return 0;
3484}
3485
3486/* Check arguments for the fucntion "hlua_channel_get_yield". */
3487__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3488{
3489 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3490 int len = -1;
3491
3492 if (lua_gettop(L) > 2)
3493 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3494 if (lua_gettop(L) >= 2) {
3495 len = MAY_LJMP(luaL_checkinteger(L, 2));
3496 lua_pop(L, 1);
3497 }
3498
3499 /* Confirm or set the required length */
3500 lua_pushinteger(L, len);
3501
3502 /* Initialise the string catenation. */
3503 luaL_buffinit(L, &appctx->b);
3504
3505 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3506}
3507
3508/* Append data in the output side of the buffer. This data is immediatly
3509 * sent. The fcuntion returns the ammount of data writed. If the buffer
3510 * cannot contains the data, the function yield. The function returns -1
3511 * if the channel is closed.
3512 */
3513__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3514{
3515 size_t len;
3516 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3517 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3518 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3519 struct stream_interface *si = appctx->appctx->owner;
3520 struct channel *chn = si_ic(si);
3521 int max;
3522
3523 /* Get the max amount of data which can write as input in the channel. */
3524 max = channel_recv_max(chn);
3525 if (max > (len - l))
3526 max = len - l;
3527
3528 /* Copy data. */
3529 bi_putblk(chn, str + l, max);
3530
3531 /* update counters. */
3532 l += max;
3533 lua_pop(L, 1);
3534 lua_pushinteger(L, l);
3535
3536 /* If some data is not send, declares the situation to the
3537 * applet, and returns a yield.
3538 */
3539 if (l < len) {
3540 si_applet_cant_put(si);
3541 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3542 }
3543
3544 return 1;
3545}
3546
3547/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3548 * yield the LUA process, and resume it without checking the
3549 * input arguments.
3550 */
3551__LJMP static int hlua_applet_tcp_send(lua_State *L)
3552{
3553 MAY_LJMP(check_args(L, 2, "send"));
3554 lua_pushinteger(L, 0);
3555
3556 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3557}
3558
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003559/*
3560 *
3561 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003562 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003563 *
3564 *
3565 */
3566
3567/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003568 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003569 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003570__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003571{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003572 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003573}
3574
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003575/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003576 * according with a current TXN.
3577 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003578static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003579{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003580 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003581 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003582 struct stream_interface *si = ctx->owner;
3583 struct stream *s = si_strm(si);
3584 struct proxy *px = s->be;
3585 struct http_txn *txn = s->txn;
3586 const char *path;
3587 const char *end;
3588 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003589
3590 /* Check stack size. */
3591 if (!lua_checkstack(L, 3))
3592 return 0;
3593
3594 /* Create the object: obj[0] = userdata.
3595 * Note that the base of the Converters object is the
3596 * same than the TXN object.
3597 */
3598 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003599 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003600 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003601 appctx->appctx = ctx;
3602 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003603 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003604 appctx->htxn.s = s;
3605 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003606
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003607 /* Create the "f" field that contains a list of fetches. */
3608 lua_pushstring(L, "f");
3609 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3610 return 0;
3611 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003612
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003613 /* Create the "sf" field that contains a list of stringsafe fetches. */
3614 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003615 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003616 return 0;
3617 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003618
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003619 /* Create the "c" field that contains a list of converters. */
3620 lua_pushstring(L, "c");
3621 if (!hlua_converters_new(L, &appctx->htxn, 0))
3622 return 0;
3623 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003624
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003625 /* Create the "sc" field that contains a list of stringsafe converters. */
3626 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003627 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003628 return 0;
3629 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003630
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003631 /* Stores the request method. */
3632 lua_pushstring(L, "method");
3633 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3634 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003635
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003636 /* Stores the http version. */
3637 lua_pushstring(L, "version");
3638 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3639 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003640
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003641 /* creates an array of headers. hlua_http_get_headers() crates and push
3642 * the array on the top of the stack.
3643 */
3644 lua_pushstring(L, "headers");
3645 htxn.s = s;
3646 htxn.p = px;
3647 htxn.dir = SMP_OPT_DIR_REQ;
3648 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3649 return 0;
3650 lua_settable(L, -3);
3651
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003652 /* Get path and qs */
3653 path = http_get_path(txn);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003654 if (path) {
3655 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3656 p = path;
3657 while (p < end && *p != '?')
3658 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003659
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003660 /* Stores the request path. */
3661 lua_pushstring(L, "path");
3662 lua_pushlstring(L, path, p - path);
3663 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003664
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003665 /* Stores the query string. */
3666 lua_pushstring(L, "qs");
3667 if (*p == '?')
3668 p++;
3669 lua_pushlstring(L, p, end - p);
3670 lua_settable(L, -3);
3671 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003672
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003673 /* Stores the request path. */
3674 lua_pushstring(L, "length");
3675 lua_pushinteger(L, txn->req.body_len);
3676 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003677
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003678 /* Create an array of HTTP request headers. */
3679 lua_pushstring(L, "headers");
3680 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3681 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003682
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003683 /* Create an empty array of HTTP request headers. */
3684 lua_pushstring(L, "response");
3685 lua_newtable(L);
3686 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003687
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003688 /* Pop a class stream metatable and affect it to the table. */
3689 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3690 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003691
3692 return 1;
3693}
3694
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003695__LJMP static int hlua_applet_http_set_var(lua_State *L)
3696{
3697 struct hlua_appctx *appctx;
3698 struct stream *s;
3699 const char *name;
3700 size_t len;
3701 struct sample smp;
3702
3703 MAY_LJMP(check_args(L, 3, "set_var"));
3704
3705 /* It is useles to retrieve the stream, but this function
3706 * runs only in a stream context.
3707 */
3708 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3709 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3710 s = appctx->htxn.s;
3711
3712 /* Converts the third argument in a sample. */
3713 hlua_lua2smp(L, 3, &smp);
3714
3715 /* Store the sample in a variable. */
3716 smp_set_owner(&smp, s->be, s->sess, s, 0);
3717 vars_set_by_name(name, len, &smp);
3718 return 0;
3719}
3720
3721__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3722{
3723 struct hlua_appctx *appctx;
3724 struct stream *s;
3725 const char *name;
3726 size_t len;
3727 struct sample smp;
3728
3729 MAY_LJMP(check_args(L, 2, "unset_var"));
3730
3731 /* It is useles to retrieve the stream, but this function
3732 * runs only in a stream context.
3733 */
3734 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3735 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3736 s = appctx->htxn.s;
3737
3738 /* Unset the variable. */
3739 smp_set_owner(&smp, s->be, s->sess, s, 0);
3740 vars_unset_by_name(name, len, &smp);
3741 return 0;
3742}
3743
3744__LJMP static int hlua_applet_http_get_var(lua_State *L)
3745{
3746 struct hlua_appctx *appctx;
3747 struct stream *s;
3748 const char *name;
3749 size_t len;
3750 struct sample smp;
3751
3752 MAY_LJMP(check_args(L, 2, "get_var"));
3753
3754 /* It is useles to retrieve the stream, but this function
3755 * runs only in a stream context.
3756 */
3757 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3758 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3759 s = appctx->htxn.s;
3760
3761 smp_set_owner(&smp, s->be, s->sess, s, 0);
3762 if (!vars_get_by_name(name, len, &smp)) {
3763 lua_pushnil(L);
3764 return 1;
3765 }
3766
3767 return hlua_smp2lua(L, &smp);
3768}
3769
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003770__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3771{
3772 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3773 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003774 struct hlua *hlua;
3775
3776 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003777 if (!s->hlua)
3778 return 0;
3779 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003780
3781 MAY_LJMP(check_args(L, 2, "set_priv"));
3782
3783 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003784 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003785
3786 /* Get and store new value. */
3787 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3788 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3789
3790 return 0;
3791}
3792
3793__LJMP static int hlua_applet_http_get_priv(lua_State *L)
3794{
3795 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3796 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003797 struct hlua *hlua;
3798
3799 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003800 if (!s->hlua) {
3801 lua_pushnil(L);
3802 return 1;
3803 }
3804 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003805
3806 /* Push configuration index in the stack. */
3807 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3808
3809 return 1;
3810}
3811
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003812/* If expected data not yet available, it returns a yield. This function
3813 * consumes the data in the buffer. It returns a string containing the
3814 * data. This string can be empty.
3815 */
3816__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003817{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003818 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3819 struct stream_interface *si = appctx->appctx->owner;
3820 struct channel *chn = si_ic(si);
3821 int ret;
3822 char *blk1;
3823 int len1;
3824 char *blk2;
3825 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003826
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003827 /* Maybe we cant send a 100-continue ? */
3828 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3829 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3830 /* if ret == -2 or -3 the channel closed or the message si too
3831 * big for the buffers. We cant send anything. So, we ignoring
3832 * the error, considers that the 100-continue is sent, and try
3833 * to receive.
3834 * If ret is -1, we dont have room in the buffer, so we yield.
3835 */
3836 if (ret == -1) {
3837 si_applet_cant_put(si);
3838 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3839 }
3840 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3841 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003842
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003843 /* Check for the end of the data. */
3844 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3845 luaL_pushresult(&appctx->b);
3846 return 1;
3847 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003848
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003849 /* Read the maximum amount of data avalaible. */
3850 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003851
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003852 /* Data not yet avalaible. return yield. */
3853 if (ret == 0) {
3854 si_applet_cant_get(si);
3855 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3856 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003857
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003858 /* End of data: commit the total strings and return. */
3859 if (ret < 0) {
3860 luaL_pushresult(&appctx->b);
3861 return 1;
3862 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003863
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003864 /* Ensure that the block 2 length is usable. */
3865 if (ret == 1)
3866 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003867
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003868 /* Copy the fisrt block caping to the length required. */
3869 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3870 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3871 luaL_addlstring(&appctx->b, blk1, len1);
3872 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003873
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003874 /* Copy the second block. */
3875 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3876 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3877 luaL_addlstring(&appctx->b, blk2, len2);
3878 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003879
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003880 /* Consume input channel output buffer data. */
3881 bo_skip(si_oc(si), len1 + len2);
3882 luaL_pushresult(&appctx->b);
3883 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003884}
3885
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003886/* Check arguments for the fucntion "hlua_channel_get_yield". */
3887__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003888{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003889 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003890
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003891 /* Initialise the string catenation. */
3892 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003893
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003894 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003895}
3896
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003897/* If expected data not yet available, it returns a yield. This function
3898 * consumes the data in the buffer. It returns a string containing the
3899 * data. This string can be empty.
3900 */
3901__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003902{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003903 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3904 struct stream_interface *si = appctx->appctx->owner;
3905 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3906 struct channel *chn = si_ic(si);
3907 int ret;
3908 char *blk1;
3909 int len1;
3910 char *blk2;
3911 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003912
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003913 /* Maybe we cant send a 100-continue ? */
3914 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3915 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3916 /* if ret == -2 or -3 the channel closed or the message si too
3917 * big for the buffers. We cant send anything. So, we ignoring
3918 * the error, considers that the 100-continue is sent, and try
3919 * to receive.
3920 * If ret is -1, we dont have room in the buffer, so we yield.
3921 */
3922 if (ret == -1) {
3923 si_applet_cant_put(si);
3924 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3925 }
3926 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3927 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003928
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003929 /* Read the maximum amount of data avalaible. */
3930 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003931
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003932 /* Data not yet avalaible. return yield. */
3933 if (ret == 0) {
3934 si_applet_cant_get(si);
3935 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3936 }
3937
3938 /* End of data: commit the total strings and return. */
3939 if (ret < 0) {
3940 luaL_pushresult(&appctx->b);
3941 return 1;
3942 }
3943
3944 /* Ensure that the block 2 length is usable. */
3945 if (ret == 1)
3946 len2 = 0;
3947
3948 /* Copy the fisrt block caping to the length required. */
3949 if (len1 > len)
3950 len1 = len;
3951 luaL_addlstring(&appctx->b, blk1, len1);
3952 len -= len1;
3953
3954 /* Copy the second block. */
3955 if (len2 > len)
3956 len2 = len;
3957 luaL_addlstring(&appctx->b, blk2, len2);
3958 len -= len2;
3959
3960 /* Consume input channel output buffer data. */
3961 bo_skip(si_oc(si), len1 + len2);
3962 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
3963 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
3964
3965 /* If we are no other data avalaible, yield waiting for new data. */
3966 if (len > 0) {
3967 lua_pushinteger(L, len);
3968 lua_replace(L, 2);
3969 si_applet_cant_get(si);
3970 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3971 }
3972
3973 /* return the result. */
3974 luaL_pushresult(&appctx->b);
3975 return 1;
3976}
3977
3978/* Check arguments for the fucntion "hlua_channel_get_yield". */
3979__LJMP static int hlua_applet_http_recv(lua_State *L)
3980{
3981 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3982 int len = -1;
3983
3984 /* Check arguments. */
3985 if (lua_gettop(L) > 2)
3986 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3987 if (lua_gettop(L) >= 2) {
3988 len = MAY_LJMP(luaL_checkinteger(L, 2));
3989 lua_pop(L, 1);
3990 }
3991
3992 /* Check the required length */
3993 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3994 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3995 lua_pushinteger(L, len);
3996
3997 /* Initialise the string catenation. */
3998 luaL_buffinit(L, &appctx->b);
3999
4000 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4001}
4002
4003/* Append data in the output side of the buffer. This data is immediatly
4004 * sent. The fcuntion returns the ammount of data writed. If the buffer
4005 * cannot contains the data, the function yield. The function returns -1
4006 * if the channel is closed.
4007 */
4008__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4009{
4010 size_t len;
4011 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4012 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4013 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4014 struct stream_interface *si = appctx->appctx->owner;
4015 struct channel *chn = si_ic(si);
4016 int max;
4017
4018 /* Get the max amount of data which can write as input in the channel. */
4019 max = channel_recv_max(chn);
4020 if (max > (len - l))
4021 max = len - l;
4022
4023 /* Copy data. */
4024 bi_putblk(chn, str + l, max);
4025
4026 /* update counters. */
4027 l += max;
4028 lua_pop(L, 1);
4029 lua_pushinteger(L, l);
4030
4031 /* If some data is not send, declares the situation to the
4032 * applet, and returns a yield.
4033 */
4034 if (l < len) {
4035 si_applet_cant_put(si);
4036 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
4037 }
4038
4039 return 1;
4040}
4041
4042/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4043 * yield the LUA process, and resume it without checking the
4044 * input arguments.
4045 */
4046__LJMP static int hlua_applet_http_send(lua_State *L)
4047{
4048 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4049 size_t len;
4050 char hex[10];
4051
4052 MAY_LJMP(luaL_checklstring(L, 2, &len));
4053
4054 /* If transfer encoding chunked is selected, we surround the data
4055 * by chunk data.
4056 */
4057 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4058 snprintf(hex, 9, "%x", (unsigned int)len);
4059 lua_pushfstring(L, "%s\r\n", hex);
4060 lua_insert(L, 2); /* swap the last 2 entries. */
4061 lua_pushstring(L, "\r\n");
4062 lua_concat(L, 3);
4063 }
4064
4065 /* This interger is used for followinf the amount of data sent. */
4066 lua_pushinteger(L, 0);
4067
4068 /* We want to send some data. Headers must be sent. */
4069 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4070 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4071 WILL_LJMP(lua_error(L));
4072 }
4073
4074 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4075}
4076
4077__LJMP static int hlua_applet_http_addheader(lua_State *L)
4078{
4079 const char *name;
4080 int ret;
4081
4082 MAY_LJMP(hlua_checkapplet_http(L, 1));
4083 name = MAY_LJMP(luaL_checkstring(L, 2));
4084 MAY_LJMP(luaL_checkstring(L, 3));
4085
4086 /* Push in the stack the "response" entry. */
4087 ret = lua_getfield(L, 1, "response");
4088 if (ret != LUA_TTABLE) {
4089 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4090 "is expected as an array. %s found", lua_typename(L, ret));
4091 WILL_LJMP(lua_error(L));
4092 }
4093
4094 /* check if the header is already registered if it is not
4095 * the case, register it.
4096 */
4097 ret = lua_getfield(L, -1, name);
4098 if (ret == LUA_TNIL) {
4099
4100 /* Entry not found. */
4101 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4102
4103 /* Insert the new header name in the array in the top of the stack.
4104 * It left the new array in the top of the stack.
4105 */
4106 lua_newtable(L);
4107 lua_pushvalue(L, 2);
4108 lua_pushvalue(L, -2);
4109 lua_settable(L, -4);
4110
4111 } else if (ret != LUA_TTABLE) {
4112
4113 /* corruption error. */
4114 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4115 "is expected as an array. %s found", name, lua_typename(L, ret));
4116 WILL_LJMP(lua_error(L));
4117 }
4118
4119 /* Now the top od thestack is an array of values. We push
4120 * the header value as new entry.
4121 */
4122 lua_pushvalue(L, 3);
4123 ret = lua_rawlen(L, -2);
4124 lua_rawseti(L, -2, ret + 1);
4125 lua_pushboolean(L, 1);
4126 return 1;
4127}
4128
4129__LJMP static int hlua_applet_http_status(lua_State *L)
4130{
4131 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4132 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004133 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004134
4135 if (status < 100 || status > 599) {
4136 lua_pushboolean(L, 0);
4137 return 1;
4138 }
4139
4140 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004141 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004142 lua_pushboolean(L, 1);
4143 return 1;
4144}
4145
4146/* We will build the status line and the headers of the HTTP response.
4147 * We will try send at once if its not possible, we give back the hand
4148 * waiting for more room.
4149 */
4150__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4151{
4152 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4153 struct stream_interface *si = appctx->appctx->owner;
4154 struct channel *chn = si_ic(si);
4155 int ret;
4156 size_t len;
4157 const char *msg;
4158
4159 /* Get the message as the first argument on the stack. */
4160 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4161
4162 /* Send the message at once. */
4163 ret = bi_putblk(chn, msg, len);
4164
4165 /* if ret == -2 or -3 the channel closed or the message si too
4166 * big for the buffers.
4167 */
4168 if (ret == -2 || ret == -3) {
4169 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4170 WILL_LJMP(lua_error(L));
4171 }
4172
4173 /* If ret is -1, we dont have room in the buffer, so we yield. */
4174 if (ret == -1) {
4175 si_applet_cant_put(si);
4176 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4177 }
4178
4179 /* Headers sent, set the flag. */
4180 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4181 return 0;
4182}
4183
4184__LJMP static int hlua_applet_http_start_response(lua_State *L)
4185{
4186 struct chunk *tmp = get_trash_chunk();
4187 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004188 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02004189 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004190 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02004191 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004192 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004193 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004194 int hdr_chunked = 0;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004195 const char *reason = appctx->appctx->ctx.hlua_apphttp.reason;
4196
4197 if (reason == NULL)
4198 reason = get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004199
4200 /* Use the same http version than the request. */
4201 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004202 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004203 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004204 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004205
4206 /* Get the array associated to the field "response" in the object AppletHTTP. */
4207 lua_pushvalue(L, 0);
4208 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4209 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4210 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4211 WILL_LJMP(lua_error(L));
4212 }
4213
4214 /* Browse the list of headers. */
4215 lua_pushnil(L);
4216 while(lua_next(L, -2) != 0) {
4217
4218 /* We expect a string as -2. */
4219 if (lua_type(L, -2) != LUA_TSTRING) {
4220 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4221 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4222 lua_typename(L, lua_type(L, -2)));
4223 WILL_LJMP(lua_error(L));
4224 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004225 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004226
4227 /* We expect an array as -1. */
4228 if (lua_type(L, -1) != LUA_TTABLE) {
4229 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4230 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4231 name,
4232 lua_typename(L, lua_type(L, -1)));
4233 WILL_LJMP(lua_error(L));
4234 }
4235
4236 /* Browse the table who is on the top of the stack. */
4237 lua_pushnil(L);
4238 while(lua_next(L, -2) != 0) {
4239
4240 /* We expect a number as -2. */
4241 if (lua_type(L, -2) != LUA_TNUMBER) {
4242 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4243 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4244 name,
4245 lua_typename(L, lua_type(L, -2)));
4246 WILL_LJMP(lua_error(L));
4247 }
4248 id = lua_tointeger(L, -2);
4249
4250 /* We expect a string as -2. */
4251 if (lua_type(L, -1) != LUA_TSTRING) {
4252 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4253 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4254 name, id,
4255 lua_typename(L, lua_type(L, -1)));
4256 WILL_LJMP(lua_error(L));
4257 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004258 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004259
4260 /* Catenate a new header. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004261 if (tmp->len + name_len + 2 + value_len + 2 < tmp->size) {
4262 memcpy(tmp->str + tmp->len, name, name_len);
4263 tmp->len += name_len;
4264 tmp->str[tmp->len++] = ':';
4265 tmp->str[tmp->len++] = ' ';
4266
4267 memcpy(tmp->str + tmp->len, value, value_len);
4268 tmp->len += value_len;
4269 tmp->str[tmp->len++] = '\r';
4270 tmp->str[tmp->len++] = '\n';
4271 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004272
4273 /* Protocol checks. */
4274
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004275 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004276 * is done without control. If it contains a bad value,
4277 * the content-length remains negative so that we can
4278 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004279 */
Willy Tarreaua3294632017-08-23 11:24:47 +02004280 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004281 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004282
4283 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004284 if (name_len == 17 && value_len == 7 &&
4285 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004286 strcasecmp("chunked", value) == 0)
4287 hdr_chunked = 1;
4288
4289 /* Remove the array from the stack, and get next element with a remaining string. */
4290 lua_pop(L, 1);
4291 }
4292
4293 /* Remove the array from the stack, and get next element with a remaining string. */
4294 lua_pop(L, 1);
4295 }
4296
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004297 /* If we dont have a content-length set, and the HTTP version is 1.1
4298 * and the status code implies the presence of a message body, we must
4299 * announce a transfer encoding chunked. This is required by haproxy
4300 * for the keepalive compliance. If the applet annouces a transfer-encoding
4301 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004302 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004303 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004304 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
4305 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4306 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4307 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004308 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4309 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4310 }
4311
4312 /* Finalize headers. */
4313 chunk_appendf(tmp, "\r\n");
4314
4315 /* Remove the last entry and the array of headers */
4316 lua_pop(L, 2);
4317
4318 /* Push the headers block. */
4319 lua_pushlstring(L, tmp->str, tmp->len);
4320
4321 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4322}
4323
4324/*
4325 *
4326 *
4327 * Class HTTP
4328 *
4329 *
4330 */
4331
4332/* Returns a struct hlua_txn if the stack entry "ud" is
4333 * a class stream, otherwise it throws an error.
4334 */
4335__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4336{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004337 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004338}
4339
4340/* This function creates and push in the stack a HTTP object
4341 * according with a current TXN.
4342 */
4343static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4344{
4345 struct hlua_txn *htxn;
4346
4347 /* Check stack size. */
4348 if (!lua_checkstack(L, 3))
4349 return 0;
4350
4351 /* Create the object: obj[0] = userdata.
4352 * Note that the base of the Converters object is the
4353 * same than the TXN object.
4354 */
4355 lua_newtable(L);
4356 htxn = lua_newuserdata(L, sizeof(*htxn));
4357 lua_rawseti(L, -2, 0);
4358
4359 htxn->s = txn->s;
4360 htxn->p = txn->p;
4361
4362 /* Pop a class stream metatable and affect it to the table. */
4363 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4364 lua_setmetatable(L, -2);
4365
4366 return 1;
4367}
4368
4369/* This function creates ans returns an array of HTTP headers.
4370 * This function does not fails. It is used as wrapper with the
4371 * 2 following functions.
4372 */
4373__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4374{
4375 const char *cur_ptr, *cur_next, *p;
4376 int old_idx, cur_idx;
4377 struct hdr_idx_elem *cur_hdr;
4378 const char *hn, *hv;
4379 int hnl, hvl;
4380 int type;
4381 const char *in;
4382 char *out;
4383 int len;
4384
4385 /* Create the table. */
4386 lua_newtable(L);
4387
4388 if (!htxn->s->txn)
4389 return 1;
4390
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004391 /* Check if a valid response is parsed */
4392 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4393 return 1;
4394
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004395 /* Build array of headers. */
4396 old_idx = 0;
4397 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4398
4399 while (1) {
4400 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4401 if (!cur_idx)
4402 break;
4403 old_idx = cur_idx;
4404
4405 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4406 cur_ptr = cur_next;
4407 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4408
4409 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4410 * and the next header starts at cur_next. We'll check
4411 * this header in the list as well as against the default
4412 * rule.
4413 */
4414
4415 /* look for ': *'. */
4416 hn = cur_ptr;
4417 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4418 if (p >= cur_ptr+cur_hdr->len)
4419 continue;
4420 hnl = p - hn;
4421 p++;
4422 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4423 p++;
4424 if (p >= cur_ptr+cur_hdr->len)
4425 continue;
4426 hv = p;
4427 hvl = cur_ptr+cur_hdr->len-p;
4428
4429 /* Lowercase the key. Don't check the size of trash, it have
4430 * the size of one buffer and the input data contains in one
4431 * buffer.
4432 */
4433 out = trash.str;
4434 for (in=hn; in<hn+hnl; in++, out++)
4435 *out = tolower(*in);
4436 *out = '\0';
4437
4438 /* Check for existing entry:
4439 * assume that the table is on the top of the stack, and
4440 * push the key in the stack, the function lua_gettable()
4441 * perform the lookup.
4442 */
4443 lua_pushlstring(L, trash.str, hnl);
4444 lua_gettable(L, -2);
4445 type = lua_type(L, -1);
4446
4447 switch (type) {
4448 case LUA_TNIL:
4449 /* Table not found, create it. */
4450 lua_pop(L, 1); /* remove the nil value. */
4451 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4452 lua_newtable(L); /* create and push empty table. */
4453 lua_pushlstring(L, hv, hvl); /* push header value. */
4454 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4455 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4456 break;
4457
4458 case LUA_TTABLE:
4459 /* Entry found: push the value in the table. */
4460 len = lua_rawlen(L, -1);
4461 lua_pushlstring(L, hv, hvl); /* push header value. */
4462 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4463 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4464 break;
4465
4466 default:
4467 /* Other cases are errors. */
4468 hlua_pusherror(L, "internal error during the parsing of headers.");
4469 WILL_LJMP(lua_error(L));
4470 }
4471 }
4472
4473 return 1;
4474}
4475
4476__LJMP static int hlua_http_req_get_headers(lua_State *L)
4477{
4478 struct hlua_txn *htxn;
4479
4480 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4481 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4482
4483 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4484}
4485
4486__LJMP static int hlua_http_res_get_headers(lua_State *L)
4487{
4488 struct hlua_txn *htxn;
4489
4490 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4491 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4492
4493 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4494}
4495
4496/* This function replace full header, or just a value in
4497 * the request or in the response. It is a wrapper fir the
4498 * 4 following functions.
4499 */
4500__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4501 struct http_msg *msg, int action)
4502{
4503 size_t name_len;
4504 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4505 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4506 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4507 struct my_regex re;
4508
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004509 /* Check if a valid response is parsed */
4510 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4511 return 0;
4512
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004513 if (!regex_comp(reg, &re, 1, 1, NULL))
4514 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4515
4516 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4517 regex_free(&re);
4518 return 0;
4519}
4520
4521__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4522{
4523 struct hlua_txn *htxn;
4524
4525 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4526 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4527
4528 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4529}
4530
4531__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4532{
4533 struct hlua_txn *htxn;
4534
4535 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4536 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4537
4538 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4539}
4540
4541__LJMP static int hlua_http_req_rep_val(lua_State *L)
4542{
4543 struct hlua_txn *htxn;
4544
4545 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4546 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4547
4548 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4549}
4550
4551__LJMP static int hlua_http_res_rep_val(lua_State *L)
4552{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004553 struct hlua_txn *htxn;
4554
4555 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4556 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4557
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004558 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004559}
4560
4561/* This function deletes all the occurences of an header.
4562 * It is a wrapper for the 2 following functions.
4563 */
4564__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4565{
4566 size_t len;
4567 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4568 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004569 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004570
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004571 /* Check if a valid response is parsed */
4572 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4573 return 0;
4574
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004575 ctx.idx = 0;
4576 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4577 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4578 return 0;
4579}
4580
4581__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4582{
4583 struct hlua_txn *htxn;
4584
4585 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4586 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4587
Willy Tarreaueee5b512015-04-03 23:46:31 +02004588 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004589}
4590
4591__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4592{
4593 struct hlua_txn *htxn;
4594
4595 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4596 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4597
Willy Tarreaueee5b512015-04-03 23:46:31 +02004598 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004599}
4600
4601/* This function adds an header. It is a wrapper used by
4602 * the 2 following functions.
4603 */
4604__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4605{
4606 size_t name_len;
4607 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4608 size_t value_len;
4609 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4610 char *p;
4611
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004612 /* Check if a valid message is parsed */
4613 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4614 return 0;
4615
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004616 /* Check length. */
4617 trash.len = value_len + name_len + 2;
4618 if (trash.len > trash.size)
4619 return 0;
4620
4621 /* Creates the header string. */
4622 p = trash.str;
4623 memcpy(p, name, name_len);
4624 p += name_len;
4625 *p = ':';
4626 p++;
4627 *p = ' ';
4628 p++;
4629 memcpy(p, value, value_len);
4630
Willy Tarreaueee5b512015-04-03 23:46:31 +02004631 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004632 trash.str, trash.len) != 0);
4633
4634 return 0;
4635}
4636
4637__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4638{
4639 struct hlua_txn *htxn;
4640
4641 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4642 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4643
Willy Tarreaueee5b512015-04-03 23:46:31 +02004644 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004645}
4646
4647__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4648{
4649 struct hlua_txn *htxn;
4650
4651 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4652 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4653
Willy Tarreaueee5b512015-04-03 23:46:31 +02004654 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004655}
4656
4657static int hlua_http_req_set_hdr(lua_State *L)
4658{
4659 struct hlua_txn *htxn;
4660
4661 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4662 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4663
Willy Tarreaueee5b512015-04-03 23:46:31 +02004664 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4665 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004666}
4667
4668static int hlua_http_res_set_hdr(lua_State *L)
4669{
4670 struct hlua_txn *htxn;
4671
4672 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4673 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4674
Willy Tarreaueee5b512015-04-03 23:46:31 +02004675 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4676 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004677}
4678
4679/* This function set the method. */
4680static int hlua_http_req_set_meth(lua_State *L)
4681{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004682 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004683 size_t name_len;
4684 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004685
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004686 /* Check if a valid request is parsed */
4687 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4688 lua_pushboolean(L, 0);
4689 return 1;
4690 }
4691
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004692 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004693 return 1;
4694}
4695
4696/* This function set the method. */
4697static int hlua_http_req_set_path(lua_State *L)
4698{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004699 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004700 size_t name_len;
4701 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004702
4703 /* Check if a valid request is parsed */
4704 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4705 lua_pushboolean(L, 0);
4706 return 1;
4707 }
4708
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004709 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004710 return 1;
4711}
4712
4713/* This function set the query-string. */
4714static int hlua_http_req_set_query(lua_State *L)
4715{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004716 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004717 size_t name_len;
4718 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004719
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004720 /* Check if a valid request is parsed */
4721 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4722 lua_pushboolean(L, 0);
4723 return 1;
4724 }
4725
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004726 /* Check length. */
4727 if (name_len > trash.size - 1) {
4728 lua_pushboolean(L, 0);
4729 return 1;
4730 }
4731
4732 /* Add the mark question as prefix. */
4733 chunk_reset(&trash);
4734 trash.str[trash.len++] = '?';
4735 memcpy(trash.str + trash.len, name, name_len);
4736 trash.len += name_len;
4737
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004738 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004739 return 1;
4740}
4741
4742/* This function set the uri. */
4743static int hlua_http_req_set_uri(lua_State *L)
4744{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004745 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004746 size_t name_len;
4747 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004748
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004749 /* Check if a valid request is parsed */
4750 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4751 lua_pushboolean(L, 0);
4752 return 1;
4753 }
4754
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004755 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004756 return 1;
4757}
4758
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004759/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004760static int hlua_http_res_set_status(lua_State *L)
4761{
4762 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4763 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004764 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004765
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004766 /* Check if a valid response is parsed */
4767 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4768 return 0;
4769
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004770 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004771 return 0;
4772}
4773
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004774/*
4775 *
4776 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004777 * Class TXN
4778 *
4779 *
4780 */
4781
4782/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004783 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004784 */
4785__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4786{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004787 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004788}
4789
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004790__LJMP static int hlua_set_var(lua_State *L)
4791{
4792 struct hlua_txn *htxn;
4793 const char *name;
4794 size_t len;
4795 struct sample smp;
4796
4797 MAY_LJMP(check_args(L, 3, "set_var"));
4798
4799 /* It is useles to retrieve the stream, but this function
4800 * runs only in a stream context.
4801 */
4802 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4803 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4804
4805 /* Converts the third argument in a sample. */
4806 hlua_lua2smp(L, 3, &smp);
4807
4808 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01004809 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004810 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004811 return 0;
4812}
4813
Christopher Faulet85d79c92016-11-09 16:54:56 +01004814__LJMP static int hlua_unset_var(lua_State *L)
4815{
4816 struct hlua_txn *htxn;
4817 const char *name;
4818 size_t len;
4819 struct sample smp;
4820
4821 MAY_LJMP(check_args(L, 2, "unset_var"));
4822
4823 /* It is useles to retrieve the stream, but this function
4824 * runs only in a stream context.
4825 */
4826 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4827 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4828
4829 /* Unset the variable. */
4830 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
4831 vars_unset_by_name(name, len, &smp);
4832 return 0;
4833}
4834
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004835__LJMP static int hlua_get_var(lua_State *L)
4836{
4837 struct hlua_txn *htxn;
4838 const char *name;
4839 size_t len;
4840 struct sample smp;
4841
4842 MAY_LJMP(check_args(L, 2, "get_var"));
4843
4844 /* It is useles to retrieve the stream, but this function
4845 * runs only in a stream context.
4846 */
4847 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4848 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4849
Willy Tarreau7560dd42016-03-10 16:28:58 +01004850 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004851 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004852 lua_pushnil(L);
4853 return 1;
4854 }
4855
4856 return hlua_smp2lua(L, &smp);
4857}
4858
Willy Tarreau59551662015-03-10 14:23:13 +01004859__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004860{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004861 struct hlua *hlua;
4862
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004863 MAY_LJMP(check_args(L, 2, "set_priv"));
4864
Willy Tarreau87b09662015-04-03 00:22:06 +02004865 /* It is useles to retrieve the stream, but this function
4866 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004867 */
4868 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004869 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004870
4871 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004872 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004873
4874 /* Get and store new value. */
4875 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4876 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4877
4878 return 0;
4879}
4880
Willy Tarreau59551662015-03-10 14:23:13 +01004881__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004882{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004883 struct hlua *hlua;
4884
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004885 MAY_LJMP(check_args(L, 1, "get_priv"));
4886
Willy Tarreau87b09662015-04-03 00:22:06 +02004887 /* It is useles to retrieve the stream, but this function
4888 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004889 */
4890 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004891 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004892
4893 /* Push configuration index in the stack. */
4894 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4895
4896 return 1;
4897}
4898
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004899/* Create stack entry containing a class TXN. This function
4900 * return 0 if the stack does not contains free slots,
4901 * otherwise it returns 1.
4902 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004903static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004904{
Willy Tarreaude491382015-04-06 11:04:28 +02004905 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004906
4907 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004908 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004909 return 0;
4910
4911 /* NOTE: The allocation never fails. The failure
4912 * throw an error, and the function never returns.
4913 * if the throw is not avalaible, the process is aborted.
4914 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004915 /* Create the object: obj[0] = userdata. */
4916 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004917 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004918 lua_rawseti(L, -2, 0);
4919
Willy Tarreaude491382015-04-06 11:04:28 +02004920 htxn->s = s;
4921 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004922 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004923 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004924
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004925 /* Create the "f" field that contains a list of fetches. */
4926 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004927 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004928 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004929 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004930
4931 /* Create the "sf" field that contains a list of stringsafe fetches. */
4932 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004933 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004934 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004935 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004936
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004937 /* Create the "c" field that contains a list of converters. */
4938 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004939 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004940 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004941 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004942
4943 /* Create the "sc" field that contains a list of stringsafe converters. */
4944 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004945 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004946 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004947 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004948
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004949 /* Create the "req" field that contains the request channel object. */
4950 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004951 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004952 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004953 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004954
4955 /* Create the "res" field that contains the response channel object. */
4956 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004957 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004958 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004959 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004960
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004961 /* Creates the HTTP object is the current proxy allows http. */
4962 lua_pushstring(L, "http");
4963 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02004964 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004965 return 0;
4966 }
4967 else
4968 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004969 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004970
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004971 /* Pop a class sesison metatable and affect it to the userdata. */
4972 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
4973 lua_setmetatable(L, -2);
4974
4975 return 1;
4976}
4977
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004978__LJMP static int hlua_txn_deflog(lua_State *L)
4979{
4980 const char *msg;
4981 struct hlua_txn *htxn;
4982
4983 MAY_LJMP(check_args(L, 2, "deflog"));
4984 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4985 msg = MAY_LJMP(luaL_checkstring(L, 2));
4986
4987 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
4988 return 0;
4989}
4990
4991__LJMP static int hlua_txn_log(lua_State *L)
4992{
4993 int level;
4994 const char *msg;
4995 struct hlua_txn *htxn;
4996
4997 MAY_LJMP(check_args(L, 3, "log"));
4998 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4999 level = MAY_LJMP(luaL_checkinteger(L, 2));
5000 msg = MAY_LJMP(luaL_checkstring(L, 3));
5001
5002 if (level < 0 || level >= NB_LOG_LEVELS)
5003 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5004
5005 hlua_sendlog(htxn->s->be, level, msg);
5006 return 0;
5007}
5008
5009__LJMP static int hlua_txn_log_debug(lua_State *L)
5010{
5011 const char *msg;
5012 struct hlua_txn *htxn;
5013
5014 MAY_LJMP(check_args(L, 2, "Debug"));
5015 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5016 msg = MAY_LJMP(luaL_checkstring(L, 2));
5017 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5018 return 0;
5019}
5020
5021__LJMP static int hlua_txn_log_info(lua_State *L)
5022{
5023 const char *msg;
5024 struct hlua_txn *htxn;
5025
5026 MAY_LJMP(check_args(L, 2, "Info"));
5027 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5028 msg = MAY_LJMP(luaL_checkstring(L, 2));
5029 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5030 return 0;
5031}
5032
5033__LJMP static int hlua_txn_log_warning(lua_State *L)
5034{
5035 const char *msg;
5036 struct hlua_txn *htxn;
5037
5038 MAY_LJMP(check_args(L, 2, "Warning"));
5039 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5040 msg = MAY_LJMP(luaL_checkstring(L, 2));
5041 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5042 return 0;
5043}
5044
5045__LJMP static int hlua_txn_log_alert(lua_State *L)
5046{
5047 const char *msg;
5048 struct hlua_txn *htxn;
5049
5050 MAY_LJMP(check_args(L, 2, "Alert"));
5051 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5052 msg = MAY_LJMP(luaL_checkstring(L, 2));
5053 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5054 return 0;
5055}
5056
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005057__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5058{
5059 struct hlua_txn *htxn;
5060 int ll;
5061
5062 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5063 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5064 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5065
5066 if (ll < 0 || ll > 7)
5067 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5068
5069 htxn->s->logs.level = ll;
5070 return 0;
5071}
5072
5073__LJMP static int hlua_txn_set_tos(lua_State *L)
5074{
5075 struct hlua_txn *htxn;
5076 struct connection *cli_conn;
5077 int tos;
5078
5079 MAY_LJMP(check_args(L, 2, "set_tos"));
5080 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5081 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5082
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005083 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005084 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005085
5086 return 0;
5087}
5088
5089__LJMP static int hlua_txn_set_mark(lua_State *L)
5090{
5091#ifdef SO_MARK
5092 struct hlua_txn *htxn;
5093 struct connection *cli_conn;
5094 int mark;
5095
5096 MAY_LJMP(check_args(L, 2, "set_mark"));
5097 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5098 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5099
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005100 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005101 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005102#endif
5103 return 0;
5104}
5105
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005106/* This function is an Lua binding that send pending data
5107 * to the client, and close the stream interface.
5108 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005109__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005110{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005111 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005112 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005113 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005114
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005115 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005116 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005117 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005118
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005119 /* If the flags NOTERM is set, we cannot terminate the http
5120 * session, so we just end the execution of the current
5121 * lua code.
5122 */
5123 if (htxn->flags & HLUA_TXN_NOTERM) {
5124 WILL_LJMP(hlua_done(L));
5125 return 0;
5126 }
5127
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005128 ic = &htxn->s->req;
5129 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005130
Willy Tarreau630ef452015-08-28 10:06:15 +02005131 if (htxn->s->txn) {
5132 /* HTTP mode, let's stay in sync with the stream */
5133 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
5134 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5135 htxn->s->txn->req.sov = 0;
5136 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5137 oc->analysers = AN_RES_HTTP_XFER_BODY;
5138 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5139 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5140
Willy Tarreau630ef452015-08-28 10:06:15 +02005141 /* Note that if we want to support keep-alive, we need
5142 * to bypass the close/shutr_now calls below, but that
5143 * may only be done if the HTTP request was already
5144 * processed and the connection header is known (ie
5145 * not during TCP rules).
5146 */
5147 }
5148
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005149 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005150 channel_abort(ic);
5151 channel_auto_close(ic);
5152 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005153
5154 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005155 channel_auto_read(oc);
5156 channel_auto_close(oc);
5157 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005158
Willy Tarreau0458b082015-08-28 09:40:04 +02005159 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005160
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005161 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005162 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005163 return 0;
5164}
5165
5166__LJMP static int hlua_log(lua_State *L)
5167{
5168 int level;
5169 const char *msg;
5170
5171 MAY_LJMP(check_args(L, 2, "log"));
5172 level = MAY_LJMP(luaL_checkinteger(L, 1));
5173 msg = MAY_LJMP(luaL_checkstring(L, 2));
5174
5175 if (level < 0 || level >= NB_LOG_LEVELS)
5176 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5177
5178 hlua_sendlog(NULL, level, msg);
5179 return 0;
5180}
5181
5182__LJMP static int hlua_log_debug(lua_State *L)
5183{
5184 const char *msg;
5185
5186 MAY_LJMP(check_args(L, 1, "debug"));
5187 msg = MAY_LJMP(luaL_checkstring(L, 1));
5188 hlua_sendlog(NULL, LOG_DEBUG, msg);
5189 return 0;
5190}
5191
5192__LJMP static int hlua_log_info(lua_State *L)
5193{
5194 const char *msg;
5195
5196 MAY_LJMP(check_args(L, 1, "info"));
5197 msg = MAY_LJMP(luaL_checkstring(L, 1));
5198 hlua_sendlog(NULL, LOG_INFO, msg);
5199 return 0;
5200}
5201
5202__LJMP static int hlua_log_warning(lua_State *L)
5203{
5204 const char *msg;
5205
5206 MAY_LJMP(check_args(L, 1, "warning"));
5207 msg = MAY_LJMP(luaL_checkstring(L, 1));
5208 hlua_sendlog(NULL, LOG_WARNING, msg);
5209 return 0;
5210}
5211
5212__LJMP static int hlua_log_alert(lua_State *L)
5213{
5214 const char *msg;
5215
5216 MAY_LJMP(check_args(L, 1, "alert"));
5217 msg = MAY_LJMP(luaL_checkstring(L, 1));
5218 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005219 return 0;
5220}
5221
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005222__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005223{
5224 int wakeup_ms = lua_tointeger(L, -1);
5225 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005226 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005227 return 0;
5228}
5229
5230__LJMP static int hlua_sleep(lua_State *L)
5231{
5232 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005233 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005234
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005235 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005236
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005237 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005238 wakeup_ms = tick_add(now_ms, delay);
5239 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005240
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005241 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5242 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005243}
5244
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005245__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005246{
5247 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005248 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005249
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005250 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005251
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005252 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005253 wakeup_ms = tick_add(now_ms, delay);
5254 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005255
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005256 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5257 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005258}
5259
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005260/* This functionis an LUA binding. it permits to give back
5261 * the hand at the HAProxy scheduler. It is used when the
5262 * LUA processing consumes a lot of time.
5263 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005264__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005265{
5266 return 0;
5267}
5268
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005269__LJMP static int hlua_yield(lua_State *L)
5270{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005271 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5272 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005273}
5274
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005275/* This function change the nice of the currently executed
5276 * task. It is used set low or high priority at the current
5277 * task.
5278 */
Willy Tarreau59551662015-03-10 14:23:13 +01005279__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005280{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005281 struct hlua *hlua;
5282 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005283
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005284 MAY_LJMP(check_args(L, 1, "set_nice"));
5285 hlua = hlua_gethlua(L);
5286 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005287
5288 /* If he task is not set, I'm in a start mode. */
5289 if (!hlua || !hlua->task)
5290 return 0;
5291
5292 if (nice < -1024)
5293 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005294 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005295 nice = 1024;
5296
5297 hlua->task->nice = nice;
5298 return 0;
5299}
5300
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005301/* This function is used as a calback of a task. It is called by the
5302 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5303 * return an E_AGAIN signal, the emmiter of this signal must set a
5304 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005305 *
5306 * Task wrapper are longjmp safe because the only one Lua code
5307 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005308 */
5309static struct task *hlua_process_task(struct task *task)
5310{
5311 struct hlua *hlua = task->context;
5312 enum hlua_exec status;
5313
5314 /* We need to remove the task from the wait queue before executing
5315 * the Lua code because we don't know if it needs to wait for
5316 * another timer or not in the case of E_AGAIN.
5317 */
5318 task_delete(task);
5319
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005320 /* If it is the first call to the task, we must initialize the
5321 * execution timeouts.
5322 */
5323 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005324 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005325
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005326 /* Execute the Lua code. */
5327 status = hlua_ctx_resume(hlua, 1);
5328
5329 switch (status) {
5330 /* finished or yield */
5331 case HLUA_E_OK:
5332 hlua_ctx_destroy(hlua);
5333 task_delete(task);
5334 task_free(task);
5335 break;
5336
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005337 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5338 if (hlua->wake_time != TICK_ETERNITY)
5339 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005340 break;
5341
5342 /* finished with error. */
5343 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005344 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005345 hlua_ctx_destroy(hlua);
5346 task_delete(task);
5347 task_free(task);
5348 break;
5349
5350 case HLUA_E_ERR:
5351 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005352 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005353 hlua_ctx_destroy(hlua);
5354 task_delete(task);
5355 task_free(task);
5356 break;
5357 }
5358 return NULL;
5359}
5360
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005361/* This function is an LUA binding that register LUA function to be
5362 * executed after the HAProxy configuration parsing and before the
5363 * HAProxy scheduler starts. This function expect only one LUA
5364 * argument that is a function. This function returns nothing, but
5365 * throws if an error is encountered.
5366 */
5367__LJMP static int hlua_register_init(lua_State *L)
5368{
5369 struct hlua_init_function *init;
5370 int ref;
5371
5372 MAY_LJMP(check_args(L, 1, "register_init"));
5373
5374 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5375
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005376 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005377 if (!init)
5378 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5379
5380 init->function_ref = ref;
5381 LIST_ADDQ(&hlua_init_functions, &init->l);
5382 return 0;
5383}
5384
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005385/* This functio is an LUA binding. It permits to register a task
5386 * executed in parallel of the main HAroxy activity. The task is
5387 * created and it is set in the HAProxy scheduler. It can be called
5388 * from the "init" section, "post init" or during the runtime.
5389 *
5390 * Lua prototype:
5391 *
5392 * <none> core.register_task(<function>)
5393 */
5394static int hlua_register_task(lua_State *L)
5395{
5396 struct hlua *hlua;
5397 struct task *task;
5398 int ref;
5399
5400 MAY_LJMP(check_args(L, 1, "register_task"));
5401
5402 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5403
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005404 hlua = pool_alloc2(pool2_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005405 if (!hlua)
5406 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5407
5408 task = task_new();
5409 task->context = hlua;
5410 task->process = hlua_process_task;
5411
5412 if (!hlua_ctx_init(hlua, task))
5413 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5414
5415 /* Restore the function in the stack. */
5416 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5417 hlua->nargs = 0;
5418
5419 /* Schedule task. */
5420 task_schedule(task, now_ms);
5421
5422 return 0;
5423}
5424
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005425/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5426 * doesn't allow "yield" functions because the HAProxy engine cannot
5427 * resume converters.
5428 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005429static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005430{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005431 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005432 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005433 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005434
Willy Tarreaube508f12016-03-10 11:47:01 +01005435 if (!stream)
5436 return 0;
5437
Willy Tarreau87b09662015-04-03 00:22:06 +02005438 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005439 * Lua context can be not initialized. This behavior
5440 * permits to save performances because a systematic
5441 * Lua initialization cause 5% performances loss.
5442 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005443 if (!stream->hlua) {
5444 stream->hlua = pool_alloc2(pool2_hlua);
5445 if (!stream->hlua) {
5446 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5447 return 0;
5448 }
5449 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5450 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5451 return 0;
5452 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005453 }
5454
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005455 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005456 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005457
5458 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005459 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5460 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5461 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005462 else
5463 error = "critical error";
5464 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005465 return 0;
5466 }
5467
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005468 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005469 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005470 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005471 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005472 return 0;
5473 }
5474
5475 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005476 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005477
5478 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005479 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005480 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005481 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005482 return 0;
5483 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005484 hlua_smp2lua(stream->hlua->T, smp);
5485 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005486
5487 /* push keywords in the stack. */
5488 if (arg_p) {
5489 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005490 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005491 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005492 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005493 return 0;
5494 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005495 hlua_arg2lua(stream->hlua->T, arg_p);
5496 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005497 }
5498 }
5499
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005500 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005501 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005502
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005503 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005504 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005505 }
5506
5507 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005508 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005509 /* finished. */
5510 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005511 /* If the stack is empty, the function fails. */
5512 if (lua_gettop(stream->hlua->T) <= 0)
5513 return 0;
5514
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005515 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005516 hlua_lua2smp(stream->hlua->T, -1, smp);
5517 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005518 return 1;
5519
5520 /* yield. */
5521 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005522 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005523 return 0;
5524
5525 /* finished with error. */
5526 case HLUA_E_ERRMSG:
5527 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005528 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005529 fcn->name, lua_tostring(stream->hlua->T, -1));
5530 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005531 return 0;
5532
5533 case HLUA_E_ERR:
5534 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005535 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005536
5537 default:
5538 return 0;
5539 }
5540}
5541
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005542/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5543 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005544 * resume sample-fetches. This function will be called by the sample
5545 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005546 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005547static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5548 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005549{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005550 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005551 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005552 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005553 const struct chunk msg = { .len = 0 };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005554
Willy Tarreaube508f12016-03-10 11:47:01 +01005555 if (!stream)
5556 return 0;
5557
Willy Tarreau87b09662015-04-03 00:22:06 +02005558 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005559 * Lua context can be not initialized. This behavior
5560 * permits to save performances because a systematic
5561 * Lua initialization cause 5% performances loss.
5562 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005563 if (!stream->hlua) {
5564 stream->hlua = pool_alloc2(pool2_hlua);
5565 if (!stream->hlua) {
5566 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5567 return 0;
5568 }
5569 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5570 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5571 return 0;
5572 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005573 }
5574
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005575 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005576
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005577 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005578 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005579
5580 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005581 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5582 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5583 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005584 else
5585 error = "critical error";
5586 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005587 return 0;
5588 }
5589
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005590 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005591 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005592 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005593 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005594 return 0;
5595 }
5596
5597 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005598 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005599
5600 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005601 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005602 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005603 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005604 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005605 return 0;
5606 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005607 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005608
5609 /* push keywords in the stack. */
5610 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5611 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005612 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005613 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005614 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005615 return 0;
5616 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005617 hlua_arg2lua(stream->hlua->T, arg_p);
5618 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005619 }
5620
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005621 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005622 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005623
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005624 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005625 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005626 }
5627
5628 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005629 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005630 /* finished. */
5631 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005632 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005633 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005634 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005635 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005636 /* If the stack is empty, the function fails. */
5637 if (lua_gettop(stream->hlua->T) <= 0)
5638 return 0;
5639
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005640 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005641 hlua_lua2smp(stream->hlua->T, -1, smp);
5642 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005643
5644 /* Set the end of execution flag. */
5645 smp->flags &= ~SMP_F_MAY_CHANGE;
5646 return 1;
5647
5648 /* yield. */
5649 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005650 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005651 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005652 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005653 return 0;
5654
5655 /* finished with error. */
5656 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005657 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005658 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005659 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005660 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005661 fcn->name, lua_tostring(stream->hlua->T, -1));
5662 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005663 return 0;
5664
5665 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005666 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005667 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005668 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005669 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005670
5671 default:
5672 return 0;
5673 }
5674}
5675
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005676/* This function is an LUA binding used for registering
5677 * "sample-conv" functions. It expects a converter name used
5678 * in the haproxy configuration file, and an LUA function.
5679 */
5680__LJMP static int hlua_register_converters(lua_State *L)
5681{
5682 struct sample_conv_kw_list *sck;
5683 const char *name;
5684 int ref;
5685 int len;
5686 struct hlua_function *fcn;
5687
5688 MAY_LJMP(check_args(L, 2, "register_converters"));
5689
5690 /* First argument : converter name. */
5691 name = MAY_LJMP(luaL_checkstring(L, 1));
5692
5693 /* Second argument : lua function. */
5694 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5695
5696 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005697 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005698 if (!sck)
5699 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005700 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005701 if (!fcn)
5702 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5703
5704 /* Fill fcn. */
5705 fcn->name = strdup(name);
5706 if (!fcn->name)
5707 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5708 fcn->function_ref = ref;
5709
5710 /* List head */
5711 sck->list.n = sck->list.p = NULL;
5712
5713 /* converter keyword. */
5714 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005715 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005716 if (!sck->kw[0].kw)
5717 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5718
5719 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5720 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005721 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 +01005722 sck->kw[0].val_args = NULL;
5723 sck->kw[0].in_type = SMP_T_STR;
5724 sck->kw[0].out_type = SMP_T_STR;
5725 sck->kw[0].private = fcn;
5726
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005727 /* Register this new converter */
5728 sample_register_convs(sck);
5729
5730 return 0;
5731}
5732
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005733/* This fucntion is an LUA binding used for registering
5734 * "sample-fetch" functions. It expects a converter name used
5735 * in the haproxy configuration file, and an LUA function.
5736 */
5737__LJMP static int hlua_register_fetches(lua_State *L)
5738{
5739 const char *name;
5740 int ref;
5741 int len;
5742 struct sample_fetch_kw_list *sfk;
5743 struct hlua_function *fcn;
5744
5745 MAY_LJMP(check_args(L, 2, "register_fetches"));
5746
5747 /* First argument : sample-fetch name. */
5748 name = MAY_LJMP(luaL_checkstring(L, 1));
5749
5750 /* Second argument : lua function. */
5751 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5752
5753 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005754 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005755 if (!sfk)
5756 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005757 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005758 if (!fcn)
5759 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5760
5761 /* Fill fcn. */
5762 fcn->name = strdup(name);
5763 if (!fcn->name)
5764 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5765 fcn->function_ref = ref;
5766
5767 /* List head */
5768 sfk->list.n = sfk->list.p = NULL;
5769
5770 /* sample-fetch keyword. */
5771 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005772 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005773 if (!sfk->kw[0].kw)
5774 return luaL_error(L, "lua out of memory error.");
5775
5776 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5777 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005778 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 +01005779 sfk->kw[0].val_args = NULL;
5780 sfk->kw[0].out_type = SMP_T_STR;
5781 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5782 sfk->kw[0].val = 0;
5783 sfk->kw[0].private = fcn;
5784
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005785 /* Register this new fetch. */
5786 sample_register_fetches(sfk);
5787
5788 return 0;
5789}
5790
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005791/* This function is a wrapper to execute each LUA function declared
5792 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005793 * return ACT_RET_CONT if the processing is finished (with or without
5794 * error) and return ACT_RET_YIELD if the function must be called again
5795 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005796 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005797static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005798 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005799{
5800 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005801 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005802 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005803 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005804 const struct chunk msg = { .len = 0 };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005805
5806 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01005807 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
5808 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
5809 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
5810 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005811 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005812 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005813 return ACT_RET_CONT;
5814 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005815
Willy Tarreau87b09662015-04-03 00:22:06 +02005816 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005817 * Lua context can be not initialized. This behavior
5818 * permits to save performances because a systematic
5819 * Lua initialization cause 5% performances loss.
5820 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005821 if (!s->hlua) {
5822 s->hlua = pool_alloc2(pool2_hlua);
5823 if (!s->hlua) {
5824 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
5825 rule->arg.hlua_rule->fcn.name);
5826 return ACT_RET_CONT;
5827 }
5828 if (!hlua_ctx_init(s->hlua, s->task)) {
5829 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
5830 rule->arg.hlua_rule->fcn.name);
5831 return ACT_RET_CONT;
5832 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005833 }
5834
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005835 consistency_set(s, dir, &s->hlua->cons);
5836
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005837 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005838 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005839
5840 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005841 if (!SET_SAFE_LJMP(s->hlua->T)) {
5842 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
5843 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005844 else
5845 error = "critical error";
5846 SEND_ERR(px, "Lua function '%s': %s.\n",
5847 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005848 return ACT_RET_CONT;
5849 }
5850
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005851 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005852 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005853 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005854 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005855 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005856 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005857 }
5858
5859 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005860 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005861
Willy Tarreau87b09662015-04-03 00:22:06 +02005862 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005863 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005864 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005865 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005866 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005867 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005868 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005869 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005870
5871 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005872 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005873 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005874 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005875 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005876 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005877 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005878 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005879 lua_pushstring(s->hlua->T, *arg);
5880 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005881 }
5882
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005883 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005884 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005885
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005886 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005887 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005888 }
5889
5890 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005891 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005892 /* finished. */
5893 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005894 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005895 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005896 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005897 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005898 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005899 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005900 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005901
5902 /* yield. */
5903 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005904 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005905 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005906 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005907 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005908 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005909 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005910 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005911 /* Some actions can be wake up when a "write" event
5912 * is detected on a response channel. This is useful
5913 * only for actions targetted on the requests.
5914 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005915 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005916 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005917 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005918 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005919 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005920 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005921 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005922 /* We can quit the fcuntion without consistency check
5923 * because HAProxy is not able to manipulate data, it
5924 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005925 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005926
5927 /* finished with error. */
5928 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005929 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005930 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005931 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005932 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005933 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005934 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005935 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
5936 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005937 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005938
5939 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005940 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005941 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005942 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005943 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005944 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005945 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005946 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005947
5948 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005949 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005950 }
5951}
5952
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005953struct task *hlua_applet_wakeup(struct task *t)
5954{
5955 struct appctx *ctx = t->context;
5956 struct stream_interface *si = ctx->owner;
5957
5958 /* If the applet is wake up without any expected work, the sheduler
5959 * remove it from the run queue. This flag indicate that the applet
5960 * is waiting for write. If the buffer is full, the main processing
5961 * will send some data and after call the applet, otherwise it call
5962 * the applet ASAP.
5963 */
5964 si_applet_cant_put(si);
5965 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02005966 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02005967 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005968}
5969
5970static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5971{
5972 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01005973 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005974 struct task *task;
5975 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005976 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005977
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01005978 hlua = pool_alloc2(pool2_hlua);
5979 if (!hlua) {
5980 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5981 ctx->rule->arg.hlua_rule->fcn.name);
5982 return 0;
5983 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005984 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01005985 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005986 ctx->ctx.hlua_apptcp.flags = 0;
5987
5988 /* Create task used by signal to wakeup applets. */
5989 task = task_new();
5990 if (!task) {
5991 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5992 ctx->rule->arg.hlua_rule->fcn.name);
5993 return 0;
5994 }
5995 task->nice = 0;
5996 task->context = ctx;
5997 task->process = hlua_applet_wakeup;
5998 ctx->ctx.hlua_apptcp.task = task;
5999
6000 /* In the execution wrappers linked with a stream, the
6001 * Lua context can be not initialized. This behavior
6002 * permits to save performances because a systematic
6003 * Lua initialization cause 5% performances loss.
6004 */
6005 if (!hlua_ctx_init(hlua, task)) {
6006 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6007 ctx->rule->arg.hlua_rule->fcn.name);
6008 return 0;
6009 }
6010
6011 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006012 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006013
6014 /* The following Lua calls can fail. */
6015 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006016 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6017 error = lua_tostring(hlua->T, -1);
6018 else
6019 error = "critical error";
6020 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6021 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006022 RESET_SAFE_LJMP(hlua->T);
6023 return 0;
6024 }
6025
6026 /* Check stack available size. */
6027 if (!lua_checkstack(hlua->T, 1)) {
6028 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6029 ctx->rule->arg.hlua_rule->fcn.name);
6030 RESET_SAFE_LJMP(hlua->T);
6031 return 0;
6032 }
6033
6034 /* Restore the function in the stack. */
6035 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6036
6037 /* Create and and push object stream in the stack. */
6038 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6039 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6040 ctx->rule->arg.hlua_rule->fcn.name);
6041 RESET_SAFE_LJMP(hlua->T);
6042 return 0;
6043 }
6044 hlua->nargs = 1;
6045
6046 /* push keywords in the stack. */
6047 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6048 if (!lua_checkstack(hlua->T, 1)) {
6049 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6050 ctx->rule->arg.hlua_rule->fcn.name);
6051 RESET_SAFE_LJMP(hlua->T);
6052 return 0;
6053 }
6054 lua_pushstring(hlua->T, *arg);
6055 hlua->nargs++;
6056 }
6057
6058 RESET_SAFE_LJMP(hlua->T);
6059
6060 /* Wakeup the applet ASAP. */
6061 si_applet_cant_get(si);
6062 si_applet_cant_put(si);
6063
6064 return 1;
6065}
6066
6067static void hlua_applet_tcp_fct(struct appctx *ctx)
6068{
6069 struct stream_interface *si = ctx->owner;
6070 struct stream *strm = si_strm(si);
6071 struct channel *res = si_ic(si);
6072 struct act_rule *rule = ctx->rule;
6073 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006074 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006075
6076 /* The applet execution is already done. */
6077 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
6078 return;
6079
6080 /* If the stream is disconnect or closed, ldo nothing. */
6081 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6082 return;
6083
6084 /* Execute the function. */
6085 switch (hlua_ctx_resume(hlua, 1)) {
6086 /* finished. */
6087 case HLUA_E_OK:
6088 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6089
6090 /* log time */
6091 strm->logs.tv_request = now;
6092
6093 /* eat the whole request */
6094 bo_skip(si_oc(si), si_ob(si)->o);
6095 res->flags |= CF_READ_NULL;
6096 si_shutr(si);
6097 return;
6098
6099 /* yield. */
6100 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006101 if (hlua->wake_time != TICK_ETERNITY)
6102 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006103 return;
6104
6105 /* finished with error. */
6106 case HLUA_E_ERRMSG:
6107 /* Display log. */
6108 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6109 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6110 lua_pop(hlua->T, 1);
6111 goto error;
6112
6113 case HLUA_E_ERR:
6114 /* Display log. */
6115 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6116 rule->arg.hlua_rule->fcn.name);
6117 goto error;
6118
6119 default:
6120 goto error;
6121 }
6122
6123error:
6124
6125 /* For all other cases, just close the stream. */
6126 si_shutw(si);
6127 si_shutr(si);
6128 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6129}
6130
6131static void hlua_applet_tcp_release(struct appctx *ctx)
6132{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006133 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006134 task_free(ctx->ctx.hlua_apptcp.task);
6135 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006136 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006137 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006138}
6139
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006140/* The function returns 1 if the initialisation is complete, 0 if
6141 * an errors occurs and -1 if more data are required for initializing
6142 * the applet.
6143 */
6144static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6145{
6146 struct stream_interface *si = ctx->owner;
6147 struct channel *req = si_oc(si);
6148 struct http_msg *msg;
6149 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006150 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006151 char **arg;
6152 struct hdr_ctx hdr;
6153 struct task *task;
6154 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006155 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006156
6157 /* Wait for a full HTTP request. */
6158 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6159 if (smp.flags & SMP_F_MAY_CHANGE)
6160 return -1;
6161 return 0;
6162 }
6163 txn = strm->txn;
6164 msg = &txn->req;
6165
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006166 /* We want two things in HTTP mode :
6167 * - enforce server-close mode if we were in keep-alive, so that the
6168 * applet is released after each response ;
6169 * - enable request body transfer to the applet in order to resync
6170 * with the response body.
6171 */
6172 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6173 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006174
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006175 hlua = pool_alloc2(pool2_hlua);
6176 if (!hlua) {
6177 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6178 ctx->rule->arg.hlua_rule->fcn.name);
6179 return 0;
6180 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006181 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006182 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006183 ctx->ctx.hlua_apphttp.left_bytes = -1;
6184 ctx->ctx.hlua_apphttp.flags = 0;
6185
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006186 if (txn->req.flags & HTTP_MSGF_VER_11)
6187 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6188
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006189 /* Create task used by signal to wakeup applets. */
6190 task = task_new();
6191 if (!task) {
6192 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6193 ctx->rule->arg.hlua_rule->fcn.name);
6194 return 0;
6195 }
6196 task->nice = 0;
6197 task->context = ctx;
6198 task->process = hlua_applet_wakeup;
6199 ctx->ctx.hlua_apphttp.task = task;
6200
6201 /* In the execution wrappers linked with a stream, the
6202 * Lua context can be not initialized. This behavior
6203 * permits to save performances because a systematic
6204 * Lua initialization cause 5% performances loss.
6205 */
6206 if (!hlua_ctx_init(hlua, task)) {
6207 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6208 ctx->rule->arg.hlua_rule->fcn.name);
6209 return 0;
6210 }
6211
6212 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006213 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006214
6215 /* The following Lua calls can fail. */
6216 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006217 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6218 error = lua_tostring(hlua->T, -1);
6219 else
6220 error = "critical error";
6221 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6222 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006223 return 0;
6224 }
6225
6226 /* Check stack available size. */
6227 if (!lua_checkstack(hlua->T, 1)) {
6228 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6229 ctx->rule->arg.hlua_rule->fcn.name);
6230 RESET_SAFE_LJMP(hlua->T);
6231 return 0;
6232 }
6233
6234 /* Restore the function in the stack. */
6235 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6236
6237 /* Create and and push object stream in the stack. */
6238 if (!hlua_applet_http_new(hlua->T, ctx)) {
6239 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6240 ctx->rule->arg.hlua_rule->fcn.name);
6241 RESET_SAFE_LJMP(hlua->T);
6242 return 0;
6243 }
6244 hlua->nargs = 1;
6245
6246 /* Look for a 100-continue expected. */
6247 if (msg->flags & HTTP_MSGF_VER_11) {
6248 hdr.idx = 0;
6249 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
6250 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6251 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6252 }
6253
6254 /* push keywords in the stack. */
6255 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6256 if (!lua_checkstack(hlua->T, 1)) {
6257 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6258 ctx->rule->arg.hlua_rule->fcn.name);
6259 RESET_SAFE_LJMP(hlua->T);
6260 return 0;
6261 }
6262 lua_pushstring(hlua->T, *arg);
6263 hlua->nargs++;
6264 }
6265
6266 RESET_SAFE_LJMP(hlua->T);
6267
6268 /* Wakeup the applet when data is ready for read. */
6269 si_applet_cant_get(si);
6270
6271 return 1;
6272}
6273
6274static void hlua_applet_http_fct(struct appctx *ctx)
6275{
6276 struct stream_interface *si = ctx->owner;
6277 struct stream *strm = si_strm(si);
6278 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006279 struct act_rule *rule = ctx->rule;
6280 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006281 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006282 char *blk1;
6283 int len1;
6284 char *blk2;
6285 int len2;
6286 int ret;
6287
6288 /* If the stream is disconnect or closed, ldo nothing. */
6289 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6290 return;
6291
6292 /* Set the currently running flag. */
6293 if (!HLUA_IS_RUNNING(hlua) &&
6294 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6295
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006296 /* Wait for full HTTP analysys. */
6297 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6298 si_applet_cant_get(si);
6299 return;
6300 }
6301
6302 /* Store the max amount of bytes that we can read. */
6303 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6304
6305 /* We need to flush the request header. This left the body
6306 * for the Lua.
6307 */
6308
6309 /* Read the maximum amount of data avalaible. */
6310 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
6311 if (ret == -1)
6312 return;
6313
6314 /* No data available, ask for more data. */
6315 if (ret == 1)
6316 len2 = 0;
6317 if (ret == 0)
6318 len1 = 0;
6319 if (len1 + len2 < strm->txn->req.eoh + 2) {
6320 si_applet_cant_get(si);
6321 return;
6322 }
6323
6324 /* skip the requests bytes. */
6325 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
6326 }
6327
6328 /* Executes The applet if it is not done. */
6329 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6330
6331 /* Execute the function. */
6332 switch (hlua_ctx_resume(hlua, 1)) {
6333 /* finished. */
6334 case HLUA_E_OK:
6335 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6336 break;
6337
6338 /* yield. */
6339 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006340 if (hlua->wake_time != TICK_ETERNITY)
6341 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006342 return;
6343
6344 /* finished with error. */
6345 case HLUA_E_ERRMSG:
6346 /* Display log. */
6347 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6348 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6349 lua_pop(hlua->T, 1);
6350 goto error;
6351
6352 case HLUA_E_ERR:
6353 /* Display log. */
6354 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6355 rule->arg.hlua_rule->fcn.name);
6356 goto error;
6357
6358 default:
6359 goto error;
6360 }
6361 }
6362
6363 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6364
6365 /* We must send the final chunk. */
6366 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6367 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6368
6369 /* sent last chunk at once. */
6370 ret = bi_putblk(res, "0\r\n\r\n", 5);
6371
6372 /* critical error. */
6373 if (ret == -2 || ret == -3) {
6374 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6375 rule->arg.hlua_rule->fcn.name);
6376 goto error;
6377 }
6378
6379 /* no enough space error. */
6380 if (ret == -1) {
6381 si_applet_cant_put(si);
6382 return;
6383 }
6384
6385 /* set the last chunk sent. */
6386 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6387 }
6388
6389 /* close the connection. */
6390
6391 /* status / log */
6392 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6393 strm->logs.tv_request = now;
6394
6395 /* eat the whole request */
6396 bo_skip(si_oc(si), si_ob(si)->o);
6397 res->flags |= CF_READ_NULL;
6398 si_shutr(si);
6399
6400 return;
6401 }
6402
6403error:
6404
6405 /* If we are in HTTP mode, and we are not send any
6406 * data, return a 500 server error in best effort:
6407 * if there are no room avalaible in the buffer,
6408 * just close the connection.
6409 */
6410 bi_putblk(res, error_500, strlen(error_500));
6411 if (!(strm->flags & SF_ERR_MASK))
6412 strm->flags |= SF_ERR_RESOURCE;
6413 si_shutw(si);
6414 si_shutr(si);
6415 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6416}
6417
6418static void hlua_applet_http_release(struct appctx *ctx)
6419{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006420 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006421 task_free(ctx->ctx.hlua_apphttp.task);
6422 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006423 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006424 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006425}
6426
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006427/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6428 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006429 *
6430 * This function can fail with an abort() due to an Lua critical error.
6431 * We are in the configuration parsing process of HAProxy, this abort() is
6432 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006433 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006434static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6435 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006436{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006437 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006438 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006439
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006440 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006441 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006442 if (!rule->arg.hlua_rule) {
6443 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006444 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006445 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006446
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006447 /* Memory for arguments. */
6448 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6449 if (!rule->arg.hlua_rule->args) {
6450 memprintf(err, "out of memory error");
6451 return ACT_RET_PRS_ERR;
6452 }
6453
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006454 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006455 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006456
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006457 /* Expect some arguments */
6458 for (i = 0; i < fcn->nargs; i++) {
6459 if (*args[i+1] == '\0') {
6460 memprintf(err, "expect %d arguments", fcn->nargs);
6461 return ACT_RET_PRS_ERR;
6462 }
6463 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6464 if (!rule->arg.hlua_rule->args[i]) {
6465 memprintf(err, "out of memory error");
6466 return ACT_RET_PRS_ERR;
6467 }
6468 (*cur_arg)++;
6469 }
6470 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006471
Thierry FOURNIER42148732015-09-02 17:17:33 +02006472 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006473 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006474 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006475}
6476
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006477static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6478 struct act_rule *rule, char **err)
6479{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006480 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006481
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006482 /* HTTP applets are forbidden in tcp-request rules.
6483 * HTTP applet request requires everything initilized by
6484 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6485 * The applet will be immediately initilized, but its before
6486 * the call of this analyzer.
6487 */
6488 if (rule->from != ACT_F_HTTP_REQ) {
6489 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6490 return ACT_RET_PRS_ERR;
6491 }
6492
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006493 /* Memory for the rule. */
6494 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6495 if (!rule->arg.hlua_rule) {
6496 memprintf(err, "out of memory error");
6497 return ACT_RET_PRS_ERR;
6498 }
6499
6500 /* Reference the Lua function and store the reference. */
6501 rule->arg.hlua_rule->fcn = *fcn;
6502
6503 /* TODO: later accept arguments. */
6504 rule->arg.hlua_rule->args = NULL;
6505
6506 /* Add applet pointer in the rule. */
6507 rule->applet.obj_type = OBJ_TYPE_APPLET;
6508 rule->applet.name = fcn->name;
6509 rule->applet.init = hlua_applet_http_init;
6510 rule->applet.fct = hlua_applet_http_fct;
6511 rule->applet.release = hlua_applet_http_release;
6512 rule->applet.timeout = hlua_timeout_applet;
6513
6514 return ACT_RET_PRS_OK;
6515}
6516
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006517/* This function is an LUA binding used for registering
6518 * "sample-conv" functions. It expects a converter name used
6519 * in the haproxy configuration file, and an LUA function.
6520 */
6521__LJMP static int hlua_register_action(lua_State *L)
6522{
6523 struct action_kw_list *akl;
6524 const char *name;
6525 int ref;
6526 int len;
6527 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006528 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006529
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006530 /* Initialise the number of expected arguments at 0. */
6531 nargs = 0;
6532
6533 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6534 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006535
6536 /* First argument : converter name. */
6537 name = MAY_LJMP(luaL_checkstring(L, 1));
6538
6539 /* Second argument : environment. */
6540 if (lua_type(L, 2) != LUA_TTABLE)
6541 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6542
6543 /* Third argument : lua function. */
6544 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6545
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006546 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6547 if (lua_gettop(L) >= 4)
6548 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6549
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006550 /* browse the second argulent as an array. */
6551 lua_pushnil(L);
6552 while (lua_next(L, 2) != 0) {
6553 if (lua_type(L, -1) != LUA_TSTRING)
6554 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6555
6556 /* Check required environment. Only accepted "http" or "tcp". */
6557 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006558 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006559 if (!akl)
6560 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006561 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006562 if (!fcn)
6563 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6564
6565 /* Fill fcn. */
6566 fcn->name = strdup(name);
6567 if (!fcn->name)
6568 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6569 fcn->function_ref = ref;
6570
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006571 /* Set the expected number od arguments. */
6572 fcn->nargs = nargs;
6573
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006574 /* List head */
6575 akl->list.n = akl->list.p = NULL;
6576
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006577 /* action keyword. */
6578 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006579 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006580 if (!akl->kw[0].kw)
6581 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6582
6583 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6584
6585 akl->kw[0].match_pfx = 0;
6586 akl->kw[0].private = fcn;
6587 akl->kw[0].parse = action_register_lua;
6588
6589 /* select the action registering point. */
6590 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6591 tcp_req_cont_keywords_register(akl);
6592 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6593 tcp_res_cont_keywords_register(akl);
6594 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6595 http_req_keywords_register(akl);
6596 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6597 http_res_keywords_register(akl);
6598 else
6599 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6600 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6601 "are expected.", lua_tostring(L, -1)));
6602
6603 /* pop the environment string. */
6604 lua_pop(L, 1);
6605 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006606 return ACT_RET_PRS_OK;
6607}
6608
6609static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6610 struct act_rule *rule, char **err)
6611{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006612 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006613
6614 /* Memory for the rule. */
6615 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6616 if (!rule->arg.hlua_rule) {
6617 memprintf(err, "out of memory error");
6618 return ACT_RET_PRS_ERR;
6619 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006620
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006621 /* Reference the Lua function and store the reference. */
6622 rule->arg.hlua_rule->fcn = *fcn;
6623
6624 /* TODO: later accept arguments. */
6625 rule->arg.hlua_rule->args = NULL;
6626
6627 /* Add applet pointer in the rule. */
6628 rule->applet.obj_type = OBJ_TYPE_APPLET;
6629 rule->applet.name = fcn->name;
6630 rule->applet.init = hlua_applet_tcp_init;
6631 rule->applet.fct = hlua_applet_tcp_fct;
6632 rule->applet.release = hlua_applet_tcp_release;
6633 rule->applet.timeout = hlua_timeout_applet;
6634
6635 return 0;
6636}
6637
6638/* This function is an LUA binding used for registering
6639 * "sample-conv" functions. It expects a converter name used
6640 * in the haproxy configuration file, and an LUA function.
6641 */
6642__LJMP static int hlua_register_service(lua_State *L)
6643{
6644 struct action_kw_list *akl;
6645 const char *name;
6646 const char *env;
6647 int ref;
6648 int len;
6649 struct hlua_function *fcn;
6650
6651 MAY_LJMP(check_args(L, 3, "register_service"));
6652
6653 /* First argument : converter name. */
6654 name = MAY_LJMP(luaL_checkstring(L, 1));
6655
6656 /* Second argument : environment. */
6657 env = MAY_LJMP(luaL_checkstring(L, 2));
6658
6659 /* Third argument : lua function. */
6660 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6661
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006662 /* Allocate and fill the sample fetch keyword struct. */
6663 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6664 if (!akl)
6665 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6666 fcn = calloc(1, sizeof(*fcn));
6667 if (!fcn)
6668 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6669
6670 /* Fill fcn. */
6671 len = strlen("<lua.>") + strlen(name) + 1;
6672 fcn->name = calloc(1, len);
6673 if (!fcn->name)
6674 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6675 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6676 fcn->function_ref = ref;
6677
6678 /* List head */
6679 akl->list.n = akl->list.p = NULL;
6680
6681 /* converter keyword. */
6682 len = strlen("lua.") + strlen(name) + 1;
6683 akl->kw[0].kw = calloc(1, len);
6684 if (!akl->kw[0].kw)
6685 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6686
6687 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6688
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01006689 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006690 if (strcmp(env, "tcp") == 0)
6691 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006692 else if (strcmp(env, "http") == 0)
6693 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006694 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006695 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6696 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006697
6698 akl->kw[0].match_pfx = 0;
6699 akl->kw[0].private = fcn;
6700
6701 /* End of array. */
6702 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6703
6704 /* Register this new converter */
6705 service_keywords_register(akl);
6706
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006707 return 0;
6708}
6709
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006710/* This function initialises Lua cli handler. It copies the
6711 * arguments in the Lua stack and create channel IO objects.
6712 */
6713static int hlua_cli_parse_fct(char **args, struct appctx *appctx, void *private)
6714{
6715 struct hlua *hlua;
6716 struct hlua_function *fcn;
6717 int i;
6718 const char *error;
6719
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006720 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006721 appctx->ctx.hlua_cli.fcn = private;
6722
6723 hlua = pool_alloc2(pool2_hlua);
6724 if (!hlua) {
6725 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006726 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006727 }
6728 HLUA_INIT(hlua);
6729 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006730
6731 /* Create task used by signal to wakeup applets.
6732 * We use the same wakeup fonction than the Lua applet_tcp and
6733 * applet_http. It is absolutely compatible.
6734 */
6735 appctx->ctx.hlua_cli.task = task_new();
6736 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01006737 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006738 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006739 }
6740 appctx->ctx.hlua_cli.task->nice = 0;
6741 appctx->ctx.hlua_cli.task->context = appctx;
6742 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
6743
6744 /* Initialises the Lua context */
6745 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
6746 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006747 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006748 }
6749
6750 /* The following Lua calls can fail. */
6751 if (!SET_SAFE_LJMP(hlua->T)) {
6752 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6753 error = lua_tostring(hlua->T, -1);
6754 else
6755 error = "critical error";
6756 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
6757 goto error;
6758 }
6759
6760 /* Check stack available size. */
6761 if (!lua_checkstack(hlua->T, 2)) {
6762 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6763 goto error;
6764 }
6765
6766 /* Restore the function in the stack. */
6767 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
6768
6769 /* Once the arguments parsed, the CLI is like an AppletTCP,
6770 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006771 */
6772 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
6773 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6774 goto error;
6775 }
6776 hlua->nargs = 1;
6777
6778 /* push keywords in the stack. */
6779 for (i = 0; *args[i]; i++) {
6780 /* Check stack available size. */
6781 if (!lua_checkstack(hlua->T, 1)) {
6782 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6783 goto error;
6784 }
6785 lua_pushstring(hlua->T, args[i]);
6786 hlua->nargs++;
6787 }
6788
6789 /* We must initialize the execution timeouts. */
6790 hlua->max_time = hlua_timeout_session;
6791
6792 /* At this point the execution is safe. */
6793 RESET_SAFE_LJMP(hlua->T);
6794
6795 /* It's ok */
6796 return 0;
6797
6798 /* It's not ok. */
6799error:
6800 RESET_SAFE_LJMP(hlua->T);
6801 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006802 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006803 return 1;
6804}
6805
6806static int hlua_cli_io_handler_fct(struct appctx *appctx)
6807{
6808 struct hlua *hlua;
6809 struct stream_interface *si;
6810 struct hlua_function *fcn;
6811
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006812 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006813 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01006814 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006815
6816 /* If the stream is disconnect or closed, ldo nothing. */
6817 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6818 return 1;
6819
6820 /* Execute the function. */
6821 switch (hlua_ctx_resume(hlua, 1)) {
6822
6823 /* finished. */
6824 case HLUA_E_OK:
6825 return 1;
6826
6827 /* yield. */
6828 case HLUA_E_AGAIN:
6829 /* We want write. */
6830 if (HLUA_IS_WAKERESWR(hlua))
6831 si_applet_cant_put(si);
6832 /* Set the timeout. */
6833 if (hlua->wake_time != TICK_ETERNITY)
6834 task_schedule(hlua->task, hlua->wake_time);
6835 return 0;
6836
6837 /* finished with error. */
6838 case HLUA_E_ERRMSG:
6839 /* Display log. */
6840 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
6841 fcn->name, lua_tostring(hlua->T, -1));
6842 lua_pop(hlua->T, 1);
6843 return 1;
6844
6845 case HLUA_E_ERR:
6846 /* Display log. */
6847 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
6848 fcn->name);
6849 return 1;
6850
6851 default:
6852 return 1;
6853 }
6854
6855 return 1;
6856}
6857
6858static void hlua_cli_io_release_fct(struct appctx *appctx)
6859{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006860 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006861 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006862}
6863
6864/* This function is an LUA binding used for registering
6865 * new keywords in the cli. It expects a list of keywords
6866 * which are the "path". It is limited to 5 keywords. A
6867 * description of the command, a function to be executed
6868 * for the parsing and a function for io handlers.
6869 */
6870__LJMP static int hlua_register_cli(lua_State *L)
6871{
6872 struct cli_kw_list *cli_kws;
6873 const char *message;
6874 int ref_io;
6875 int len;
6876 struct hlua_function *fcn;
6877 int index;
6878 int i;
6879
6880 MAY_LJMP(check_args(L, 3, "register_cli"));
6881
6882 /* First argument : an array of maximum 5 keywords. */
6883 if (!lua_istable(L, 1))
6884 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
6885
6886 /* Second argument : string with contextual message. */
6887 message = MAY_LJMP(luaL_checkstring(L, 2));
6888
6889 /* Third and fourth argument : lua function. */
6890 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
6891
6892 /* Allocate and fill the sample fetch keyword struct. */
6893 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
6894 if (!cli_kws)
6895 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6896 fcn = calloc(1, sizeof(*fcn));
6897 if (!fcn)
6898 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6899
6900 /* Fill path. */
6901 index = 0;
6902 lua_pushnil(L);
6903 while(lua_next(L, 1) != 0) {
6904 if (index >= 5)
6905 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
6906 if (lua_type(L, -1) != LUA_TSTRING)
6907 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
6908 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
6909 if (!cli_kws->kw[0].str_kw[index])
6910 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6911 index++;
6912 lua_pop(L, 1);
6913 }
6914
6915 /* Copy help message. */
6916 cli_kws->kw[0].usage = strdup(message);
6917 if (!cli_kws->kw[0].usage)
6918 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6919
6920 /* Fill fcn io handler. */
6921 len = strlen("<lua.cli>") + 1;
6922 for (i = 0; i < index; i++)
6923 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
6924 fcn->name = calloc(1, len);
6925 if (!fcn->name)
6926 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6927 strncat((char *)fcn->name, "<lua.cli", len);
6928 for (i = 0; i < index; i++) {
6929 strncat((char *)fcn->name, ".", len);
6930 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
6931 }
6932 strncat((char *)fcn->name, ">", len);
6933 fcn->function_ref = ref_io;
6934
6935 /* Fill last entries. */
6936 cli_kws->kw[0].private = fcn;
6937 cli_kws->kw[0].parse = hlua_cli_parse_fct;
6938 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
6939 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
6940
6941 /* Register this new converter */
6942 cli_register_kw(cli_kws);
6943
6944 return 0;
6945}
6946
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006947static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
6948 struct proxy *defpx, const char *file, int line,
6949 char **err, unsigned int *timeout)
6950{
6951 const char *error;
6952
6953 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
6954 if (error && *error != '\0') {
6955 memprintf(err, "%s: invalid timeout", args[0]);
6956 return -1;
6957 }
6958 return 0;
6959}
6960
6961static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
6962 struct proxy *defpx, const char *file, int line,
6963 char **err)
6964{
6965 return hlua_read_timeout(args, section_type, curpx, defpx,
6966 file, line, err, &hlua_timeout_session);
6967}
6968
6969static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
6970 struct proxy *defpx, const char *file, int line,
6971 char **err)
6972{
6973 return hlua_read_timeout(args, section_type, curpx, defpx,
6974 file, line, err, &hlua_timeout_task);
6975}
6976
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006977static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
6978 struct proxy *defpx, const char *file, int line,
6979 char **err)
6980{
6981 return hlua_read_timeout(args, section_type, curpx, defpx,
6982 file, line, err, &hlua_timeout_applet);
6983}
6984
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006985static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
6986 struct proxy *defpx, const char *file, int line,
6987 char **err)
6988{
6989 char *error;
6990
6991 hlua_nb_instruction = strtoll(args[1], &error, 10);
6992 if (*error != '\0') {
6993 memprintf(err, "%s: invalid number", args[0]);
6994 return -1;
6995 }
6996 return 0;
6997}
6998
Willy Tarreau32f61e22015-03-18 17:54:59 +01006999static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7000 struct proxy *defpx, const char *file, int line,
7001 char **err)
7002{
7003 char *error;
7004
7005 if (*(args[1]) == 0) {
7006 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7007 return -1;
7008 }
7009 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7010 if (*error != '\0') {
7011 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7012 return -1;
7013 }
7014 return 0;
7015}
7016
7017
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007018/* This function is called by the main configuration key "lua-load". It loads and
7019 * execute an lua file during the parsing of the HAProxy configuration file. It is
7020 * the main lua entry point.
7021 *
7022 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7023 * occured, otherwise it returns 0.
7024 *
7025 * In some error case, LUA set an error message in top of the stack. This function
7026 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007027 *
7028 * This function can fail with an abort() due to an Lua critical error.
7029 * We are in the configuration parsing process of HAProxy, this abort() is
7030 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007031 */
7032static int hlua_load(char **args, int section_type, struct proxy *curpx,
7033 struct proxy *defpx, const char *file, int line,
7034 char **err)
7035{
7036 int error;
7037
7038 /* Just load and compile the file. */
7039 error = luaL_loadfile(gL.T, args[1]);
7040 if (error) {
7041 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
7042 lua_pop(gL.T, 1);
7043 return -1;
7044 }
7045
7046 /* If no syntax error where detected, execute the code. */
7047 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7048 switch (error) {
7049 case LUA_OK:
7050 break;
7051 case LUA_ERRRUN:
7052 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
7053 lua_pop(gL.T, 1);
7054 return -1;
7055 case LUA_ERRMEM:
7056 memprintf(err, "lua out of memory error\n");
7057 return -1;
7058 case LUA_ERRERR:
7059 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
7060 lua_pop(gL.T, 1);
7061 return -1;
7062 case LUA_ERRGCMM:
7063 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
7064 lua_pop(gL.T, 1);
7065 return -1;
7066 default:
7067 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
7068 lua_pop(gL.T, 1);
7069 return -1;
7070 }
7071
7072 return 0;
7073}
7074
7075/* configuration keywords declaration */
7076static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007077 { CFG_GLOBAL, "lua-load", hlua_load },
7078 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7079 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007080 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007081 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007082 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007083 { 0, NULL, NULL },
7084}};
7085
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007086/* This function can fail with an abort() due to an Lua critical error.
7087 * We are in the initialisation process of HAProxy, this abort() is
7088 * tolerated.
7089 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007090int hlua_post_init()
7091{
7092 struct hlua_init_function *init;
7093 const char *msg;
7094 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007095 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007096
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007097 /* Call post initialisation function in safe environement. */
7098 if (!SET_SAFE_LJMP(gL.T)) {
7099 if (lua_type(gL.T, -1) == LUA_TSTRING)
7100 error = lua_tostring(gL.T, -1);
7101 else
7102 error = "critical error";
7103 fprintf(stderr, "Lua post-init: %s.\n", error);
7104 exit(1);
7105 }
7106 hlua_fcn_post_init(gL.T);
7107 RESET_SAFE_LJMP(gL.T);
7108
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007109 list_for_each_entry(init, &hlua_init_functions, l) {
7110 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7111 ret = hlua_ctx_resume(&gL, 0);
7112 switch (ret) {
7113 case HLUA_E_OK:
7114 lua_pop(gL.T, -1);
7115 return 1;
7116 case HLUA_E_AGAIN:
7117 Alert("lua init: yield not allowed.\n");
7118 return 0;
7119 case HLUA_E_ERRMSG:
7120 msg = lua_tostring(gL.T, -1);
7121 Alert("lua init: %s.\n", msg);
7122 return 0;
7123 case HLUA_E_ERR:
7124 default:
7125 Alert("lua init: unknown runtime error.\n");
7126 return 0;
7127 }
7128 }
7129 return 1;
7130}
7131
Willy Tarreau32f61e22015-03-18 17:54:59 +01007132/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7133 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7134 * is the previously allocated size or the kind of object in case of a new
7135 * allocation. <nsize> is the requested new size.
7136 */
7137static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7138{
7139 struct hlua_mem_allocator *zone = ud;
7140
7141 if (nsize == 0) {
7142 /* it's a free */
7143 if (ptr)
7144 zone->allocated -= osize;
7145 free(ptr);
7146 return NULL;
7147 }
7148
7149 if (!ptr) {
7150 /* it's a new allocation */
7151 if (zone->limit && zone->allocated + nsize > zone->limit)
7152 return NULL;
7153
7154 ptr = malloc(nsize);
7155 if (ptr)
7156 zone->allocated += nsize;
7157 return ptr;
7158 }
7159
7160 /* it's a realloc */
7161 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7162 return NULL;
7163
7164 ptr = realloc(ptr, nsize);
7165 if (ptr)
7166 zone->allocated += nsize - osize;
7167 return ptr;
7168}
7169
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007170/* Ithis function can fail with an abort() due to an Lua critical error.
7171 * We are in the initialisation process of HAProxy, this abort() is
7172 * tolerated.
7173 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007174void hlua_init(void)
7175{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007176 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007177 int idx;
7178 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007179 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007180 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007181 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007182#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007183 struct srv_kw *kw;
7184 int tmp_error;
7185 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007186 char *args[] = { /* SSL client configuration. */
7187 "ssl",
7188 "verify",
7189 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007190 NULL
7191 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007192#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007193
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007194 /* Initialise struct hlua and com signals pool */
7195 pool2_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007196 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
7197
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007198 /* Register configuration keywords. */
7199 cfg_register_keywords(&cfg_kws);
7200
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007201 /* Init main lua stack. */
7202 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007203 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007204 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007205 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007206 hlua_sethlua(&gL);
7207 gL.Tref = LUA_REFNIL;
7208 gL.task = NULL;
7209
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007210 /* From this point, until the end of the initialisation fucntion,
7211 * the Lua function can fail with an abort. We are in the initialisation
7212 * process of HAProxy, this abort() is tolerated.
7213 */
7214
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007215 /* Initialise lua. */
7216 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007217
Thierry Fournier75933d42016-01-21 09:30:18 +01007218 /* Set safe environment for the initialisation. */
7219 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007220 if (lua_type(gL.T, -1) == LUA_TSTRING)
7221 error_msg = lua_tostring(gL.T, -1);
7222 else
7223 error_msg = "critical error";
7224 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007225 exit(1);
7226 }
7227
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007228 /*
7229 *
7230 * Create "core" object.
7231 *
7232 */
7233
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007234 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007235 lua_newtable(gL.T);
7236
7237 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007238 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007239 hlua_class_const_int(gL.T, log_levels[i], i);
7240
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007241 /* Register special functions. */
7242 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007243 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007244 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007245 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007246 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007247 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007248 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007249 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007250 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007251 hlua_class_function(gL.T, "sleep", hlua_sleep);
7252 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007253 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7254 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7255 hlua_class_function(gL.T, "set_map", hlua_set_map);
7256 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007257 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007258 hlua_class_function(gL.T, "log", hlua_log);
7259 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7260 hlua_class_function(gL.T, "Info", hlua_log_info);
7261 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7262 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007263 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007264 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007265
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007266 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007267
7268 /*
7269 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007270 * Register class Map
7271 *
7272 */
7273
7274 /* This table entry is the object "Map" base. */
7275 lua_newtable(gL.T);
7276
7277 /* register pattern types. */
7278 for (i=0; i<PAT_MATCH_NUM; i++)
7279 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007280 for (i=0; i<PAT_MATCH_NUM; i++) {
7281 snprintf(trash.str, trash.size, "_%s", pat_match_names[i]);
7282 hlua_class_const_int(gL.T, trash.str, i);
7283 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007284
7285 /* register constructor. */
7286 hlua_class_function(gL.T, "new", hlua_map_new);
7287
7288 /* Create and fill the metatable. */
7289 lua_newtable(gL.T);
7290
7291 /* Create and fille the __index entry. */
7292 lua_pushstring(gL.T, "__index");
7293 lua_newtable(gL.T);
7294
7295 /* Register . */
7296 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7297 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7298
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007299 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007300
Thierry Fournier45e78d72016-02-19 18:34:46 +01007301 /* Register previous table in the registry with reference and named entry.
7302 * The function hlua_register_metatable() pops the stack, so we
7303 * previously create a copy of the table.
7304 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007305 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007306 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007307
7308 /* Assign the metatable to the mai Map object. */
7309 lua_setmetatable(gL.T, -2);
7310
7311 /* Set a name to the table. */
7312 lua_setglobal(gL.T, "Map");
7313
7314 /*
7315 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007316 * Register class Channel
7317 *
7318 */
7319
7320 /* Create and fill the metatable. */
7321 lua_newtable(gL.T);
7322
7323 /* Create and fille the __index entry. */
7324 lua_pushstring(gL.T, "__index");
7325 lua_newtable(gL.T);
7326
7327 /* Register . */
7328 hlua_class_function(gL.T, "get", hlua_channel_get);
7329 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7330 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7331 hlua_class_function(gL.T, "set", hlua_channel_set);
7332 hlua_class_function(gL.T, "append", hlua_channel_append);
7333 hlua_class_function(gL.T, "send", hlua_channel_send);
7334 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7335 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7336 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007337 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007338
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007339 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007340
7341 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007342 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007343
7344 /*
7345 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007346 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007347 *
7348 */
7349
7350 /* Create and fill the metatable. */
7351 lua_newtable(gL.T);
7352
7353 /* Create and fille the __index entry. */
7354 lua_pushstring(gL.T, "__index");
7355 lua_newtable(gL.T);
7356
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007357 /* Browse existing fetches and create the associated
7358 * object method.
7359 */
7360 sf = NULL;
7361 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7362
7363 /* Dont register the keywork if the arguments check function are
7364 * not safe during the runtime.
7365 */
7366 if ((sf->val_args != NULL) &&
7367 (sf->val_args != val_payload_lv) &&
7368 (sf->val_args != val_hdr))
7369 continue;
7370
7371 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7372 * by an underscore.
7373 */
7374 strncpy(trash.str, sf->kw, trash.size);
7375 trash.str[trash.size - 1] = '\0';
7376 for (p = trash.str; *p; p++)
7377 if (*p == '.' || *p == '-' || *p == '+')
7378 *p = '_';
7379
7380 /* Register the function. */
7381 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007382 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007383 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007384 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007385 }
7386
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007387 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007388
7389 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007390 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007391
7392 /*
7393 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007394 * Register class Converters
7395 *
7396 */
7397
7398 /* Create and fill the metatable. */
7399 lua_newtable(gL.T);
7400
7401 /* Create and fill the __index entry. */
7402 lua_pushstring(gL.T, "__index");
7403 lua_newtable(gL.T);
7404
7405 /* Browse existing converters and create the associated
7406 * object method.
7407 */
7408 sc = NULL;
7409 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7410 /* Dont register the keywork if the arguments check function are
7411 * not safe during the runtime.
7412 */
7413 if (sc->val_args != NULL)
7414 continue;
7415
7416 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7417 * by an underscore.
7418 */
7419 strncpy(trash.str, sc->kw, trash.size);
7420 trash.str[trash.size - 1] = '\0';
7421 for (p = trash.str; *p; p++)
7422 if (*p == '.' || *p == '-' || *p == '+')
7423 *p = '_';
7424
7425 /* Register the function. */
7426 lua_pushstring(gL.T, trash.str);
7427 lua_pushlightuserdata(gL.T, sc);
7428 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007429 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007430 }
7431
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007432 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007433
7434 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007435 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007436
7437 /*
7438 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007439 * Register class HTTP
7440 *
7441 */
7442
7443 /* Create and fill the metatable. */
7444 lua_newtable(gL.T);
7445
7446 /* Create and fille the __index entry. */
7447 lua_pushstring(gL.T, "__index");
7448 lua_newtable(gL.T);
7449
7450 /* Register Lua functions. */
7451 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7452 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7453 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7454 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7455 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7456 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7457 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7458 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7459 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7460 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7461
7462 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7463 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7464 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7465 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7466 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7467 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007468 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007469
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007470 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007471
7472 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007473 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007474
7475 /*
7476 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007477 * Register class AppletTCP
7478 *
7479 */
7480
7481 /* Create and fill the metatable. */
7482 lua_newtable(gL.T);
7483
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007484 /* Create and fille the __index entry. */
7485 lua_pushstring(gL.T, "__index");
7486 lua_newtable(gL.T);
7487
7488 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007489 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7490 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7491 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7492 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7493 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007494 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7495 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7496 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007497
7498 lua_settable(gL.T, -3);
7499
7500 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007501 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007502
7503 /*
7504 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007505 * Register class AppletHTTP
7506 *
7507 */
7508
7509 /* Create and fill the metatable. */
7510 lua_newtable(gL.T);
7511
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007512 /* Create and fille the __index entry. */
7513 lua_pushstring(gL.T, "__index");
7514 lua_newtable(gL.T);
7515
7516 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007517 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7518 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007519 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7520 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7521 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007522 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7523 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7524 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7525 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7526 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7527 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7528
7529 lua_settable(gL.T, -3);
7530
7531 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007532 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007533
7534 /*
7535 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007536 * Register class TXN
7537 *
7538 */
7539
7540 /* Create and fill the metatable. */
7541 lua_newtable(gL.T);
7542
7543 /* Create and fille the __index entry. */
7544 lua_pushstring(gL.T, "__index");
7545 lua_newtable(gL.T);
7546
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007547 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007548 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7549 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007550 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007551 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007552 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007553 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007554 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7555 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7556 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007557 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7558 hlua_class_function(gL.T, "log", hlua_txn_log);
7559 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7560 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7561 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7562 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007563
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007564 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007565
7566 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007567 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007568
7569 /*
7570 *
7571 * Register class Socket
7572 *
7573 */
7574
7575 /* Create and fill the metatable. */
7576 lua_newtable(gL.T);
7577
7578 /* Create and fille the __index entry. */
7579 lua_pushstring(gL.T, "__index");
7580 lua_newtable(gL.T);
7581
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007582#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007583 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007584#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007585 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7586 hlua_class_function(gL.T, "send", hlua_socket_send);
7587 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7588 hlua_class_function(gL.T, "close", hlua_socket_close);
7589 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7590 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7591 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7592 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7593
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007594 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007595
7596 /* Register the garbage collector entry. */
7597 lua_pushstring(gL.T, "__gc");
7598 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007599 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007600
7601 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007602 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007603
7604 /* Proxy and server configuration initialisation. */
7605 memset(&socket_proxy, 0, sizeof(socket_proxy));
7606 init_new_proxy(&socket_proxy);
7607 socket_proxy.parent = NULL;
7608 socket_proxy.last_change = now.tv_sec;
7609 socket_proxy.id = "LUA-SOCKET";
7610 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7611 socket_proxy.maxconn = 0;
7612 socket_proxy.accept = NULL;
7613 socket_proxy.options2 |= PR_O2_INDEPSTR;
7614 socket_proxy.srv = NULL;
7615 socket_proxy.conn_retries = 0;
7616 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7617
7618 /* Init TCP server: unchanged parameters */
7619 memset(&socket_tcp, 0, sizeof(socket_tcp));
7620 socket_tcp.next = NULL;
7621 socket_tcp.proxy = &socket_proxy;
7622 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7623 LIST_INIT(&socket_tcp.actconns);
7624 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007625 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007626 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007627 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007628 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
7629 socket_tcp.last_change = 0;
7630 socket_tcp.id = "LUA-TCP-CONN";
7631 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7632 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7633 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7634
7635 /* XXX: Copy default parameter from default server,
7636 * but the default server is not initialized.
7637 */
7638 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7639 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7640 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7641 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7642 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7643 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7644 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7645 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7646 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7647 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7648
7649 socket_tcp.check.status = HCHK_STATUS_INI;
7650 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7651 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7652 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7653 socket_tcp.check.server = &socket_tcp;
7654
7655 socket_tcp.agent.status = HCHK_STATUS_INI;
7656 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7657 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7658 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7659 socket_tcp.agent.server = &socket_tcp;
7660
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007661 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007662
7663#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007664 /* Init TCP server: unchanged parameters */
7665 memset(&socket_ssl, 0, sizeof(socket_ssl));
7666 socket_ssl.next = NULL;
7667 socket_ssl.proxy = &socket_proxy;
7668 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7669 LIST_INIT(&socket_ssl.actconns);
7670 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007671 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007672 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007673 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007674 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
7675 socket_ssl.last_change = 0;
7676 socket_ssl.id = "LUA-SSL-CONN";
7677 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7678 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7679 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7680
7681 /* XXX: Copy default parameter from default server,
7682 * but the default server is not initialized.
7683 */
7684 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7685 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7686 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7687 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7688 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7689 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7690 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7691 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7692 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7693 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7694
7695 socket_ssl.check.status = HCHK_STATUS_INI;
7696 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7697 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7698 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7699 socket_ssl.check.server = &socket_ssl;
7700
7701 socket_ssl.agent.status = HCHK_STATUS_INI;
7702 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7703 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7704 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7705 socket_ssl.agent.server = &socket_ssl;
7706
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007707 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007708 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007709
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007710 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007711 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7712 /*
7713 *
7714 * If the keyword is not known, we can search in the registered
7715 * server keywords. This is usefull to configure special SSL
7716 * features like client certificates and ssl_verify.
7717 *
7718 */
7719 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7720 if (tmp_error != 0) {
7721 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7722 abort(); /* This must be never arrives because the command line
7723 not editable by the user. */
7724 }
7725 idx += kw->skip;
7726 }
7727 }
7728
7729 /* Initialize SSL server. */
Willy Tarreau17d45382016-12-22 21:16:08 +01007730 if (socket_ssl.xprt->prepare_srv)
7731 socket_ssl.xprt->prepare_srv(&socket_ssl);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007732#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007733
7734 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007735}
Willy Tarreaubb57d942016-12-21 19:04:56 +01007736
7737__attribute__((constructor))
7738static void __hlua_init(void)
7739{
7740 char *ptr = NULL;
7741 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
7742 hap_register_build_opts(ptr, 1);
7743}