blob: 503675bad84a098e359b95ca94f86581a1912f2e [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010013#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020014#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010016#include <lauxlib.h>
17#include <lua.h>
18#include <lualib.h>
19
Thierry FOURNIER463119c2015-03-10 00:35:36 +010020#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
21#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010022#endif
23
Thierry FOURNIER380d0932015-01-23 14:27:52 +010024#include <ebpttree.h>
25
26#include <common/cfgparse.h>
27
William Lallemand9ed62032016-11-21 17:49:11 +010028#include <types/cli.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010029#include <types/hlua.h>
30#include <types/proxy.h>
William Lallemand9ed62032016-11-21 17:49:11 +010031#include <types/stats.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010032
Thierry FOURNIER55da1652015-01-23 11:36:30 +010033#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020034#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010035#include <proto/channel.h>
William Lallemand9ed62032016-11-21 17:49:11 +010036#include <proto/cli.h>
Willy Tarreaua71f6422016-11-16 17:00:14 +010037#include <proto/connection.h>
William Lallemand9ed62032016-11-21 17:49:11 +010038#include <proto/stats.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010039#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010040#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010041#include <proto/hlua_fcn.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020042#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010043#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010044#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010045#include <proto/payload.h>
46#include <proto/proto_http.h>
47#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010048#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020049#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020050#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010051#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010052#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010053#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020054#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010055
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010056/* Lua uses longjmp to perform yield or throwing errors. This
57 * macro is used only for identifying the function that can
58 * not return because a longjmp is executed.
59 * __LJMP marks a prototype of hlua file that can use longjmp.
60 * WILL_LJMP() marks an lua function that will use longjmp.
61 * MAY_LJMP() marks an lua function that may use longjmp.
62 */
63#define __LJMP
64#define WILL_LJMP(func) func
65#define MAY_LJMP(func) func
66
Thierry FOURNIERbabae282015-09-17 11:36:37 +020067/* This couple of function executes securely some Lua calls outside of
68 * the lua runtime environment. Each Lua call can return a longjmp
69 * if it encounter a memory error.
70 *
71 * Lua documentation extract:
72 *
73 * If an error happens outside any protected environment, Lua calls
74 * a panic function (see lua_atpanic) and then calls abort, thus
75 * exiting the host application. Your panic function can avoid this
76 * exit by never returning (e.g., doing a long jump to your own
77 * recovery point outside Lua).
78 *
79 * The panic function runs as if it were a message handler (see
80 * §2.3); in particular, the error message is at the top of the
81 * stack. However, there is no guarantee about stack space. To push
82 * anything on the stack, the panic function must first check the
83 * available space (see §4.2).
84 *
85 * We must check all the Lua entry point. This includes:
86 * - The include/proto/hlua.h exported functions
87 * - the task wrapper function
88 * - The action wrapper function
89 * - The converters wrapper function
90 * - The sample-fetch wrapper functions
91 *
92 * It is tolerated that the initilisation function returns an abort.
93 * Before each Lua abort, an error message is writed on stderr.
94 *
95 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
96 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
97 * because they must be exists in the program stack when the longjmp
98 * is called.
99 */
100jmp_buf safe_ljmp_env;
101static int hlua_panic_safe(lua_State *L) { return 0; }
102static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
103
104#define SET_SAFE_LJMP(__L) \
105 ({ \
106 int ret; \
107 if (setjmp(safe_ljmp_env) != 0) { \
108 lua_atpanic(__L, hlua_panic_safe); \
109 ret = 0; \
110 } else { \
111 lua_atpanic(__L, hlua_panic_ljmp); \
112 ret = 1; \
113 } \
114 ret; \
115 })
116
117/* If we are the last function catching Lua errors, we
118 * must reset the panic function.
119 */
120#define RESET_SAFE_LJMP(__L) \
121 do { \
122 lua_atpanic(__L, hlua_panic_safe); \
123 } while(0)
124
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200125/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200126#define APPLET_DONE 0x01 /* applet processing is done. */
127#define APPLET_100C 0x02 /* 100 continue expected. */
128#define APPLET_HDR_SENT 0x04 /* Response header sent. */
129#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
130#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100131#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200132
133#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200134
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100135/* The main Lua execution context. */
136struct hlua gL;
137
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100138/* This is the memory pool containing struct lua for applets
139 * (including cli).
140 */
141struct pool_head *pool2_hlua;
142
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100143/* This is the memory pool containing all the signal structs. These
144 * struct are used to store each requiered signal between two tasks.
145 */
146struct pool_head *pool2_hlua_com;
147
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100148/* Used for Socket connection. */
149static struct proxy socket_proxy;
150static struct server socket_tcp;
151#ifdef USE_OPENSSL
152static struct server socket_ssl;
153#endif
154
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100155/* List head of the function called at the initialisation time. */
156struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
157
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100158/* The following variables contains the reference of the different
159 * Lua classes. These references are useful for identify metadata
160 * associated with an object.
161 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100162static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100163static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100164static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100165static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100166static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100167static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200168static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200169static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200170static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100171
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100172/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200173 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100174 * short timeout. Lua linked with tasks doesn't have a timeout
175 * because a task may remain alive during all the haproxy execution.
176 */
177static unsigned int hlua_timeout_session = 4000; /* session timeout. */
178static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200179static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100180
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100181/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
182 * it is used for preventing infinite loops.
183 *
184 * I test the scheer with an infinite loop containing one incrementation
185 * and one test. I run this loop between 10 seconds, I raise a ceil of
186 * 710M loops from one interrupt each 9000 instructions, so I fix the value
187 * to one interrupt each 10 000 instructions.
188 *
189 * configured | Number of
190 * instructions | loops executed
191 * between two | in milions
192 * forced yields |
193 * ---------------+---------------
194 * 10 | 160
195 * 500 | 670
196 * 1000 | 680
197 * 5000 | 700
198 * 7000 | 700
199 * 8000 | 700
200 * 9000 | 710 <- ceil
201 * 10000 | 710
202 * 100000 | 710
203 * 1000000 | 710
204 *
205 */
206static unsigned int hlua_nb_instruction = 10000;
207
Willy Tarreau32f61e22015-03-18 17:54:59 +0100208/* Descriptor for the memory allocation state. If limit is not null, it will
209 * be enforced on any memory allocation.
210 */
211struct hlua_mem_allocator {
212 size_t allocated;
213 size_t limit;
214};
215
216static struct hlua_mem_allocator hlua_global_allocator;
217
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200218static const char error_500[] =
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200219 "HTTP/1.0 500 Internal Server Error\r\n"
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200220 "Cache-Control: no-cache\r\n"
221 "Connection: close\r\n"
222 "Content-Type: text/html\r\n"
223 "\r\n"
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200224 "<html><body><h1>500 Internal Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200225
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100226/* These functions converts types between HAProxy internal args or
227 * sample and LUA types. Another function permits to check if the
228 * LUA stack contains arguments according with an required ARG_T
229 * format.
230 */
231static int hlua_arg2lua(lua_State *L, const struct arg *arg);
232static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100233__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100234 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100235static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100236static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100237static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
238
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200239__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
240
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200241#define SEND_ERR(__be, __fmt, __args...) \
242 do { \
243 send_log(__be, LOG_ERR, __fmt, ## __args); \
244 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
245 Alert(__fmt, ## __args); \
246 } while (0)
247
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100248/* Used to check an Lua function type in the stack. It creates and
249 * returns a reference of the function. This function throws an
250 * error if the rgument is not a "function".
251 */
252__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
253{
254 if (!lua_isfunction(L, argno)) {
255 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
256 WILL_LJMP(luaL_argerror(L, argno, msg));
257 }
258 lua_pushvalue(L, argno);
259 return luaL_ref(L, LUA_REGISTRYINDEX);
260}
261
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200262/* Return the string that is of the top of the stack. */
263const char *hlua_get_top_error_string(lua_State *L)
264{
265 if (lua_gettop(L) < 1)
266 return "unknown error";
267 if (lua_type(L, -1) != LUA_TSTRING)
268 return "unknown error";
269 return lua_tostring(L, -1);
270}
271
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100272/* This function check the number of arguments available in the
273 * stack. If the number of arguments available is not the same
274 * then <nb> an error is throwed.
275 */
276__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
277{
278 if (lua_gettop(L) == nb)
279 return;
280 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
281}
282
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100283/* This fucntion push an error string prefixed by the file name
284 * and the line number where the error is encountered.
285 */
286static int hlua_pusherror(lua_State *L, const char *fmt, ...)
287{
288 va_list argp;
289 va_start(argp, fmt);
290 luaL_where(L, 1);
291 lua_pushvfstring(L, fmt, argp);
292 va_end(argp);
293 lua_concat(L, 2);
294 return 1;
295}
296
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100297/* This function register a new signal. "lua" is the current lua
298 * execution context. It contains a pointer to the associated task.
299 * "link" is a list head attached to an other task that must be wake
300 * the lua task if an event occurs. This is useful with external
301 * events like TCP I/O or sleep functions. This funcion allocate
302 * memory for the signal.
303 */
Thierry FOURNIER847ca662016-12-16 13:07:22 +0100304static struct hlua_com *hlua_com_new(struct list *purge, struct list *event, struct task *wakeup)
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100305{
306 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
307 if (!com)
Thierry FOURNIER847ca662016-12-16 13:07:22 +0100308 return NULL;
309 LIST_ADDQ(purge, &com->purge_me);
310 LIST_ADDQ(event, &com->wake_me);
311 com->task = wakeup;
312 return com;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100313}
314
315/* This function purge all the pending signals when the LUA execution
316 * is finished. This prevent than a coprocess try to wake a deleted
317 * task. This function remove the memory associated to the signal.
318 */
Thierry FOURNIER847ca662016-12-16 13:07:22 +0100319static void hlua_com_purge(struct list *purge)
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100320{
321 struct hlua_com *com, *back;
322
323 /* Delete all pending communication signals. */
Thierry FOURNIER847ca662016-12-16 13:07:22 +0100324 list_for_each_entry_safe(com, back, purge, purge_me) {
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100325 LIST_DEL(&com->purge_me);
326 LIST_DEL(&com->wake_me);
327 pool_free2(pool2_hlua_com, com);
328 }
329}
330
331/* This function sends signals. It wakes all the tasks attached
332 * to a list head, and remove the signal, and free the used
333 * memory.
334 */
335static void hlua_com_wake(struct list *wake)
336{
337 struct hlua_com *com, *back;
338
339 /* Wake task and delete all pending communication signals. */
340 list_for_each_entry_safe(com, back, wake, wake_me) {
341 LIST_DEL(&com->purge_me);
342 LIST_DEL(&com->wake_me);
343 task_wakeup(com->task, TASK_WOKEN_MSG);
344 pool_free2(pool2_hlua_com, com);
345 }
346}
347
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100348/* This functions is used with sample fetch and converters. It
349 * converts the HAProxy configuration argument in a lua stack
350 * values.
351 *
352 * It takes an array of "arg", and each entry of the array is
353 * converted and pushed in the LUA stack.
354 */
355static int hlua_arg2lua(lua_State *L, const struct arg *arg)
356{
357 switch (arg->type) {
358 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100359 case ARGT_TIME:
360 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100361 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100362 break;
363
364 case ARGT_STR:
365 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
366 break;
367
368 case ARGT_IPV4:
369 case ARGT_IPV6:
370 case ARGT_MSK4:
371 case ARGT_MSK6:
372 case ARGT_FE:
373 case ARGT_BE:
374 case ARGT_TAB:
375 case ARGT_SRV:
376 case ARGT_USR:
377 case ARGT_MAP:
378 default:
379 lua_pushnil(L);
380 break;
381 }
382 return 1;
383}
384
385/* This function take one entrie in an LUA stack at the index "ud",
386 * and try to convert it in an HAProxy argument entry. This is useful
387 * with sample fetch wrappers. The input arguments are gived to the
388 * lua wrapper and converted as arg list by thi function.
389 */
390static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
391{
392 switch (lua_type(L, ud)) {
393
394 case LUA_TNUMBER:
395 case LUA_TBOOLEAN:
396 arg->type = ARGT_SINT;
397 arg->data.sint = lua_tointeger(L, ud);
398 break;
399
400 case LUA_TSTRING:
401 arg->type = ARGT_STR;
402 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
403 break;
404
405 case LUA_TUSERDATA:
406 case LUA_TNIL:
407 case LUA_TTABLE:
408 case LUA_TFUNCTION:
409 case LUA_TTHREAD:
410 case LUA_TLIGHTUSERDATA:
411 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200412 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100413 break;
414 }
415 return 1;
416}
417
418/* the following functions are used to convert a struct sample
419 * in Lua type. This useful to convert the return of the
420 * fetchs or converters.
421 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100422static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100423{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200424 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100425 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100426 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200427 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100428 break;
429
430 case SMP_T_BIN:
431 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200432 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100433 break;
434
435 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200436 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100437 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
438 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
439 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
440 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
441 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
442 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
443 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
444 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
445 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200446 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100447 break;
448 default:
449 lua_pushnil(L);
450 break;
451 }
452 break;
453
454 case SMP_T_IPV4:
455 case SMP_T_IPV6:
456 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200457 if (sample_casts[smp->data.type][SMP_T_STR] &&
458 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200459 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100460 else
461 lua_pushnil(L);
462 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100463 default:
464 lua_pushnil(L);
465 break;
466 }
467 return 1;
468}
469
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100470/* the following functions are used to convert a struct sample
471 * in Lua strings. This is useful to convert the return of the
472 * fetchs or converters.
473 */
474static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
475{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200476 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100477
478 case SMP_T_BIN:
479 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200480 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100481 break;
482
483 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200484 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100485 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
486 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
487 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
488 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
489 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
490 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
491 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
492 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
493 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200494 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100495 break;
496 default:
497 lua_pushstring(L, "");
498 break;
499 }
500 break;
501
502 case SMP_T_SINT:
503 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100504 case SMP_T_IPV4:
505 case SMP_T_IPV6:
506 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200507 if (sample_casts[smp->data.type][SMP_T_STR] &&
508 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200509 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100510 else
511 lua_pushstring(L, "");
512 break;
513 default:
514 lua_pushstring(L, "");
515 break;
516 }
517 return 1;
518}
519
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100520/* the following functions are used to convert an Lua type in a
521 * struct sample. This is useful to provide data from a converter
522 * to the LUA code.
523 */
524static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
525{
526 switch (lua_type(L, ud)) {
527
528 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200529 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200530 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100531 break;
532
533
534 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200535 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200536 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100537 break;
538
539 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200540 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100541 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200542 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100543 break;
544
545 case LUA_TUSERDATA:
546 case LUA_TNIL:
547 case LUA_TTABLE:
548 case LUA_TFUNCTION:
549 case LUA_TTHREAD:
550 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200551 case LUA_TNONE:
552 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200553 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200554 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100555 break;
556 }
557 return 1;
558}
559
560/* This function check the "argp" builded by another conversion function
561 * is in accord with the expected argp defined by the "mask". The fucntion
562 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100563 *
564 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
565 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100566 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100567__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100568 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100569{
570 int min_arg;
571 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100572 struct proxy *px;
573 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100574
575 idx = 0;
576 min_arg = ARGM(mask);
577 mask >>= ARGM_BITS;
578
579 while (1) {
580
581 /* Check oversize. */
582 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100583 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100584 }
585
586 /* Check for mandatory arguments. */
587 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100588 if (idx < min_arg) {
589
590 /* If miss other argument than the first one, we return an error. */
591 if (idx > 0)
592 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
593
594 /* If first argument have a certain type, some default values
595 * may be used. See the function smp_resolve_args().
596 */
597 switch (mask & ARGT_MASK) {
598
599 case ARGT_FE:
600 if (!(p->cap & PR_CAP_FE))
601 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
602 argp[idx].data.prx = p;
603 argp[idx].type = ARGT_FE;
604 argp[idx+1].type = ARGT_STOP;
605 break;
606
607 case ARGT_BE:
608 if (!(p->cap & PR_CAP_BE))
609 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
610 argp[idx].data.prx = p;
611 argp[idx].type = ARGT_BE;
612 argp[idx+1].type = ARGT_STOP;
613 break;
614
615 case ARGT_TAB:
616 argp[idx].data.prx = p;
617 argp[idx].type = ARGT_TAB;
618 argp[idx+1].type = ARGT_STOP;
619 break;
620
621 default:
622 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
623 break;
624 }
625 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100626 return 0;
627 }
628
629 /* Check for exceed the number of requiered argument. */
630 if ((mask & ARGT_MASK) == ARGT_STOP &&
631 argp[idx].type != ARGT_STOP) {
632 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
633 }
634
635 if ((mask & ARGT_MASK) == ARGT_STOP &&
636 argp[idx].type == ARGT_STOP) {
637 return 0;
638 }
639
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100640 /* Convert some argument types. */
641 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100642 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100643 if (argp[idx].type != ARGT_SINT)
644 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
645 argp[idx].type = ARGT_SINT;
646 break;
647
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100648 case ARGT_TIME:
649 if (argp[idx].type != ARGT_SINT)
650 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200651 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100652 break;
653
654 case ARGT_SIZE:
655 if (argp[idx].type != ARGT_SINT)
656 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200657 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100658 break;
659
660 case ARGT_FE:
661 if (argp[idx].type != ARGT_STR)
662 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
663 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
664 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200665 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100666 if (!argp[idx].data.prx)
667 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
668 argp[idx].type = ARGT_FE;
669 break;
670
671 case ARGT_BE:
672 if (argp[idx].type != ARGT_STR)
673 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
674 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
675 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200676 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100677 if (!argp[idx].data.prx)
678 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
679 argp[idx].type = ARGT_BE;
680 break;
681
682 case ARGT_TAB:
683 if (argp[idx].type != ARGT_STR)
684 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
685 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
686 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200687 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100688 if (!argp[idx].data.prx)
689 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
690 argp[idx].type = ARGT_TAB;
691 break;
692
693 case ARGT_SRV:
694 if (argp[idx].type != ARGT_STR)
695 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
696 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
697 trash.str[argp[idx].data.str.len] = 0;
698 sname = strrchr(trash.str, '/');
699 if (sname) {
700 *sname++ = '\0';
701 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200702 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100703 if (!px)
704 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
705 }
706 else {
707 sname = trash.str;
708 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100709 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100710 argp[idx].data.srv = findserver(px, sname);
711 if (!argp[idx].data.srv)
712 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
713 argp[idx].type = ARGT_SRV;
714 break;
715
716 case ARGT_IPV4:
717 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
718 trash.str[argp[idx].data.str.len] = 0;
719 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
720 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
721 argp[idx].type = ARGT_IPV4;
722 break;
723
724 case ARGT_MSK4:
725 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
726 trash.str[argp[idx].data.str.len] = 0;
727 if (!str2mask(trash.str, &argp[idx].data.ipv4))
728 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
729 argp[idx].type = ARGT_MSK4;
730 break;
731
732 case ARGT_IPV6:
733 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
734 trash.str[argp[idx].data.str.len] = 0;
735 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
736 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
737 argp[idx].type = ARGT_IPV6;
738 break;
739
740 case ARGT_MSK6:
741 case ARGT_MAP:
742 case ARGT_REG:
743 case ARGT_USR:
744 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100745 break;
746 }
747
748 /* Check for type of argument. */
749 if ((mask & ARGT_MASK) != argp[idx].type) {
750 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
751 arg_type_names[(mask & ARGT_MASK)],
752 arg_type_names[argp[idx].type & ARGT_MASK]);
753 WILL_LJMP(luaL_argerror(L, first + idx, msg));
754 }
755
756 /* Next argument. */
757 mask >>= ARGT_BITS;
758 idx++;
759 }
760}
761
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100762/*
763 * The following functions are used to make correspondance between the the
764 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100765 *
766 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100767 * - hlua_sethlua : create the association between hlua context and lua_state.
768 */
769static inline struct hlua *hlua_gethlua(lua_State *L)
770{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100771 struct hlua **hlua = lua_getextraspace(L);
772 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100773}
774static inline void hlua_sethlua(struct hlua *hlua)
775{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100776 struct hlua **hlua_store = lua_getextraspace(hlua->T);
777 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100778}
779
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100780/* This function is used to send logs. It try to send on screen (stderr)
781 * and on the default syslog server.
782 */
783static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
784{
785 struct tm tm;
786 char *p;
787
788 /* Cleanup the log message. */
789 p = trash.str;
790 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200791 if (p >= trash.str + trash.size - 1) {
792 /* Break the message if exceed the buffer size. */
793 *(p-4) = ' ';
794 *(p-3) = '.';
795 *(p-2) = '.';
796 *(p-1) = '.';
797 break;
798 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100799 if (isprint(*msg))
800 *p = *msg;
801 else
802 *p = '.';
803 }
804 *p = '\0';
805
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200806 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100807 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200808 get_localtime(date.tv_sec, &tm);
809 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100810 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
811 (int)getpid(), trash.str);
812 fflush(stderr);
813 }
814}
815
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100816/* This function just ensure that the yield will be always
817 * returned with a timeout and permit to set some flags
818 */
819__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100820 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100821{
822 struct hlua *hlua = hlua_gethlua(L);
823
824 /* Set the wake timeout. If timeout is required, we set
825 * the expiration time.
826 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200827 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100828
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100829 hlua->flags |= flags;
830
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100831 /* Process the yield. */
832 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
833}
834
Willy Tarreau87b09662015-04-03 00:22:06 +0200835/* This function initialises the Lua environment stored in the stream.
836 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100837 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200838 *
839 * This function is particular. it initialises a new Lua thread. If the
840 * initialisation fails (example: out of memory error), the lua function
841 * throws an error (longjmp).
842 *
843 * This function manipulates two Lua stack: the main and the thread. Only
844 * the main stack can fail. The thread is not manipulated. This function
845 * MUST NOT manipulate the created thread stack state, because is not
846 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100847 */
848int hlua_ctx_init(struct hlua *lua, struct task *task)
849{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200850 if (!SET_SAFE_LJMP(gL.T)) {
851 lua->Tref = LUA_REFNIL;
852 return 0;
853 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100854 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100855 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100856 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100857 lua->T = lua_newthread(gL.T);
858 if (!lua->T) {
859 lua->Tref = LUA_REFNIL;
Thierry FOURNIER0a976202017-07-12 11:18:00 +0200860 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100861 return 0;
862 }
863 hlua_sethlua(lua);
864 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
865 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200866 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100867 return 1;
868}
869
Willy Tarreau87b09662015-04-03 00:22:06 +0200870/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100871 * is destroyed. The destroy also the memory context. The struct "lua"
872 * is not freed.
873 */
874void hlua_ctx_destroy(struct hlua *lua)
875{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100876 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100877 return;
878
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100879 if (!lua->T)
880 goto end;
881
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100882 /* Purge all the pending signals. */
Thierry FOURNIER847ca662016-12-16 13:07:22 +0100883 hlua_com_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100884
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200885 if (!SET_SAFE_LJMP(lua->T))
886 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100887 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200888 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200889
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200890 if (!SET_SAFE_LJMP(gL.T))
891 return;
892 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
893 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200894 /* Forces a garbage collecting process. If the Lua program is finished
895 * without error, we run the GC on the thread pointer. Its freed all
896 * the unused memory.
897 * If the thread is finnish with an error or is currently yielded,
898 * it seems that the GC applied on the thread doesn't clean anything,
899 * so e run the GC on the main thread.
900 * NOTE: maybe this action locks all the Lua threads untiml the en of
901 * the garbage collection.
902 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200903 if (lua->flags & HLUA_MUST_GC) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200904 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200905 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200906 lua_gc(gL.T, LUA_GCCOLLECT, 0);
907 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200908 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200909
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200910 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100911
912end:
913 pool_free2(pool2_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100914}
915
916/* This function is used to restore the Lua context when a coroutine
917 * fails. This function copy the common memory between old coroutine
918 * and the new coroutine. The old coroutine is destroyed, and its
919 * replaced by the new coroutine.
920 * If the flag "keep_msg" is set, the last entry of the old is assumed
921 * as string error message and it is copied in the new stack.
922 */
923static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
924{
925 lua_State *T;
926 int new_ref;
927
928 /* Renew the main LUA stack doesn't have sense. */
929 if (lua == &gL)
930 return 0;
931
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100932 /* New Lua coroutine. */
933 T = lua_newthread(gL.T);
934 if (!T)
935 return 0;
936
937 /* Copy last error message. */
938 if (keep_msg)
939 lua_xmove(lua->T, T, 1);
940
941 /* Copy data between the coroutines. */
942 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
943 lua_xmove(lua->T, T, 1);
944 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
945
946 /* Destroy old data. */
947 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
948
949 /* The thread is garbage collected by Lua. */
950 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
951
952 /* Fill the struct with the new coroutine values. */
953 lua->Mref = new_ref;
954 lua->T = T;
955 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
956
957 /* Set context. */
958 hlua_sethlua(lua);
959
960 return 1;
961}
962
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100963void hlua_hook(lua_State *L, lua_Debug *ar)
964{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100965 struct hlua *hlua = hlua_gethlua(L);
966
967 /* Lua cannot yield when its returning from a function,
968 * so, we can fix the interrupt hook to 1 instruction,
969 * expecting that the function is finnished.
970 */
971 if (lua_gethookmask(L) & LUA_MASKRET) {
972 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
973 return;
974 }
975
976 /* restore the interrupt condition. */
977 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
978
979 /* If we interrupt the Lua processing in yieldable state, we yield.
980 * If the state is not yieldable, trying yield causes an error.
981 */
982 if (lua_isyieldable(L))
983 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
984
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100985 /* If we cannot yield, update the clock and check the timeout. */
986 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200987 hlua->run_time += now_ms - hlua->start_time;
988 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100989 lua_pushfstring(L, "execution timeout");
990 WILL_LJMP(lua_error(L));
991 }
992
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200993 /* Update the start time. */
994 hlua->start_time = now_ms;
995
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100996 /* Try to interrupt the process at the end of the current
997 * unyieldable function.
998 */
999 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001000}
1001
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001002/* This function start or resumes the Lua stack execution. If the flag
1003 * "yield_allowed" if no set and the LUA stack execution returns a yield
1004 * The function return an error.
1005 *
1006 * The function can returns 4 values:
1007 * - HLUA_E_OK : The execution is terminated without any errors.
1008 * - HLUA_E_AGAIN : The execution must continue at the next associated
1009 * task wakeup.
1010 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
1011 * the top of the stack.
1012 * - HLUA_E_ERR : An error has occured without error message.
1013 *
1014 * If an error occured, the stack is renewed and it is ready to run new
1015 * LUA code.
1016 */
1017static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1018{
1019 int ret;
1020 const char *msg;
1021
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001022 /* Initialise run time counter. */
1023 if (!HLUA_IS_RUNNING(lua))
1024 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001025
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001026resume_execution:
1027
1028 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1029 * instructions. it is used for preventing infinite loops.
1030 */
1031 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1032
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001033 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001034 HLUA_SET_RUN(lua);
1035 HLUA_CLR_CTRLYIELD(lua);
1036 HLUA_CLR_WAKERESWR(lua);
1037 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001038
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001039 /* Update the start time. */
1040 lua->start_time = now_ms;
1041
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001042 /* Call the function. */
1043 ret = lua_resume(lua->T, gL.T, lua->nargs);
1044 switch (ret) {
1045
1046 case LUA_OK:
1047 ret = HLUA_E_OK;
1048 break;
1049
1050 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001051 /* Check if the execution timeout is expired. It it is the case, we
1052 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001053 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001054 tv_update_date(0, 1);
1055 lua->run_time += now_ms - lua->start_time;
1056 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001057 lua_settop(lua->T, 0); /* Empty the stack. */
1058 if (!lua_checkstack(lua->T, 1)) {
1059 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001060 break;
1061 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001062 lua_pushfstring(lua->T, "execution timeout");
1063 ret = HLUA_E_ERRMSG;
1064 break;
1065 }
1066 /* Process the forced yield. if the general yield is not allowed or
1067 * if no task were associated this the current Lua execution
1068 * coroutine, we resume the execution. Else we want to return in the
1069 * scheduler and we want to be waked up again, to continue the
1070 * current Lua execution. So we schedule our own task.
1071 */
1072 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001073 if (!yield_allowed || !lua->task)
1074 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001075 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001076 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001077 if (!yield_allowed) {
1078 lua_settop(lua->T, 0); /* Empty the stack. */
1079 if (!lua_checkstack(lua->T, 1)) {
1080 ret = HLUA_E_ERR;
1081 break;
1082 }
1083 lua_pushfstring(lua->T, "yield not allowed");
1084 ret = HLUA_E_ERRMSG;
1085 break;
1086 }
1087 ret = HLUA_E_AGAIN;
1088 break;
1089
1090 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001091
1092 /* Special exit case. The traditionnal exit is returned as an error
1093 * because the errors ares the only one mean to return immediately
1094 * from and lua execution.
1095 */
1096 if (lua->flags & HLUA_EXIT) {
1097 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001098 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001099 break;
1100 }
1101
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001102 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001103 if (!lua_checkstack(lua->T, 1)) {
1104 ret = HLUA_E_ERR;
1105 break;
1106 }
1107 msg = lua_tostring(lua->T, -1);
1108 lua_settop(lua->T, 0); /* Empty the stack. */
1109 lua_pop(lua->T, 1);
1110 if (msg)
1111 lua_pushfstring(lua->T, "runtime error: %s", msg);
1112 else
1113 lua_pushfstring(lua->T, "unknown runtime error");
1114 ret = HLUA_E_ERRMSG;
1115 break;
1116
1117 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001118 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001119 lua_settop(lua->T, 0); /* Empty the stack. */
1120 if (!lua_checkstack(lua->T, 1)) {
1121 ret = HLUA_E_ERR;
1122 break;
1123 }
1124 lua_pushfstring(lua->T, "out of memory error");
1125 ret = HLUA_E_ERRMSG;
1126 break;
1127
1128 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001129 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001130 if (!lua_checkstack(lua->T, 1)) {
1131 ret = HLUA_E_ERR;
1132 break;
1133 }
1134 msg = lua_tostring(lua->T, -1);
1135 lua_settop(lua->T, 0); /* Empty the stack. */
1136 lua_pop(lua->T, 1);
1137 if (msg)
1138 lua_pushfstring(lua->T, "message handler error: %s", msg);
1139 else
1140 lua_pushfstring(lua->T, "message handler error");
1141 ret = HLUA_E_ERRMSG;
1142 break;
1143
1144 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001145 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001146 lua_settop(lua->T, 0); /* Empty the stack. */
1147 if (!lua_checkstack(lua->T, 1)) {
1148 ret = HLUA_E_ERR;
1149 break;
1150 }
1151 lua_pushfstring(lua->T, "unknonwn error");
1152 ret = HLUA_E_ERRMSG;
1153 break;
1154 }
1155
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001156 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001157 if (lua->flags & HLUA_MUST_GC &&
1158 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001159 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1160
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001161 switch (ret) {
1162 case HLUA_E_AGAIN:
1163 break;
1164
1165 case HLUA_E_ERRMSG:
Thierry FOURNIER847ca662016-12-16 13:07:22 +01001166 hlua_com_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001167 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001168 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001169 break;
1170
1171 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001172 HLUA_CLR_RUN(lua);
Thierry FOURNIER847ca662016-12-16 13:07:22 +01001173 hlua_com_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001174 hlua_ctx_renew(lua, 0);
1175 break;
1176
1177 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001178 HLUA_CLR_RUN(lua);
Thierry FOURNIER847ca662016-12-16 13:07:22 +01001179 hlua_com_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001180 break;
1181 }
1182
1183 return ret;
1184}
1185
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001186/* This function exit the current code. */
1187__LJMP static int hlua_done(lua_State *L)
1188{
1189 struct hlua *hlua = hlua_gethlua(L);
1190
1191 hlua->flags |= HLUA_EXIT;
1192 WILL_LJMP(lua_error(L));
1193
1194 return 0;
1195}
1196
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001197/* This function is an LUA binding. It provides a function
1198 * for deleting ACL from a referenced ACL file.
1199 */
1200__LJMP static int hlua_del_acl(lua_State *L)
1201{
1202 const char *name;
1203 const char *key;
1204 struct pat_ref *ref;
1205
1206 MAY_LJMP(check_args(L, 2, "del_acl"));
1207
1208 name = MAY_LJMP(luaL_checkstring(L, 1));
1209 key = MAY_LJMP(luaL_checkstring(L, 2));
1210
1211 ref = pat_ref_lookup(name);
1212 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001213 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001214
1215 pat_ref_delete(ref, key);
1216 return 0;
1217}
1218
1219/* This function is an LUA binding. It provides a function
1220 * for deleting map entry from a referenced map file.
1221 */
1222static int hlua_del_map(lua_State *L)
1223{
1224 const char *name;
1225 const char *key;
1226 struct pat_ref *ref;
1227
1228 MAY_LJMP(check_args(L, 2, "del_map"));
1229
1230 name = MAY_LJMP(luaL_checkstring(L, 1));
1231 key = MAY_LJMP(luaL_checkstring(L, 2));
1232
1233 ref = pat_ref_lookup(name);
1234 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001235 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001236
1237 pat_ref_delete(ref, key);
1238 return 0;
1239}
1240
1241/* This function is an LUA binding. It provides a function
1242 * for adding ACL pattern from a referenced ACL file.
1243 */
1244static int hlua_add_acl(lua_State *L)
1245{
1246 const char *name;
1247 const char *key;
1248 struct pat_ref *ref;
1249
1250 MAY_LJMP(check_args(L, 2, "add_acl"));
1251
1252 name = MAY_LJMP(luaL_checkstring(L, 1));
1253 key = MAY_LJMP(luaL_checkstring(L, 2));
1254
1255 ref = pat_ref_lookup(name);
1256 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001257 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001258
1259 if (pat_ref_find_elt(ref, key) == NULL)
1260 pat_ref_add(ref, key, NULL, NULL);
1261 return 0;
1262}
1263
1264/* This function is an LUA binding. It provides a function
1265 * for setting map pattern and sample from a referenced map
1266 * file.
1267 */
1268static int hlua_set_map(lua_State *L)
1269{
1270 const char *name;
1271 const char *key;
1272 const char *value;
1273 struct pat_ref *ref;
1274
1275 MAY_LJMP(check_args(L, 3, "set_map"));
1276
1277 name = MAY_LJMP(luaL_checkstring(L, 1));
1278 key = MAY_LJMP(luaL_checkstring(L, 2));
1279 value = MAY_LJMP(luaL_checkstring(L, 3));
1280
1281 ref = pat_ref_lookup(name);
1282 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001283 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001284
1285 if (pat_ref_find_elt(ref, key) != NULL)
1286 pat_ref_set(ref, key, value, NULL);
1287 else
1288 pat_ref_add(ref, key, value, NULL);
1289 return 0;
1290}
1291
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001292/* A class is a lot of memory that contain data. This data can be a table,
1293 * an integer or user data. This data is associated with a metatable. This
1294 * metatable have an original version registred in the global context with
1295 * the name of the object (_G[<name>] = <metable> ).
1296 *
1297 * A metable is a table that modify the standard behavior of a standard
1298 * access to the associated data. The entries of this new metatable are
1299 * defined as is:
1300 *
1301 * http://lua-users.org/wiki/MetatableEvents
1302 *
1303 * __index
1304 *
1305 * we access an absent field in a table, the result is nil. This is
1306 * true, but it is not the whole truth. Actually, such access triggers
1307 * the interpreter to look for an __index metamethod: If there is no
1308 * such method, as usually happens, then the access results in nil;
1309 * otherwise, the metamethod will provide the result.
1310 *
1311 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1312 * the key does not appear in the table, but the metatable has an __index
1313 * property:
1314 *
1315 * - if the value is a function, the function is called, passing in the
1316 * table and the key; the return value of that function is returned as
1317 * the result.
1318 *
1319 * - if the value is another table, the value of the key in that table is
1320 * asked for and returned (and if it doesn't exist in that table, but that
1321 * table's metatable has an __index property, then it continues on up)
1322 *
1323 * - Use "rawget(myTable,key)" to skip this metamethod.
1324 *
1325 * http://www.lua.org/pil/13.4.1.html
1326 *
1327 * __newindex
1328 *
1329 * Like __index, but control property assignment.
1330 *
1331 * __mode - Control weak references. A string value with one or both
1332 * of the characters 'k' and 'v' which specifies that the the
1333 * keys and/or values in the table are weak references.
1334 *
1335 * __call - Treat a table like a function. When a table is followed by
1336 * parenthesis such as "myTable( 'foo' )" and the metatable has
1337 * a __call key pointing to a function, that function is invoked
1338 * (passing any specified arguments) and the return value is
1339 * returned.
1340 *
1341 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1342 * called, if the metatable for myTable has a __metatable
1343 * key, the value of that key is returned instead of the
1344 * actual metatable.
1345 *
1346 * __tostring - Control string representation. When the builtin
1347 * "tostring( myTable )" function is called, if the metatable
1348 * for myTable has a __tostring property set to a function,
1349 * that function is invoked (passing myTable to it) and the
1350 * return value is used as the string representation.
1351 *
1352 * __len - Control table length. When the table length is requested using
1353 * the length operator ( '#' ), if the metatable for myTable has
1354 * a __len key pointing to a function, that function is invoked
1355 * (passing myTable to it) and the return value used as the value
1356 * of "#myTable".
1357 *
1358 * __gc - Userdata finalizer code. When userdata is set to be garbage
1359 * collected, if the metatable has a __gc field pointing to a
1360 * function, that function is first invoked, passing the userdata
1361 * to it. The __gc metamethod is not called for tables.
1362 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1363 *
1364 * Special metamethods for redefining standard operators:
1365 * http://www.lua.org/pil/13.1.html
1366 *
1367 * __add "+"
1368 * __sub "-"
1369 * __mul "*"
1370 * __div "/"
1371 * __unm "!"
1372 * __pow "^"
1373 * __concat ".."
1374 *
1375 * Special methods for redfining standar relations
1376 * http://www.lua.org/pil/13.2.html
1377 *
1378 * __eq "=="
1379 * __lt "<"
1380 * __le "<="
1381 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001382
1383/*
1384 *
1385 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001386 * Class Map
1387 *
1388 *
1389 */
1390
1391/* Returns a struct hlua_map if the stack entry "ud" is
1392 * a class session, otherwise it throws an error.
1393 */
1394__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1395{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001396 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001397}
1398
1399/* This function is the map constructor. It don't need
1400 * the class Map object. It creates and return a new Map
1401 * object. It must be called only during "body" or "init"
1402 * context because it process some filesystem accesses.
1403 */
1404__LJMP static int hlua_map_new(struct lua_State *L)
1405{
1406 const char *fn;
1407 int match = PAT_MATCH_STR;
1408 struct sample_conv conv;
1409 const char *file = "";
1410 int line = 0;
1411 lua_Debug ar;
1412 char *err = NULL;
1413 struct arg args[2];
1414
1415 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1416 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1417
1418 fn = MAY_LJMP(luaL_checkstring(L, 1));
1419
1420 if (lua_gettop(L) >= 2) {
1421 match = MAY_LJMP(luaL_checkinteger(L, 2));
1422 if (match < 0 || match >= PAT_MATCH_NUM)
1423 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1424 }
1425
1426 /* Get Lua filename and line number. */
1427 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1428 lua_getinfo(L, "Sl", &ar); /* get info about it */
1429 if (ar.currentline > 0) { /* is there info? */
1430 file = ar.short_src;
1431 line = ar.currentline;
1432 }
1433 }
1434
1435 /* fill fake sample_conv struct. */
1436 conv.kw = ""; /* unused. */
1437 conv.process = NULL; /* unused. */
1438 conv.arg_mask = 0; /* unused. */
1439 conv.val_args = NULL; /* unused. */
1440 conv.out_type = SMP_T_STR;
1441 conv.private = (void *)(long)match;
1442 switch (match) {
1443 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1444 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1445 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1446 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1447 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1448 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1449 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001450 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001451 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1452 default:
1453 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1454 }
1455
1456 /* fill fake args. */
1457 args[0].type = ARGT_STR;
1458 args[0].data.str.str = (char *)fn;
1459 args[1].type = ARGT_STOP;
1460
1461 /* load the map. */
1462 if (!sample_load_map(args, &conv, file, line, &err)) {
1463 /* error case: we cant use luaL_error because we must
1464 * free the err variable.
1465 */
1466 luaL_where(L, 1);
1467 lua_pushfstring(L, "'new': %s.", err);
1468 lua_concat(L, 2);
1469 free(err);
1470 WILL_LJMP(lua_error(L));
1471 }
1472
1473 /* create the lua object. */
1474 lua_newtable(L);
1475 lua_pushlightuserdata(L, args[0].data.map);
1476 lua_rawseti(L, -2, 0);
1477
1478 /* Pop a class Map metatable and affect it to the userdata. */
1479 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1480 lua_setmetatable(L, -2);
1481
1482
1483 return 1;
1484}
1485
1486__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1487{
1488 struct map_descriptor *desc;
1489 struct pattern *pat;
1490 struct sample smp;
1491
1492 MAY_LJMP(check_args(L, 2, "lookup"));
1493 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001494 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001495 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001496 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001497 }
1498 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001499 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001500 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001501 smp.data.u.str.str = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.len));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001502 }
1503
1504 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001505 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001506 if (str)
1507 lua_pushstring(L, "");
1508 else
1509 lua_pushnil(L);
1510 return 1;
1511 }
1512
1513 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001514 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001515 return 1;
1516}
1517
1518__LJMP static int hlua_map_lookup(struct lua_State *L)
1519{
1520 return _hlua_map_lookup(L, 0);
1521}
1522
1523__LJMP static int hlua_map_slookup(struct lua_State *L)
1524{
1525 return _hlua_map_lookup(L, 1);
1526}
1527
1528/*
1529 *
1530 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001531 * Class Socket
1532 *
1533 *
1534 */
1535
1536__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1537{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001538 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001539}
1540
1541/* This function is the handler called for each I/O on the established
1542 * connection. It is used for notify space avalaible to send or data
1543 * received.
1544 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001545static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001546{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001547 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001548 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001549
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001550 if (appctx->ctx.hlua_cosocket.die) {
1551 si_shutw(si);
1552 si_shutr(si);
1553 si_ic(si)->flags |= CF_READ_NULL;
1554 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1555 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
1556 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1557 }
1558
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001559 /* If the connection object is not avalaible, close all the
1560 * streams and wakeup everithing waiting for.
1561 */
1562 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001563 si_shutw(si);
1564 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001565 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001566 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1567 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001568 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001569 }
1570
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001571 /* If we cant write, wakeup the pending write signals. */
1572 if (channel_output_closed(si_ic(si)))
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001573 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001574
1575 /* If we cant read, wakeup the pending read signals. */
1576 if (channel_input_closed(si_oc(si)))
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001577 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001578
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001579 /* if the connection is not estabkished, inform the stream that we want
1580 * to be notified whenever the connection completes.
1581 */
1582 if (!(c->flags & CO_FL_CONNECTED)) {
1583 si_applet_cant_get(si);
1584 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001585 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001586 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001587
1588 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001589 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001590
1591 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001592 if (channel_may_recv(si_ic(si)))
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001593 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001594
1595 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001596 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001597 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001598}
1599
Willy Tarreau87b09662015-04-03 00:22:06 +02001600/* This function is called when the "struct stream" is destroyed.
1601 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001602 * Wake all the pending signals.
1603 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001604static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001605{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001606 /* Remove my link in the original object. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001607 if (appctx->ctx.hlua_cosocket.socket)
1608 appctx->ctx.hlua_cosocket.socket->s = NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001609
1610 /* Wake all the task waiting for me. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001611 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1612 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001613}
1614
1615/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001616 * uses this object. If the stream does not exists, just quit.
1617 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001618 * pending signal can rest in the read and write lists. destroy
1619 * it.
1620 */
1621__LJMP static int hlua_socket_gc(lua_State *L)
1622{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001623 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001624 struct appctx *appctx;
1625
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001626 MAY_LJMP(check_args(L, 1, "__gc"));
1627
1628 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001629 if (!socket->s)
1630 return 0;
1631
Willy Tarreau87b09662015-04-03 00:22:06 +02001632 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001633 appctx = objt_appctx(socket->s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001634 socket->s = NULL;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001635 appctx->ctx.hlua_cosocket.socket = NULL;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001636 appctx->ctx.hlua_cosocket.die = 1;
1637 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001638
1639 return 0;
1640}
1641
1642/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001643 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001644 */
1645__LJMP static int hlua_socket_close(lua_State *L)
1646{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001647 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001648 struct appctx *appctx;
1649
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001650 MAY_LJMP(check_args(L, 1, "close"));
1651
1652 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001653 if (!socket->s)
1654 return 0;
1655
Willy Tarreau87b09662015-04-03 00:22:06 +02001656 /* Close the stream and remove the associated stop task. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001657 appctx = objt_appctx(socket->s->si[0].end);
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001658 appctx->ctx.hlua_cosocket.socket = NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001659 socket->s = NULL;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001660 appctx->ctx.hlua_cosocket.die = 1;
1661 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001662
1663 return 0;
1664}
1665
1666/* This Lua function assumes that the stack contain three parameters.
1667 * 1 - USERDATA containing a struct socket
1668 * 2 - INTEGER with values of the macro defined below
1669 * If the integer is -1, we must read at most one line.
1670 * If the integer is -2, we ust read all the data until the
1671 * end of the stream.
1672 * If the integer is positive value, we must read a number of
1673 * bytes corresponding to this value.
1674 */
1675#define HLSR_READ_LINE (-1)
1676#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001677__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001678{
1679 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1680 int wanted = lua_tointeger(L, 2);
1681 struct hlua *hlua = hlua_gethlua(L);
1682 struct appctx *appctx;
1683 int len;
1684 int nblk;
1685 char *blk1;
1686 int len1;
1687 char *blk2;
1688 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001689 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001690 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001691
1692 /* Check if this lua stack is schedulable. */
1693 if (!hlua || !hlua->task)
1694 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1695 "'frontend', 'backend' or 'task'"));
1696
1697 /* check for connection closed. If some data where read, return it. */
1698 if (!socket->s)
1699 goto connection_closed;
1700
Willy Tarreau94aa6172015-03-13 14:19:06 +01001701 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001702 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001703 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001704 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001705 if (nblk < 0) /* Connection close. */
1706 goto connection_closed;
1707 if (nblk == 0) /* No data avalaible. */
1708 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001709
1710 /* remove final \r\n. */
1711 if (nblk == 1) {
1712 if (blk1[len1-1] == '\n') {
1713 len1--;
1714 skip_at_end++;
1715 if (blk1[len1-1] == '\r') {
1716 len1--;
1717 skip_at_end++;
1718 }
1719 }
1720 }
1721 else {
1722 if (blk2[len2-1] == '\n') {
1723 len2--;
1724 skip_at_end++;
1725 if (blk2[len2-1] == '\r') {
1726 len2--;
1727 skip_at_end++;
1728 }
1729 }
1730 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001731 }
1732
1733 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001734 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001735 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001736 if (nblk < 0) /* Connection close. */
1737 goto connection_closed;
1738 if (nblk == 0) /* No data avalaible. */
1739 goto connection_empty;
1740 }
1741
1742 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001743 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001744 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001745 if (nblk < 0) /* Connection close. */
1746 goto connection_closed;
1747 if (nblk == 0) /* No data avalaible. */
1748 goto connection_empty;
1749
1750 if (len1 > wanted) {
1751 nblk = 1;
1752 len1 = wanted;
1753 } if (nblk == 2 && len1 + len2 > wanted)
1754 len2 = wanted - len1;
1755 }
1756
1757 len = len1;
1758
1759 luaL_addlstring(&socket->b, blk1, len1);
1760 if (nblk == 2) {
1761 len += len2;
1762 luaL_addlstring(&socket->b, blk2, len2);
1763 }
1764
1765 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001766 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001767
1768 /* Don't wait anything. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001769 stream_int_notify(&socket->s->si[0]);
1770 stream_int_update_applet(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001771
1772 /* If the pattern reclaim to read all the data
1773 * in the connection, got out.
1774 */
1775 if (wanted == HLSR_READ_ALL)
1776 goto connection_empty;
1777 else if (wanted >= 0 && len < wanted)
1778 goto connection_empty;
1779
1780 /* Return result. */
1781 luaL_pushresult(&socket->b);
1782 return 1;
1783
1784connection_closed:
1785
1786 /* If the buffer containds data. */
1787 if (socket->b.n > 0) {
1788 luaL_pushresult(&socket->b);
1789 return 1;
1790 }
1791 lua_pushnil(L);
1792 lua_pushstring(L, "connection closed.");
1793 return 2;
1794
1795connection_empty:
1796
1797 appctx = objt_appctx(socket->s->si[0].end);
Thierry FOURNIER847ca662016-12-16 13:07:22 +01001798 if (!hlua_com_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001799 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001800 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001801 return 0;
1802}
1803
1804/* This Lus function gets two parameters. The first one can be string
1805 * or a number. If the string is "*l", the user require one line. If
1806 * the string is "*a", the user require all the content of the stream.
1807 * If the value is a number, the user require a number of bytes equal
1808 * to the value. The default value is "*l" (a line).
1809 *
1810 * This paraeter with a variable type is converted in integer. This
1811 * integer takes this values:
1812 * -1 : read a line
1813 * -2 : read all the stream
1814 * >0 : amount if bytes.
1815 *
1816 * The second parameter is optinal. It contains a string that must be
1817 * concatenated with the read data.
1818 */
1819__LJMP static int hlua_socket_receive(struct lua_State *L)
1820{
1821 int wanted = HLSR_READ_LINE;
1822 const char *pattern;
1823 int type;
1824 char *error;
1825 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001826 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001827
1828 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1829 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1830
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001831 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001832
1833 /* check for pattern. */
1834 if (lua_gettop(L) >= 2) {
1835 type = lua_type(L, 2);
1836 if (type == LUA_TSTRING) {
1837 pattern = lua_tostring(L, 2);
1838 if (strcmp(pattern, "*a") == 0)
1839 wanted = HLSR_READ_ALL;
1840 else if (strcmp(pattern, "*l") == 0)
1841 wanted = HLSR_READ_LINE;
1842 else {
1843 wanted = strtoll(pattern, &error, 10);
1844 if (*error != '\0')
1845 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1846 }
1847 }
1848 else if (type == LUA_TNUMBER) {
1849 wanted = lua_tointeger(L, 2);
1850 if (wanted < 0)
1851 WILL_LJMP(luaL_error(L, "Unsupported size."));
1852 }
1853 }
1854
1855 /* Set pattern. */
1856 lua_pushinteger(L, wanted);
1857 lua_replace(L, 2);
1858
1859 /* init bufffer, and fiil it wih prefix. */
1860 luaL_buffinit(L, &socket->b);
1861
1862 /* Check prefix. */
1863 if (lua_gettop(L) >= 3) {
1864 if (lua_type(L, 3) != LUA_TSTRING)
1865 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1866 pattern = lua_tolstring(L, 3, &len);
1867 luaL_addlstring(&socket->b, pattern, len);
1868 }
1869
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001870 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001871}
1872
1873/* Write the Lua input string in the output buffer.
1874 * This fucntion returns a yield if no space are available.
1875 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001876static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001877{
1878 struct hlua_socket *socket;
1879 struct hlua *hlua = hlua_gethlua(L);
1880 struct appctx *appctx;
1881 size_t buf_len;
1882 const char *buf;
1883 int len;
1884 int send_len;
1885 int sent;
1886
1887 /* Check if this lua stack is schedulable. */
1888 if (!hlua || !hlua->task)
1889 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1890 "'frontend', 'backend' or 'task'"));
1891
1892 /* Get object */
1893 socket = MAY_LJMP(hlua_checksocket(L, 1));
1894 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001895 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001896
1897 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001898 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001899 lua_pushinteger(L, -1);
1900 return 1;
1901 }
1902
1903 /* Update the input buffer data. */
1904 buf += sent;
1905 send_len = buf_len - sent;
1906
1907 /* All the data are sent. */
1908 if (sent >= buf_len)
1909 return 1; /* Implicitly return the length sent. */
1910
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001911 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1912 * the request buffer if its not required.
1913 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001914 if (socket->s->req.buf->size == 0) {
Christopher Faulet33834b12016-12-19 09:29:06 +01001915 appctx = hlua->task->context;
1916 if (!channel_alloc_buffer(&socket->s->req, &appctx->buffer_wait))
1917 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001918 }
1919
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001920 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001921 len = buffer_total_space(socket->s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01001922 if (len <= 0) {
1923 appctx = objt_appctx(socket->s->si[0].end);
1924 if (!hlua_com_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task))
1925 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001926 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01001927 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001928
1929 /* send data */
1930 if (len < send_len)
1931 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001932 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001933
1934 /* "Not enough space" (-1), "Buffer too little to contain
1935 * the data" (-2) are not expected because the available length
1936 * is tested.
1937 * Other unknown error are also not expected.
1938 */
1939 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001940 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001941 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001942
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001943 MAY_LJMP(hlua_socket_close(L));
1944 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001945 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001946 return 1;
1947 }
1948
1949 /* update buffers. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001950 stream_int_notify(&socket->s->si[0]);
1951 stream_int_update_applet(&socket->s->si[0]);
1952
Willy Tarreau94aa6172015-03-13 14:19:06 +01001953 socket->s->req.rex = TICK_ETERNITY;
1954 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001955
1956 /* Update length sent. */
1957 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001958 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001959
1960 /* All the data buffer is sent ? */
1961 if (sent + len >= buf_len)
1962 return 1;
1963
1964hlua_socket_write_yield_return:
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001965 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001966 return 0;
1967}
1968
1969/* This function initiate the send of data. It just check the input
1970 * parameters and push an integer in the Lua stack that contain the
1971 * amount of data writed in the buffer. This is used by the function
1972 * "hlua_socket_write_yield" that can yield.
1973 *
1974 * The Lua function gets between 3 and 4 parameters. The first one is
1975 * the associated object. The second is a string buffer. The third is
1976 * a facultative integer that represents where is the buffer position
1977 * of the start of the data that can send. The first byte is the
1978 * position "1". The default value is "1". The fourth argument is a
1979 * facultative integer that represents where is the buffer position
1980 * of the end of the data that can send. The default is the last byte.
1981 */
1982static int hlua_socket_send(struct lua_State *L)
1983{
1984 int i;
1985 int j;
1986 const char *buf;
1987 size_t buf_len;
1988
1989 /* Check number of arguments. */
1990 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1991 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1992
1993 /* Get the string. */
1994 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1995
1996 /* Get and check j. */
1997 if (lua_gettop(L) == 4) {
1998 j = MAY_LJMP(luaL_checkinteger(L, 4));
1999 if (j < 0)
2000 j = buf_len + j + 1;
2001 if (j > buf_len)
2002 j = buf_len + 1;
2003 lua_pop(L, 1);
2004 }
2005 else
2006 j = buf_len;
2007
2008 /* Get and check i. */
2009 if (lua_gettop(L) == 3) {
2010 i = MAY_LJMP(luaL_checkinteger(L, 3));
2011 if (i < 0)
2012 i = buf_len + i + 1;
2013 if (i > buf_len)
2014 i = buf_len + 1;
2015 lua_pop(L, 1);
2016 } else
2017 i = 1;
2018
2019 /* Check bth i and j. */
2020 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002021 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002022 return 1;
2023 }
2024 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002025 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002026 return 1;
2027 }
2028 if (i == 0)
2029 i = 1;
2030 if (j == 0)
2031 j = 1;
2032
2033 /* Pop the string. */
2034 lua_pop(L, 1);
2035
2036 /* Update the buffer length. */
2037 buf += i - 1;
2038 buf_len = j - i + 1;
2039 lua_pushlstring(L, buf, buf_len);
2040
2041 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002042 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002043
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002044 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002045}
2046
Willy Tarreau22b0a682015-06-17 19:43:49 +02002047#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002048__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2049{
2050 static char buffer[SOCKET_INFO_MAX_LEN];
2051 int ret;
2052 int len;
2053 char *p;
2054
2055 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2056 if (ret <= 0) {
2057 lua_pushnil(L);
2058 return 1;
2059 }
2060
2061 if (ret == AF_UNIX) {
2062 lua_pushstring(L, buffer+1);
2063 return 1;
2064 }
2065 else if (ret == AF_INET6) {
2066 buffer[0] = '[';
2067 len = strlen(buffer);
2068 buffer[len] = ']';
2069 len++;
2070 buffer[len] = ':';
2071 len++;
2072 p = buffer;
2073 }
2074 else if (ret == AF_INET) {
2075 p = buffer + 1;
2076 len = strlen(p);
2077 p[len] = ':';
2078 len++;
2079 }
2080 else {
2081 lua_pushnil(L);
2082 return 1;
2083 }
2084
2085 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2086 lua_pushnil(L);
2087 return 1;
2088 }
2089
2090 lua_pushstring(L, p);
2091 return 1;
2092}
2093
2094/* Returns information about the peer of the connection. */
2095__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2096{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002097 struct hlua_socket *socket;
2098 struct connection *conn;
2099
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002100 MAY_LJMP(check_args(L, 1, "getpeername"));
2101
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002102 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002103
2104 /* Check if the tcp object is avalaible. */
2105 if (!socket->s) {
2106 lua_pushnil(L);
2107 return 1;
2108 }
2109
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002110 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002111 if (!conn) {
2112 lua_pushnil(L);
2113 return 1;
2114 }
2115
Willy Tarreaua71f6422016-11-16 17:00:14 +01002116 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002117 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Willy Tarreaua71f6422016-11-16 17:00:14 +01002118 lua_pushnil(L);
2119 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002120 }
2121
2122 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2123}
2124
2125/* Returns information about my connection side. */
2126static int hlua_socket_getsockname(struct lua_State *L)
2127{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002128 struct hlua_socket *socket;
2129 struct connection *conn;
2130
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002131 MAY_LJMP(check_args(L, 1, "getsockname"));
2132
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002133 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002134
2135 /* Check if the tcp object is avalaible. */
2136 if (!socket->s) {
2137 lua_pushnil(L);
2138 return 1;
2139 }
2140
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002141 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002142 if (!conn) {
2143 lua_pushnil(L);
2144 return 1;
2145 }
2146
Willy Tarreaua71f6422016-11-16 17:00:14 +01002147 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002148 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Willy Tarreaua71f6422016-11-16 17:00:14 +01002149 lua_pushnil(L);
2150 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002151 }
2152
2153 return hlua_socket_info(L, &conn->addr.from);
2154}
2155
2156/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002157static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002158 .obj_type = OBJ_TYPE_APPLET,
2159 .name = "<LUA_TCP>",
2160 .fct = hlua_socket_handler,
2161 .release = hlua_socket_release,
2162};
2163
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002164__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002165{
2166 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2167 struct hlua *hlua = hlua_gethlua(L);
2168 struct appctx *appctx;
2169
2170 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002171 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002172 lua_pushnil(L);
2173 lua_pushstring(L, "Can't connect");
2174 return 2;
2175 }
2176
2177 appctx = objt_appctx(socket->s->si[0].end);
2178
2179 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002180 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002181 lua_pushinteger(L, 1);
2182 return 1;
2183 }
2184
Thierry FOURNIER847ca662016-12-16 13:07:22 +01002185 if (!hlua_com_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002187 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002188 return 0;
2189}
2190
2191/* This function fail or initite the connection. */
2192__LJMP static int hlua_socket_connect(struct lua_State *L)
2193{
2194 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002195 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002196 const char *ip;
2197 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002198 struct hlua *hlua;
2199 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002200 int low, high;
2201 struct sockaddr_storage *addr;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002202
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002203 if (lua_gettop(L) < 2)
2204 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002205
2206 /* Get args. */
2207 socket = MAY_LJMP(hlua_checksocket(L, 1));
2208 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002209 if (lua_gettop(L) >= 3)
2210 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002211
Willy Tarreau973a5422015-08-05 21:47:23 +02002212 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002213 if (!conn)
2214 WILL_LJMP(luaL_error(L, "connect: internal error"));
2215
Willy Tarreau3adac082015-09-26 17:51:09 +02002216 /* needed for the connection not to be closed */
2217 conn->target = socket->s->target;
2218
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002219 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002220 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002221 if (!addr)
2222 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
2223 if (low != high)
2224 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
2225 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226
2227 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002228 if (low == 0) {
2229 if (conn->addr.to.ss_family == AF_INET) {
2230 if (port == -1)
2231 WILL_LJMP(luaL_error(L, "connect: port missing"));
2232 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2233 } else if (conn->addr.to.ss_family == AF_INET6) {
2234 if (port == -1)
2235 WILL_LJMP(luaL_error(L, "connect: port missing"));
2236 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2237 }
2238 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002239
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002240 hlua = hlua_gethlua(L);
2241 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002242
2243 /* inform the stream that we want to be notified whenever the
2244 * connection completes.
2245 */
2246 si_applet_cant_get(&socket->s->si[0]);
2247 si_applet_cant_put(&socket->s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002248 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002249
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002250 hlua->flags |= HLUA_MUST_GC;
2251
Thierry FOURNIER847ca662016-12-16 13:07:22 +01002252 if (!hlua_com_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task))
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002253 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002254 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002255
2256 return 0;
2257}
2258
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002259#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002260__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2261{
2262 struct hlua_socket *socket;
2263
2264 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2265 socket = MAY_LJMP(hlua_checksocket(L, 1));
2266 socket->s->target = &socket_ssl.obj_type;
2267 return MAY_LJMP(hlua_socket_connect(L));
2268}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002269#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002270
2271__LJMP static int hlua_socket_setoption(struct lua_State *L)
2272{
2273 return 0;
2274}
2275
2276__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2277{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002278 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002279 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002280
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002281 MAY_LJMP(check_args(L, 2, "settimeout"));
2282
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002283 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002284 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002285
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002286 socket->s->req.rto = tmout;
2287 socket->s->req.wto = tmout;
2288 socket->s->res.rto = tmout;
2289 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002290
2291 return 0;
2292}
2293
2294__LJMP static int hlua_socket_new(lua_State *L)
2295{
2296 struct hlua_socket *socket;
2297 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002298 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002299 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002300 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002301
2302 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002303 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002304 hlua_pusherror(L, "socket: full stack");
2305 goto out_fail_conf;
2306 }
2307
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002308 /* Create the object: obj[0] = userdata. */
2309 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002310 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002311 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002312 memset(socket, 0, sizeof(*socket));
2313
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002314 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002315 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002316 hlua_pusherror(L, "socket: uninitialized pools.");
2317 goto out_fail_conf;
2318 }
2319
Willy Tarreau87b09662015-04-03 00:22:06 +02002320 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2322 lua_setmetatable(L, -2);
2323
Willy Tarreaud420a972015-04-06 00:39:18 +02002324 /* Create the applet context */
2325 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002326 if (!appctx) {
2327 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002328 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002329 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002330
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002331 appctx->ctx.hlua_cosocket.socket = socket;
2332 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002333 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002334 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2335 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002336
Willy Tarreaud420a972015-04-06 00:39:18 +02002337 /* Now create a session, task and stream for this applet */
2338 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2339 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002340 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002341 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002342 }
2343
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002344 task = task_new();
2345 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002346 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002347 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002348 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002349 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002350
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002351 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002352 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002353 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002354 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002355 }
2356
Willy Tarreaud420a972015-04-06 00:39:18 +02002357 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002358 socket->s = strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002359
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002360 /* Configure "right" stream interface. this "si" is used to connect
2361 * and retrieve data from the server. The connection is initialized
2362 * with the "struct server".
2363 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002364 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002365
2366 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002367 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2368 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002369
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002370 /* Update statistics counters. */
2371 socket_proxy.feconn++; /* beconn will be increased later */
2372 jobs++;
2373 totalconn++;
2374
Emeric Brun5f77fef2017-05-29 15:26:51 +02002375 task_wakeup(task, TASK_WOKEN_INIT);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002376 /* Return yield waiting for connection. */
2377 return 1;
2378
Willy Tarreaud420a972015-04-06 00:39:18 +02002379 out_fail_stream:
2380 task_free(task);
2381 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002382 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002383 out_fail_sess:
2384 appctx_free(appctx);
2385 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002386 WILL_LJMP(lua_error(L));
2387 return 0;
2388}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002389
2390/*
2391 *
2392 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002393 * Class Channel
2394 *
2395 *
2396 */
2397
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002398/* The state between the channel data and the HTTP parser state can be
2399 * unconsistent, so reset the parser and call it again. Warning, this
2400 * action not revalidate the request and not send a 400 if the modified
2401 * resuest is not valid.
2402 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002403 * This function never fails. The direction is set using dir, which equals
2404 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002405 */
2406static void hlua_resynchonize_proto(struct stream *stream, int dir)
2407{
2408 /* Protocol HTTP. */
2409 if (stream->be->mode == PR_MODE_HTTP) {
2410
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002411 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002412 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002413 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002414 http_txn_reset_res(stream->txn);
2415
2416 if (stream->txn->hdr_idx.v)
2417 hdr_idx_init(&stream->txn->hdr_idx);
2418
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002419 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002420 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002421 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002422 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2423 }
2424}
2425
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002426/* This function is called before the Lua execution. It stores
2427 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002428 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002429static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002430{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002431 c->mode = stream->be->mode;
2432 switch (c->mode) {
2433 case PR_MODE_HTTP:
2434 c->data.http.dir = opt & SMP_OPT_DIR;
2435 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2436 c->data.http.state = stream->txn->req.msg_state;
2437 else
2438 c->data.http.state = stream->txn->rsp.msg_state;
2439 break;
2440 default:
2441 break;
2442 }
2443}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002444
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002445/* This function is called after the Lua execution. it
2446 * returns true if the parser state is consistent, otherwise,
2447 * it return false.
2448 *
2449 * In HTTP mode, the parser state must be in the same state
2450 * or greater when we exit the function. Even if we do a
2451 * control yield. This prevent to break the HTTP message
2452 * from the Lua code.
2453 */
2454static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2455{
2456 if (c->mode != stream->be->mode)
2457 return 0;
2458
2459 switch (c->mode) {
2460 case PR_MODE_HTTP:
2461 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002462 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002463 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2464 return stream->txn->req.msg_state >= c->data.http.state;
2465 else
2466 return stream->txn->rsp.msg_state >= c->data.http.state;
2467 default:
2468 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002469 }
2470 return 1;
2471}
2472
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002473/* Returns the struct hlua_channel join to the class channel in the
2474 * stack entry "ud" or throws an argument error.
2475 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002476__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002477{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002478 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002479}
2480
Willy Tarreau47860ed2015-03-10 14:07:50 +01002481/* Pushes the channel onto the top of the stack. If the stask does not have a
2482 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002483 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002484static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002485{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002486 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002487 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002488 return 0;
2489
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002490 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002491 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002492 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002493
2494 /* Pop a class sesison metatable and affect it to the userdata. */
2495 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2496 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002497 return 1;
2498}
2499
2500/* Duplicate all the data present in the input channel and put it
2501 * in a string LUA variables. Returns -1 and push a nil value in
2502 * the stack if the channel is closed and all the data are consumed,
2503 * returns 0 if no data are available, otherwise it returns the length
2504 * of the builded string.
2505 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002506static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002507{
2508 char *blk1;
2509 char *blk2;
2510 int len1;
2511 int len2;
2512 int ret;
2513 luaL_Buffer b;
2514
Willy Tarreau47860ed2015-03-10 14:07:50 +01002515 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002516 if (unlikely(ret == 0))
2517 return 0;
2518
2519 if (unlikely(ret < 0)) {
2520 lua_pushnil(L);
2521 return -1;
2522 }
2523
2524 luaL_buffinit(L, &b);
2525 luaL_addlstring(&b, blk1, len1);
2526 if (unlikely(ret == 2))
2527 luaL_addlstring(&b, blk2, len2);
2528 luaL_pushresult(&b);
2529
2530 if (unlikely(ret == 2))
2531 return len1 + len2;
2532 return len1;
2533}
2534
2535/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2536 * a yield. This function keep the data in the buffer.
2537 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002538__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002539{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002540 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002541
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002542 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2543
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002544 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002545 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002546 return 1;
2547}
2548
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002549/* Check arguments for the function "hlua_channel_dup_yield". */
2550__LJMP static int hlua_channel_dup(lua_State *L)
2551{
2552 MAY_LJMP(check_args(L, 1, "dup"));
2553 MAY_LJMP(hlua_checkchannel(L, 1));
2554 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2555}
2556
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002557/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2558 * a yield. This function consumes the data in the buffer. It returns
2559 * a string containing the data or a nil pointer if no data are available
2560 * and the channel is closed.
2561 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002562__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002563{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002564 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002565 int ret;
2566
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002567 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002568
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002569 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002570 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002571 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002572
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002573 if (unlikely(ret == -1))
2574 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002575
Willy Tarreau47860ed2015-03-10 14:07:50 +01002576 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002577 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002578 return 1;
2579}
2580
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002581/* Check arguments for the fucntion "hlua_channel_get_yield". */
2582__LJMP static int hlua_channel_get(lua_State *L)
2583{
2584 MAY_LJMP(check_args(L, 1, "get"));
2585 MAY_LJMP(hlua_checkchannel(L, 1));
2586 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2587}
2588
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002589/* This functions consumes and returns one line. If the channel is closed,
2590 * and the last data does not contains a final '\n', the data are returned
2591 * without the final '\n'. When no more data are avalaible, it returns nil
2592 * value.
2593 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002594__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002595{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002596 char *blk1;
2597 char *blk2;
2598 int len1;
2599 int len2;
2600 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002601 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002602 int ret;
2603 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002604
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002605 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2606
Willy Tarreau47860ed2015-03-10 14:07:50 +01002607 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002608 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002609 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002610
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002611 if (ret == -1) {
2612 lua_pushnil(L);
2613 return 1;
2614 }
2615
2616 luaL_buffinit(L, &b);
2617 luaL_addlstring(&b, blk1, len1);
2618 len = len1;
2619 if (unlikely(ret == 2)) {
2620 luaL_addlstring(&b, blk2, len2);
2621 len += len2;
2622 }
2623 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002624 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002625 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002626 return 1;
2627}
2628
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002629/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2630__LJMP static int hlua_channel_getline(lua_State *L)
2631{
2632 MAY_LJMP(check_args(L, 1, "getline"));
2633 MAY_LJMP(hlua_checkchannel(L, 1));
2634 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2635}
2636
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002637/* This function takes a string as input, and append it at the
2638 * input side of channel. If the data is too big, but a space
2639 * is probably available after sending some data, the function
2640 * yield. If the data is bigger than the buffer, or if the
2641 * channel is closed, it returns -1. otherwise, it returns the
2642 * amount of data writed.
2643 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002644__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002645{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002646 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002647 size_t len;
2648 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2649 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2650 int ret;
2651 int max;
2652
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002653 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2654 * the request buffer if its not required.
2655 */
2656 if (chn->buf->size == 0) {
2657 si_applet_cant_put(chn_prod(chn));
2658 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2659 }
2660
Willy Tarreau47860ed2015-03-10 14:07:50 +01002661 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002662 if (max > len - l)
2663 max = len - l;
2664
Willy Tarreau47860ed2015-03-10 14:07:50 +01002665 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002666 if (ret == -2 || ret == -3) {
2667 lua_pushinteger(L, -1);
2668 return 1;
2669 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002670 if (ret == -1) {
2671 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002672 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002673 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002674 l += ret;
2675 lua_pop(L, 1);
2676 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002677 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002678
Willy Tarreau47860ed2015-03-10 14:07:50 +01002679 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2680 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002681 /* There are no space avalaible, and the output buffer is empty.
2682 * in this case, we cannot add more data, so we cannot yield,
2683 * we return the amount of copyied data.
2684 */
2685 return 1;
2686 }
2687 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002688 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002689 return 1;
2690}
2691
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002692/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002693 * of the writed string, or -1 if the channel is closed or if the
2694 * buffer size is too little for the data.
2695 */
2696__LJMP static int hlua_channel_append(lua_State *L)
2697{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002698 size_t len;
2699
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002700 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002701 MAY_LJMP(hlua_checkchannel(L, 1));
2702 MAY_LJMP(luaL_checklstring(L, 2, &len));
2703 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002704 lua_pushinteger(L, 0);
2705
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002706 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002707}
2708
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002709/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002710 * his process by cleaning the buffer. The result is a replacement
2711 * of the current data. It returns the length of the writed string,
2712 * or -1 if the channel is closed or if the buffer size is too
2713 * little for the data.
2714 */
2715__LJMP static int hlua_channel_set(lua_State *L)
2716{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002717 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002718
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002719 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002720 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002721 lua_pushinteger(L, 0);
2722
Willy Tarreau47860ed2015-03-10 14:07:50 +01002723 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002724
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002725 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002726}
2727
2728/* Append data in the output side of the buffer. This data is immediatly
2729 * sent. The fcuntion returns the ammount of data writed. If the buffer
2730 * cannot contains the data, the function yield. The function returns -1
2731 * if the channel is closed.
2732 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002733__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002734{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002735 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002736 size_t len;
2737 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2738 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2739 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002740 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002741
Willy Tarreau47860ed2015-03-10 14:07:50 +01002742 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002743 lua_pushinteger(L, -1);
2744 return 1;
2745 }
2746
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002747 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2748 * the request buffer if its not required.
2749 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002750 if (chn->buf->size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002751 si_applet_cant_put(chn_prod(chn));
2752 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002753 }
2754
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002755 /* the writed data will be immediatly sent, so we can check
2756 * the avalaible space without taking in account the reserve.
2757 * The reserve is guaranted for the processing of incoming
2758 * data, because the buffer will be flushed.
2759 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002760 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002761
2762 /* If there are no space avalaible, and the output buffer is empty.
2763 * in this case, we cannot add more data, so we cannot yield,
2764 * we return the amount of copyied data.
2765 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002766 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002767 return 1;
2768
2769 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002770 if (max > len - l)
2771 max = len - l;
2772
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002773 /* The buffer avalaible size may be not contiguous. This test
2774 * detects a non contiguous buffer and realign it.
2775 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002776 if (bi_space_for_replace(chn->buf) < max)
2777 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002778
2779 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002780 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002781
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002782 /* buffer replace considers that the input part is filled.
2783 * so, I must forward these new data in the output part.
2784 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002785 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002786
2787 l += max;
2788 lua_pop(L, 1);
2789 lua_pushinteger(L, l);
2790
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002791 /* If there are no space avalaible, and the output buffer is empty.
2792 * in this case, we cannot add more data, so we cannot yield,
2793 * we return the amount of copyied data.
2794 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002795 max = chn->buf->size - buffer_len(chn->buf);
2796 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002797 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002798
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002799 if (l < len) {
2800 /* If we are waiting for space in the response buffer, we
2801 * must set the flag WAKERESWR. This flag required the task
2802 * wake up if any activity is detected on the response buffer.
2803 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002804 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002805 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002806 else
2807 HLUA_SET_WAKEREQWR(hlua);
2808 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002809 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002810
2811 return 1;
2812}
2813
2814/* Just a wraper of "_hlua_channel_send". This wrapper permits
2815 * yield the LUA process, and resume it without checking the
2816 * input arguments.
2817 */
2818__LJMP static int hlua_channel_send(lua_State *L)
2819{
2820 MAY_LJMP(check_args(L, 2, "send"));
2821 lua_pushinteger(L, 0);
2822
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002823 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002824}
2825
2826/* This function forward and amount of butes. The data pass from
2827 * the input side of the buffer to the output side, and can be
2828 * forwarded. This function never fails.
2829 *
2830 * The Lua function takes an amount of bytes to be forwarded in
2831 * imput. It returns the number of bytes forwarded.
2832 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002833__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002834{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002835 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002836 int len;
2837 int l;
2838 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002839 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002840
2841 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2842 len = MAY_LJMP(luaL_checkinteger(L, 2));
2843 l = MAY_LJMP(luaL_checkinteger(L, -1));
2844
2845 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002846 if (max > chn->buf->i)
2847 max = chn->buf->i;
2848 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002849 l += max;
2850
2851 lua_pop(L, 1);
2852 lua_pushinteger(L, l);
2853
2854 /* Check if it miss bytes to forward. */
2855 if (l < len) {
2856 /* The the input channel or the output channel are closed, we
2857 * must return the amount of data forwarded.
2858 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002859 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002860 return 1;
2861
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002862 /* If we are waiting for space data in the response buffer, we
2863 * must set the flag WAKERESWR. This flag required the task
2864 * wake up if any activity is detected on the response buffer.
2865 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002866 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002867 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002868 else
2869 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002870
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002871 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002872 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002873 }
2874
2875 return 1;
2876}
2877
2878/* Just check the input and prepare the stack for the previous
2879 * function "hlua_channel_forward_yield"
2880 */
2881__LJMP static int hlua_channel_forward(lua_State *L)
2882{
2883 MAY_LJMP(check_args(L, 2, "forward"));
2884 MAY_LJMP(hlua_checkchannel(L, 1));
2885 MAY_LJMP(luaL_checkinteger(L, 2));
2886
2887 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002888 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002889}
2890
2891/* Just returns the number of bytes available in the input
2892 * side of the buffer. This function never fails.
2893 */
2894__LJMP static int hlua_channel_get_in_len(lua_State *L)
2895{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002896 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002897
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002898 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002899 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002900 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002901 return 1;
2902}
2903
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01002904/* Returns true if the channel is full. */
2905__LJMP static int hlua_channel_is_full(lua_State *L)
2906{
2907 struct channel *chn;
2908 int rem;
2909
2910 MAY_LJMP(check_args(L, 1, "is_full"));
2911 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2912
2913 rem = chn->buf->size;
2914 rem -= chn->buf->o; /* Output size */
2915 rem -= chn->buf->i; /* Input size */
2916 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
2917
2918 lua_pushboolean(L, rem <= 0);
2919 return 1;
2920}
2921
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002922/* Just returns the number of bytes available in the output
2923 * side of the buffer. This function never fails.
2924 */
2925__LJMP static int hlua_channel_get_out_len(lua_State *L)
2926{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002927 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002928
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002929 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002930 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002931 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002932 return 1;
2933}
2934
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002935/*
2936 *
2937 *
2938 * Class Fetches
2939 *
2940 *
2941 */
2942
2943/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002944 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002945 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002946__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002947{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002948 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002949}
2950
2951/* This function creates and push in the stack a fetch object according
2952 * with a current TXN.
2953 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002954static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002955{
Willy Tarreau7073c472015-04-06 11:15:40 +02002956 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002957
2958 /* Check stack size. */
2959 if (!lua_checkstack(L, 3))
2960 return 0;
2961
2962 /* Create the object: obj[0] = userdata.
2963 * Note that the base of the Fetches object is the
2964 * transaction object.
2965 */
2966 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002967 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002968 lua_rawseti(L, -2, 0);
2969
Willy Tarreau7073c472015-04-06 11:15:40 +02002970 hsmp->s = txn->s;
2971 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01002972 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002973 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002974
2975 /* Pop a class sesison metatable and affect it to the userdata. */
2976 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2977 lua_setmetatable(L, -2);
2978
2979 return 1;
2980}
2981
2982/* This function is an LUA binding. It is called with each sample-fetch.
2983 * It uses closure argument to store the associated sample-fetch. It
2984 * returns only one argument or throws an error. An error is thrown
2985 * only if an error is encountered during the argument parsing. If
2986 * the "sample-fetch" function fails, nil is returned.
2987 */
2988__LJMP static int hlua_run_sample_fetch(lua_State *L)
2989{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002990 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002991 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002992 struct arg args[ARGM_NBARGS + 1];
2993 int i;
2994 struct sample smp;
2995
2996 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002997 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002998
2999 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003000 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003001
Thierry FOURNIERca988662015-12-20 18:43:03 +01003002 /* Check execution authorization. */
3003 if (f->use & SMP_USE_HTTP_ANY &&
3004 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3005 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3006 "is not available in Lua services", f->kw);
3007 WILL_LJMP(lua_error(L));
3008 }
3009
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003010 /* Get extra arguments. */
3011 for (i = 0; i < lua_gettop(L) - 1; i++) {
3012 if (i >= ARGM_NBARGS)
3013 break;
3014 hlua_lua2arg(L, i + 2, &args[i]);
3015 }
3016 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003017 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003018
3019 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003020 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003021
3022 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003023 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003024 lua_pushfstring(L, "error in arguments");
3025 WILL_LJMP(lua_error(L));
3026 }
3027
3028 /* Initialise the sample. */
3029 memset(&smp, 0, sizeof(smp));
3030
3031 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003032 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003033 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003034 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003035 lua_pushstring(L, "");
3036 else
3037 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003038 return 1;
3039 }
3040
3041 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003042 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003043 hlua_smp2lua_str(L, &smp);
3044 else
3045 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003046 return 1;
3047}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003048
3049/*
3050 *
3051 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003052 * Class Converters
3053 *
3054 *
3055 */
3056
3057/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003058 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003059 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003060__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003061{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003062 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003063}
3064
3065/* This function creates and push in the stack a Converters object
3066 * according with a current TXN.
3067 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003068static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003069{
Willy Tarreau7073c472015-04-06 11:15:40 +02003070 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003071
3072 /* Check stack size. */
3073 if (!lua_checkstack(L, 3))
3074 return 0;
3075
3076 /* Create the object: obj[0] = userdata.
3077 * Note that the base of the Converters object is the
3078 * same than the TXN object.
3079 */
3080 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003081 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003082 lua_rawseti(L, -2, 0);
3083
Willy Tarreau7073c472015-04-06 11:15:40 +02003084 hsmp->s = txn->s;
3085 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003086 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003087 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003088
Willy Tarreau87b09662015-04-03 00:22:06 +02003089 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003090 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3091 lua_setmetatable(L, -2);
3092
3093 return 1;
3094}
3095
3096/* This function is an LUA binding. It is called with each converter.
3097 * It uses closure argument to store the associated converter. It
3098 * returns only one argument or throws an error. An error is thrown
3099 * only if an error is encountered during the argument parsing. If
3100 * the converter function function fails, nil is returned.
3101 */
3102__LJMP static int hlua_run_sample_conv(lua_State *L)
3103{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003104 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003105 struct sample_conv *conv;
3106 struct arg args[ARGM_NBARGS + 1];
3107 int i;
3108 struct sample smp;
3109
3110 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003111 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003112
3113 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003114 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003115
3116 /* Get extra arguments. */
3117 for (i = 0; i < lua_gettop(L) - 2; i++) {
3118 if (i >= ARGM_NBARGS)
3119 break;
3120 hlua_lua2arg(L, i + 3, &args[i]);
3121 }
3122 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003123 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003124
3125 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003126 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003127
3128 /* Run the special args checker. */
3129 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3130 hlua_pusherror(L, "error in arguments");
3131 WILL_LJMP(lua_error(L));
3132 }
3133
3134 /* Initialise the sample. */
3135 if (!hlua_lua2smp(L, 2, &smp)) {
3136 hlua_pusherror(L, "error in the input argument");
3137 WILL_LJMP(lua_error(L));
3138 }
3139
Willy Tarreau1777ea62016-03-10 16:15:46 +01003140 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3141
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003142 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003143 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003144 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003145 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003146 WILL_LJMP(lua_error(L));
3147 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003148 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3149 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003150 hlua_pusherror(L, "error during the input argument casting");
3151 WILL_LJMP(lua_error(L));
3152 }
3153
3154 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003155 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003156 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003157 lua_pushstring(L, "");
3158 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003159 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003160 return 1;
3161 }
3162
3163 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003164 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003165 hlua_smp2lua_str(L, &smp);
3166 else
3167 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003168 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003169}
3170
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003171/*
3172 *
3173 *
3174 * Class AppletTCP
3175 *
3176 *
3177 */
3178
3179/* Returns a struct hlua_txn if the stack entry "ud" is
3180 * a class stream, otherwise it throws an error.
3181 */
3182__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3183{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003184 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003185}
3186
3187/* This function creates and push in the stack an Applet object
3188 * according with a current TXN.
3189 */
3190static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3191{
3192 struct hlua_appctx *appctx;
3193 struct stream_interface *si = ctx->owner;
3194 struct stream *s = si_strm(si);
3195 struct proxy *p = s->be;
3196
3197 /* Check stack size. */
3198 if (!lua_checkstack(L, 3))
3199 return 0;
3200
3201 /* Create the object: obj[0] = userdata.
3202 * Note that the base of the Converters object is the
3203 * same than the TXN object.
3204 */
3205 lua_newtable(L);
3206 appctx = lua_newuserdata(L, sizeof(*appctx));
3207 lua_rawseti(L, -2, 0);
3208 appctx->appctx = ctx;
3209 appctx->htxn.s = s;
3210 appctx->htxn.p = p;
3211
3212 /* Create the "f" field that contains a list of fetches. */
3213 lua_pushstring(L, "f");
3214 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3215 return 0;
3216 lua_settable(L, -3);
3217
3218 /* Create the "sf" field that contains a list of stringsafe fetches. */
3219 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003220 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003221 return 0;
3222 lua_settable(L, -3);
3223
3224 /* Create the "c" field that contains a list of converters. */
3225 lua_pushstring(L, "c");
3226 if (!hlua_converters_new(L, &appctx->htxn, 0))
3227 return 0;
3228 lua_settable(L, -3);
3229
3230 /* Create the "sc" field that contains a list of stringsafe converters. */
3231 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003232 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003233 return 0;
3234 lua_settable(L, -3);
3235
3236 /* Pop a class stream metatable and affect it to the table. */
3237 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3238 lua_setmetatable(L, -2);
3239
3240 return 1;
3241}
3242
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003243__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3244{
3245 struct hlua_appctx *appctx;
3246 struct stream *s;
3247 const char *name;
3248 size_t len;
3249 struct sample smp;
3250
3251 MAY_LJMP(check_args(L, 3, "set_var"));
3252
3253 /* It is useles to retrieve the stream, but this function
3254 * runs only in a stream context.
3255 */
3256 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3257 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3258 s = appctx->htxn.s;
3259
3260 /* Converts the third argument in a sample. */
3261 hlua_lua2smp(L, 3, &smp);
3262
3263 /* Store the sample in a variable. */
3264 smp_set_owner(&smp, s->be, s->sess, s, 0);
3265 vars_set_by_name(name, len, &smp);
3266 return 0;
3267}
3268
3269__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3270{
3271 struct hlua_appctx *appctx;
3272 struct stream *s;
3273 const char *name;
3274 size_t len;
3275 struct sample smp;
3276
3277 MAY_LJMP(check_args(L, 2, "unset_var"));
3278
3279 /* It is useles to retrieve the stream, but this function
3280 * runs only in a stream context.
3281 */
3282 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3283 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3284 s = appctx->htxn.s;
3285
3286 /* Unset the variable. */
3287 smp_set_owner(&smp, s->be, s->sess, s, 0);
3288 vars_unset_by_name(name, len, &smp);
3289 return 0;
3290}
3291
3292__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3293{
3294 struct hlua_appctx *appctx;
3295 struct stream *s;
3296 const char *name;
3297 size_t len;
3298 struct sample smp;
3299
3300 MAY_LJMP(check_args(L, 2, "get_var"));
3301
3302 /* It is useles to retrieve the stream, but this function
3303 * runs only in a stream context.
3304 */
3305 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3306 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3307 s = appctx->htxn.s;
3308
3309 smp_set_owner(&smp, s->be, s->sess, s, 0);
3310 if (!vars_get_by_name(name, len, &smp)) {
3311 lua_pushnil(L);
3312 return 1;
3313 }
3314
3315 return hlua_smp2lua(L, &smp);
3316}
3317
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003318__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3319{
3320 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3321 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003322 struct hlua *hlua;
3323
3324 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003325 if (!s->hlua)
3326 return 0;
3327 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003328
3329 MAY_LJMP(check_args(L, 2, "set_priv"));
3330
3331 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003332 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003333
3334 /* Get and store new value. */
3335 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3336 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3337
3338 return 0;
3339}
3340
3341__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3342{
3343 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3344 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003345 struct hlua *hlua;
3346
3347 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003348 if (!s->hlua) {
3349 lua_pushnil(L);
3350 return 1;
3351 }
3352 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003353
3354 /* Push configuration index in the stack. */
3355 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3356
3357 return 1;
3358}
3359
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003360/* If expected data not yet available, it returns a yield. This function
3361 * consumes the data in the buffer. It returns a string containing the
3362 * data. This string can be empty.
3363 */
3364__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3365{
3366 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3367 struct stream_interface *si = appctx->appctx->owner;
3368 int ret;
3369 char *blk1;
3370 int len1;
3371 char *blk2;
3372 int len2;
3373
3374 /* Read the maximum amount of data avalaible. */
3375 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3376
3377 /* Data not yet avalaible. return yield. */
3378 if (ret == 0) {
3379 si_applet_cant_get(si);
3380 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3381 }
3382
3383 /* End of data: commit the total strings and return. */
3384 if (ret < 0) {
3385 luaL_pushresult(&appctx->b);
3386 return 1;
3387 }
3388
3389 /* Ensure that the block 2 length is usable. */
3390 if (ret == 1)
3391 len2 = 0;
3392
3393 /* dont check the max length read and dont check. */
3394 luaL_addlstring(&appctx->b, blk1, len1);
3395 luaL_addlstring(&appctx->b, blk2, len2);
3396
3397 /* Consume input channel output buffer data. */
3398 bo_skip(si_oc(si), len1 + len2);
3399 luaL_pushresult(&appctx->b);
3400 return 1;
3401}
3402
3403/* Check arguments for the fucntion "hlua_channel_get_yield". */
3404__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3405{
3406 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3407
3408 /* Initialise the string catenation. */
3409 luaL_buffinit(L, &appctx->b);
3410
3411 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3412}
3413
3414/* If expected data not yet available, it returns a yield. This function
3415 * consumes the data in the buffer. It returns a string containing the
3416 * data. This string can be empty.
3417 */
3418__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3419{
3420 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3421 struct stream_interface *si = appctx->appctx->owner;
3422 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3423 int ret;
3424 char *blk1;
3425 int len1;
3426 char *blk2;
3427 int len2;
3428
3429 /* Read the maximum amount of data avalaible. */
3430 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3431
3432 /* Data not yet avalaible. return yield. */
3433 if (ret == 0) {
3434 si_applet_cant_get(si);
3435 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3436 }
3437
3438 /* End of data: commit the total strings and return. */
3439 if (ret < 0) {
3440 luaL_pushresult(&appctx->b);
3441 return 1;
3442 }
3443
3444 /* Ensure that the block 2 length is usable. */
3445 if (ret == 1)
3446 len2 = 0;
3447
3448 if (len == -1) {
3449
3450 /* If len == -1, catenate all the data avalaile and
3451 * yield because we want to get all the data until
3452 * the end of data stream.
3453 */
3454 luaL_addlstring(&appctx->b, blk1, len1);
3455 luaL_addlstring(&appctx->b, blk2, len2);
3456 bo_skip(si_oc(si), len1 + len2);
3457 si_applet_cant_get(si);
3458 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3459
3460 } else {
3461
3462 /* Copy the fisrt block caping to the length required. */
3463 if (len1 > len)
3464 len1 = len;
3465 luaL_addlstring(&appctx->b, blk1, len1);
3466 len -= len1;
3467
3468 /* Copy the second block. */
3469 if (len2 > len)
3470 len2 = len;
3471 luaL_addlstring(&appctx->b, blk2, len2);
3472 len -= len2;
3473
3474 /* Consume input channel output buffer data. */
3475 bo_skip(si_oc(si), len1 + len2);
3476
3477 /* If we are no other data avalaible, yield waiting for new data. */
3478 if (len > 0) {
3479 lua_pushinteger(L, len);
3480 lua_replace(L, 2);
3481 si_applet_cant_get(si);
3482 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3483 }
3484
3485 /* return the result. */
3486 luaL_pushresult(&appctx->b);
3487 return 1;
3488 }
3489
3490 /* we never executes this */
3491 hlua_pusherror(L, "Lua: internal error");
3492 WILL_LJMP(lua_error(L));
3493 return 0;
3494}
3495
3496/* Check arguments for the fucntion "hlua_channel_get_yield". */
3497__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3498{
3499 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3500 int len = -1;
3501
3502 if (lua_gettop(L) > 2)
3503 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3504 if (lua_gettop(L) >= 2) {
3505 len = MAY_LJMP(luaL_checkinteger(L, 2));
3506 lua_pop(L, 1);
3507 }
3508
3509 /* Confirm or set the required length */
3510 lua_pushinteger(L, len);
3511
3512 /* Initialise the string catenation. */
3513 luaL_buffinit(L, &appctx->b);
3514
3515 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3516}
3517
3518/* Append data in the output side of the buffer. This data is immediatly
3519 * sent. The fcuntion returns the ammount of data writed. If the buffer
3520 * cannot contains the data, the function yield. The function returns -1
3521 * if the channel is closed.
3522 */
3523__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3524{
3525 size_t len;
3526 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3527 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3528 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3529 struct stream_interface *si = appctx->appctx->owner;
3530 struct channel *chn = si_ic(si);
3531 int max;
3532
3533 /* Get the max amount of data which can write as input in the channel. */
3534 max = channel_recv_max(chn);
3535 if (max > (len - l))
3536 max = len - l;
3537
3538 /* Copy data. */
3539 bi_putblk(chn, str + l, max);
3540
3541 /* update counters. */
3542 l += max;
3543 lua_pop(L, 1);
3544 lua_pushinteger(L, l);
3545
3546 /* If some data is not send, declares the situation to the
3547 * applet, and returns a yield.
3548 */
3549 if (l < len) {
3550 si_applet_cant_put(si);
3551 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3552 }
3553
3554 return 1;
3555}
3556
3557/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3558 * yield the LUA process, and resume it without checking the
3559 * input arguments.
3560 */
3561__LJMP static int hlua_applet_tcp_send(lua_State *L)
3562{
3563 MAY_LJMP(check_args(L, 2, "send"));
3564 lua_pushinteger(L, 0);
3565
3566 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3567}
3568
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003569/*
3570 *
3571 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003572 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003573 *
3574 *
3575 */
3576
3577/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003578 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003579 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003580__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003581{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003582 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003583}
3584
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003585/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003586 * according with a current TXN.
3587 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003588static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003589{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003590 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003591 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003592 struct stream_interface *si = ctx->owner;
3593 struct stream *s = si_strm(si);
3594 struct proxy *px = s->be;
3595 struct http_txn *txn = s->txn;
3596 const char *path;
3597 const char *end;
3598 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003599
3600 /* Check stack size. */
3601 if (!lua_checkstack(L, 3))
3602 return 0;
3603
3604 /* Create the object: obj[0] = userdata.
3605 * Note that the base of the Converters object is the
3606 * same than the TXN object.
3607 */
3608 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003609 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003610 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003611 appctx->appctx = ctx;
3612 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003613 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003614 appctx->htxn.s = s;
3615 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003616
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003617 /* Create the "f" field that contains a list of fetches. */
3618 lua_pushstring(L, "f");
3619 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3620 return 0;
3621 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003622
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003623 /* Create the "sf" field that contains a list of stringsafe fetches. */
3624 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003625 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003626 return 0;
3627 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003628
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003629 /* Create the "c" field that contains a list of converters. */
3630 lua_pushstring(L, "c");
3631 if (!hlua_converters_new(L, &appctx->htxn, 0))
3632 return 0;
3633 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003634
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003635 /* Create the "sc" field that contains a list of stringsafe converters. */
3636 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003637 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003638 return 0;
3639 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003640
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003641 /* Stores the request method. */
3642 lua_pushstring(L, "method");
3643 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3644 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003645
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003646 /* Stores the http version. */
3647 lua_pushstring(L, "version");
3648 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3649 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003650
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003651 /* creates an array of headers. hlua_http_get_headers() crates and push
3652 * the array on the top of the stack.
3653 */
3654 lua_pushstring(L, "headers");
3655 htxn.s = s;
3656 htxn.p = px;
3657 htxn.dir = SMP_OPT_DIR_REQ;
3658 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3659 return 0;
3660 lua_settable(L, -3);
3661
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003662 /* Get path and qs */
3663 path = http_get_path(txn);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003664 if (path) {
3665 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3666 p = path;
3667 while (p < end && *p != '?')
3668 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003669
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003670 /* Stores the request path. */
3671 lua_pushstring(L, "path");
3672 lua_pushlstring(L, path, p - path);
3673 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003674
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003675 /* Stores the query string. */
3676 lua_pushstring(L, "qs");
3677 if (*p == '?')
3678 p++;
3679 lua_pushlstring(L, p, end - p);
3680 lua_settable(L, -3);
3681 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003682
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003683 /* Stores the request path. */
3684 lua_pushstring(L, "length");
3685 lua_pushinteger(L, txn->req.body_len);
3686 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003687
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003688 /* Create an array of HTTP request headers. */
3689 lua_pushstring(L, "headers");
3690 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3691 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003692
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003693 /* Create an empty array of HTTP request headers. */
3694 lua_pushstring(L, "response");
3695 lua_newtable(L);
3696 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003697
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003698 /* Pop a class stream metatable and affect it to the table. */
3699 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3700 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003701
3702 return 1;
3703}
3704
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003705__LJMP static int hlua_applet_http_set_var(lua_State *L)
3706{
3707 struct hlua_appctx *appctx;
3708 struct stream *s;
3709 const char *name;
3710 size_t len;
3711 struct sample smp;
3712
3713 MAY_LJMP(check_args(L, 3, "set_var"));
3714
3715 /* It is useles to retrieve the stream, but this function
3716 * runs only in a stream context.
3717 */
3718 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3719 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3720 s = appctx->htxn.s;
3721
3722 /* Converts the third argument in a sample. */
3723 hlua_lua2smp(L, 3, &smp);
3724
3725 /* Store the sample in a variable. */
3726 smp_set_owner(&smp, s->be, s->sess, s, 0);
3727 vars_set_by_name(name, len, &smp);
3728 return 0;
3729}
3730
3731__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3732{
3733 struct hlua_appctx *appctx;
3734 struct stream *s;
3735 const char *name;
3736 size_t len;
3737 struct sample smp;
3738
3739 MAY_LJMP(check_args(L, 2, "unset_var"));
3740
3741 /* It is useles to retrieve the stream, but this function
3742 * runs only in a stream context.
3743 */
3744 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3745 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3746 s = appctx->htxn.s;
3747
3748 /* Unset the variable. */
3749 smp_set_owner(&smp, s->be, s->sess, s, 0);
3750 vars_unset_by_name(name, len, &smp);
3751 return 0;
3752}
3753
3754__LJMP static int hlua_applet_http_get_var(lua_State *L)
3755{
3756 struct hlua_appctx *appctx;
3757 struct stream *s;
3758 const char *name;
3759 size_t len;
3760 struct sample smp;
3761
3762 MAY_LJMP(check_args(L, 2, "get_var"));
3763
3764 /* It is useles to retrieve the stream, but this function
3765 * runs only in a stream context.
3766 */
3767 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3768 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3769 s = appctx->htxn.s;
3770
3771 smp_set_owner(&smp, s->be, s->sess, s, 0);
3772 if (!vars_get_by_name(name, len, &smp)) {
3773 lua_pushnil(L);
3774 return 1;
3775 }
3776
3777 return hlua_smp2lua(L, &smp);
3778}
3779
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003780__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3781{
3782 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3783 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003784 struct hlua *hlua;
3785
3786 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003787 if (!s->hlua)
3788 return 0;
3789 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003790
3791 MAY_LJMP(check_args(L, 2, "set_priv"));
3792
3793 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003794 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003795
3796 /* Get and store new value. */
3797 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3798 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3799
3800 return 0;
3801}
3802
3803__LJMP static int hlua_applet_http_get_priv(lua_State *L)
3804{
3805 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3806 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003807 struct hlua *hlua;
3808
3809 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003810 if (!s->hlua) {
3811 lua_pushnil(L);
3812 return 1;
3813 }
3814 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003815
3816 /* Push configuration index in the stack. */
3817 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3818
3819 return 1;
3820}
3821
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003822/* If expected data not yet available, it returns a yield. This function
3823 * consumes the data in the buffer. It returns a string containing the
3824 * data. This string can be empty.
3825 */
3826__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003827{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003828 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3829 struct stream_interface *si = appctx->appctx->owner;
3830 struct channel *chn = si_ic(si);
3831 int ret;
3832 char *blk1;
3833 int len1;
3834 char *blk2;
3835 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003836
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003837 /* Maybe we cant send a 100-continue ? */
3838 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3839 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3840 /* if ret == -2 or -3 the channel closed or the message si too
3841 * big for the buffers. We cant send anything. So, we ignoring
3842 * the error, considers that the 100-continue is sent, and try
3843 * to receive.
3844 * If ret is -1, we dont have room in the buffer, so we yield.
3845 */
3846 if (ret == -1) {
3847 si_applet_cant_put(si);
3848 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3849 }
3850 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3851 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003852
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003853 /* Check for the end of the data. */
3854 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3855 luaL_pushresult(&appctx->b);
3856 return 1;
3857 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003858
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003859 /* Read the maximum amount of data avalaible. */
3860 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003861
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003862 /* Data not yet avalaible. return yield. */
3863 if (ret == 0) {
3864 si_applet_cant_get(si);
3865 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3866 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003867
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003868 /* End of data: commit the total strings and return. */
3869 if (ret < 0) {
3870 luaL_pushresult(&appctx->b);
3871 return 1;
3872 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003873
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003874 /* Ensure that the block 2 length is usable. */
3875 if (ret == 1)
3876 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003877
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003878 /* Copy the fisrt block caping to the length required. */
3879 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3880 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3881 luaL_addlstring(&appctx->b, blk1, len1);
3882 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003883
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003884 /* Copy the second block. */
3885 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3886 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3887 luaL_addlstring(&appctx->b, blk2, len2);
3888 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003889
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003890 /* Consume input channel output buffer data. */
3891 bo_skip(si_oc(si), len1 + len2);
3892 luaL_pushresult(&appctx->b);
3893 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003894}
3895
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003896/* Check arguments for the fucntion "hlua_channel_get_yield". */
3897__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003898{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003899 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003900
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003901 /* Initialise the string catenation. */
3902 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003903
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003904 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003905}
3906
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003907/* If expected data not yet available, it returns a yield. This function
3908 * consumes the data in the buffer. It returns a string containing the
3909 * data. This string can be empty.
3910 */
3911__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003912{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003913 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3914 struct stream_interface *si = appctx->appctx->owner;
3915 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3916 struct channel *chn = si_ic(si);
3917 int ret;
3918 char *blk1;
3919 int len1;
3920 char *blk2;
3921 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003922
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003923 /* Maybe we cant send a 100-continue ? */
3924 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3925 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3926 /* if ret == -2 or -3 the channel closed or the message si too
3927 * big for the buffers. We cant send anything. So, we ignoring
3928 * the error, considers that the 100-continue is sent, and try
3929 * to receive.
3930 * If ret is -1, we dont have room in the buffer, so we yield.
3931 */
3932 if (ret == -1) {
3933 si_applet_cant_put(si);
3934 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3935 }
3936 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3937 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003938
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003939 /* Read the maximum amount of data avalaible. */
3940 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003941
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003942 /* Data not yet avalaible. return yield. */
3943 if (ret == 0) {
3944 si_applet_cant_get(si);
3945 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3946 }
3947
3948 /* End of data: commit the total strings and return. */
3949 if (ret < 0) {
3950 luaL_pushresult(&appctx->b);
3951 return 1;
3952 }
3953
3954 /* Ensure that the block 2 length is usable. */
3955 if (ret == 1)
3956 len2 = 0;
3957
3958 /* Copy the fisrt block caping to the length required. */
3959 if (len1 > len)
3960 len1 = len;
3961 luaL_addlstring(&appctx->b, blk1, len1);
3962 len -= len1;
3963
3964 /* Copy the second block. */
3965 if (len2 > len)
3966 len2 = len;
3967 luaL_addlstring(&appctx->b, blk2, len2);
3968 len -= len2;
3969
3970 /* Consume input channel output buffer data. */
3971 bo_skip(si_oc(si), len1 + len2);
3972 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
3973 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
3974
3975 /* If we are no other data avalaible, yield waiting for new data. */
3976 if (len > 0) {
3977 lua_pushinteger(L, len);
3978 lua_replace(L, 2);
3979 si_applet_cant_get(si);
3980 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3981 }
3982
3983 /* return the result. */
3984 luaL_pushresult(&appctx->b);
3985 return 1;
3986}
3987
3988/* Check arguments for the fucntion "hlua_channel_get_yield". */
3989__LJMP static int hlua_applet_http_recv(lua_State *L)
3990{
3991 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3992 int len = -1;
3993
3994 /* Check arguments. */
3995 if (lua_gettop(L) > 2)
3996 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3997 if (lua_gettop(L) >= 2) {
3998 len = MAY_LJMP(luaL_checkinteger(L, 2));
3999 lua_pop(L, 1);
4000 }
4001
4002 /* Check the required length */
4003 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4004 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4005 lua_pushinteger(L, len);
4006
4007 /* Initialise the string catenation. */
4008 luaL_buffinit(L, &appctx->b);
4009
4010 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4011}
4012
4013/* Append data in the output side of the buffer. This data is immediatly
4014 * sent. The fcuntion returns the ammount of data writed. If the buffer
4015 * cannot contains the data, the function yield. The function returns -1
4016 * if the channel is closed.
4017 */
4018__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4019{
4020 size_t len;
4021 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4022 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4023 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4024 struct stream_interface *si = appctx->appctx->owner;
4025 struct channel *chn = si_ic(si);
4026 int max;
4027
4028 /* Get the max amount of data which can write as input in the channel. */
4029 max = channel_recv_max(chn);
4030 if (max > (len - l))
4031 max = len - l;
4032
4033 /* Copy data. */
4034 bi_putblk(chn, str + l, max);
4035
4036 /* update counters. */
4037 l += max;
4038 lua_pop(L, 1);
4039 lua_pushinteger(L, l);
4040
4041 /* If some data is not send, declares the situation to the
4042 * applet, and returns a yield.
4043 */
4044 if (l < len) {
4045 si_applet_cant_put(si);
4046 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
4047 }
4048
4049 return 1;
4050}
4051
4052/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4053 * yield the LUA process, and resume it without checking the
4054 * input arguments.
4055 */
4056__LJMP static int hlua_applet_http_send(lua_State *L)
4057{
4058 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4059 size_t len;
4060 char hex[10];
4061
4062 MAY_LJMP(luaL_checklstring(L, 2, &len));
4063
4064 /* If transfer encoding chunked is selected, we surround the data
4065 * by chunk data.
4066 */
4067 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4068 snprintf(hex, 9, "%x", (unsigned int)len);
4069 lua_pushfstring(L, "%s\r\n", hex);
4070 lua_insert(L, 2); /* swap the last 2 entries. */
4071 lua_pushstring(L, "\r\n");
4072 lua_concat(L, 3);
4073 }
4074
4075 /* This interger is used for followinf the amount of data sent. */
4076 lua_pushinteger(L, 0);
4077
4078 /* We want to send some data. Headers must be sent. */
4079 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4080 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4081 WILL_LJMP(lua_error(L));
4082 }
4083
4084 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4085}
4086
4087__LJMP static int hlua_applet_http_addheader(lua_State *L)
4088{
4089 const char *name;
4090 int ret;
4091
4092 MAY_LJMP(hlua_checkapplet_http(L, 1));
4093 name = MAY_LJMP(luaL_checkstring(L, 2));
4094 MAY_LJMP(luaL_checkstring(L, 3));
4095
4096 /* Push in the stack the "response" entry. */
4097 ret = lua_getfield(L, 1, "response");
4098 if (ret != LUA_TTABLE) {
4099 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4100 "is expected as an array. %s found", lua_typename(L, ret));
4101 WILL_LJMP(lua_error(L));
4102 }
4103
4104 /* check if the header is already registered if it is not
4105 * the case, register it.
4106 */
4107 ret = lua_getfield(L, -1, name);
4108 if (ret == LUA_TNIL) {
4109
4110 /* Entry not found. */
4111 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4112
4113 /* Insert the new header name in the array in the top of the stack.
4114 * It left the new array in the top of the stack.
4115 */
4116 lua_newtable(L);
4117 lua_pushvalue(L, 2);
4118 lua_pushvalue(L, -2);
4119 lua_settable(L, -4);
4120
4121 } else if (ret != LUA_TTABLE) {
4122
4123 /* corruption error. */
4124 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4125 "is expected as an array. %s found", name, lua_typename(L, ret));
4126 WILL_LJMP(lua_error(L));
4127 }
4128
4129 /* Now the top od thestack is an array of values. We push
4130 * the header value as new entry.
4131 */
4132 lua_pushvalue(L, 3);
4133 ret = lua_rawlen(L, -2);
4134 lua_rawseti(L, -2, ret + 1);
4135 lua_pushboolean(L, 1);
4136 return 1;
4137}
4138
4139__LJMP static int hlua_applet_http_status(lua_State *L)
4140{
4141 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4142 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004143 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004144
4145 if (status < 100 || status > 599) {
4146 lua_pushboolean(L, 0);
4147 return 1;
4148 }
4149
4150 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004151 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004152 lua_pushboolean(L, 1);
4153 return 1;
4154}
4155
4156/* We will build the status line and the headers of the HTTP response.
4157 * We will try send at once if its not possible, we give back the hand
4158 * waiting for more room.
4159 */
4160__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4161{
4162 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4163 struct stream_interface *si = appctx->appctx->owner;
4164 struct channel *chn = si_ic(si);
4165 int ret;
4166 size_t len;
4167 const char *msg;
4168
4169 /* Get the message as the first argument on the stack. */
4170 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4171
4172 /* Send the message at once. */
4173 ret = bi_putblk(chn, msg, len);
4174
4175 /* if ret == -2 or -3 the channel closed or the message si too
4176 * big for the buffers.
4177 */
4178 if (ret == -2 || ret == -3) {
4179 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4180 WILL_LJMP(lua_error(L));
4181 }
4182
4183 /* If ret is -1, we dont have room in the buffer, so we yield. */
4184 if (ret == -1) {
4185 si_applet_cant_put(si);
4186 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4187 }
4188
4189 /* Headers sent, set the flag. */
4190 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4191 return 0;
4192}
4193
4194__LJMP static int hlua_applet_http_start_response(lua_State *L)
4195{
4196 struct chunk *tmp = get_trash_chunk();
4197 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004198 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02004199 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004200 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02004201 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004202 int id;
4203 int hdr_connection = 0;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004204 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004205 int hdr_chunked = 0;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004206 const char *reason = appctx->appctx->ctx.hlua_apphttp.reason;
4207
4208 if (reason == NULL)
4209 reason = get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004210
4211 /* Use the same http version than the request. */
4212 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004213 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004214 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004215 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004216
4217 /* Get the array associated to the field "response" in the object AppletHTTP. */
4218 lua_pushvalue(L, 0);
4219 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4220 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4221 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4222 WILL_LJMP(lua_error(L));
4223 }
4224
4225 /* Browse the list of headers. */
4226 lua_pushnil(L);
4227 while(lua_next(L, -2) != 0) {
4228
4229 /* We expect a string as -2. */
4230 if (lua_type(L, -2) != LUA_TSTRING) {
4231 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4232 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4233 lua_typename(L, lua_type(L, -2)));
4234 WILL_LJMP(lua_error(L));
4235 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004236 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004237
4238 /* We expect an array as -1. */
4239 if (lua_type(L, -1) != LUA_TTABLE) {
4240 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4241 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4242 name,
4243 lua_typename(L, lua_type(L, -1)));
4244 WILL_LJMP(lua_error(L));
4245 }
4246
4247 /* Browse the table who is on the top of the stack. */
4248 lua_pushnil(L);
4249 while(lua_next(L, -2) != 0) {
4250
4251 /* We expect a number as -2. */
4252 if (lua_type(L, -2) != LUA_TNUMBER) {
4253 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4254 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4255 name,
4256 lua_typename(L, lua_type(L, -2)));
4257 WILL_LJMP(lua_error(L));
4258 }
4259 id = lua_tointeger(L, -2);
4260
4261 /* We expect a string as -2. */
4262 if (lua_type(L, -1) != LUA_TSTRING) {
4263 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4264 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4265 name, id,
4266 lua_typename(L, lua_type(L, -1)));
4267 WILL_LJMP(lua_error(L));
4268 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004269 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004270
4271 /* Catenate a new header. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004272 if (tmp->len + name_len + 2 + value_len + 2 < tmp->size) {
4273 memcpy(tmp->str + tmp->len, name, name_len);
4274 tmp->len += name_len;
4275 tmp->str[tmp->len++] = ':';
4276 tmp->str[tmp->len++] = ' ';
4277
4278 memcpy(tmp->str + tmp->len, value, value_len);
4279 tmp->len += value_len;
4280 tmp->str[tmp->len++] = '\r';
4281 tmp->str[tmp->len++] = '\n';
4282 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004283
4284 /* Protocol checks. */
4285
4286 /* Check if the header conneciton is present. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004287 if (name_len == 10 && strcasecmp("connection", name) == 0)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004288 hdr_connection = 1;
4289
4290 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004291 * is done without control. If it contains a bad value,
4292 * the content-length remains negative so that we can
4293 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004294 */
Willy Tarreaua3294632017-08-23 11:24:47 +02004295 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004296 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004297
4298 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004299 if (name_len == 17 && value_len == 7 &&
4300 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004301 strcasecmp("chunked", value) == 0)
4302 hdr_chunked = 1;
4303
4304 /* Remove the array from the stack, and get next element with a remaining string. */
4305 lua_pop(L, 1);
4306 }
4307
4308 /* Remove the array from the stack, and get next element with a remaining string. */
4309 lua_pop(L, 1);
4310 }
4311
4312 /* If the http protocol version is 1.1, we expect an header "connection" set
4313 * to "close" to be HAProxy/keeplive compliant. Otherwise, we expect nothing.
4314 * If the header conneciton is present, don't change it, if it is not present,
4315 * we must set.
4316 *
4317 * we set a "connection: close" header for ensuring that the keepalive will be
4318 * respected by haproxy. HAProcy considers that the application cloe the connection
4319 * and it keep the connection from the client open.
4320 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004321 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 && !hdr_connection)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004322 chunk_appendf(tmp, "Connection: close\r\n");
4323
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004324 /* If we dont have a content-length set, and the HTTP version is 1.1
4325 * and the status code implies the presence of a message body, we must
4326 * announce a transfer encoding chunked. This is required by haproxy
4327 * for the keepalive compliance. If the applet annouces a transfer-encoding
4328 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004329 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004330 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004331 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
4332 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4333 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4334 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004335 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4336 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4337 }
4338
4339 /* Finalize headers. */
4340 chunk_appendf(tmp, "\r\n");
4341
4342 /* Remove the last entry and the array of headers */
4343 lua_pop(L, 2);
4344
4345 /* Push the headers block. */
4346 lua_pushlstring(L, tmp->str, tmp->len);
4347
4348 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4349}
4350
4351/*
4352 *
4353 *
4354 * Class HTTP
4355 *
4356 *
4357 */
4358
4359/* Returns a struct hlua_txn if the stack entry "ud" is
4360 * a class stream, otherwise it throws an error.
4361 */
4362__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4363{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004364 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004365}
4366
4367/* This function creates and push in the stack a HTTP object
4368 * according with a current TXN.
4369 */
4370static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4371{
4372 struct hlua_txn *htxn;
4373
4374 /* Check stack size. */
4375 if (!lua_checkstack(L, 3))
4376 return 0;
4377
4378 /* Create the object: obj[0] = userdata.
4379 * Note that the base of the Converters object is the
4380 * same than the TXN object.
4381 */
4382 lua_newtable(L);
4383 htxn = lua_newuserdata(L, sizeof(*htxn));
4384 lua_rawseti(L, -2, 0);
4385
4386 htxn->s = txn->s;
4387 htxn->p = txn->p;
4388
4389 /* Pop a class stream metatable and affect it to the table. */
4390 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4391 lua_setmetatable(L, -2);
4392
4393 return 1;
4394}
4395
4396/* This function creates ans returns an array of HTTP headers.
4397 * This function does not fails. It is used as wrapper with the
4398 * 2 following functions.
4399 */
4400__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4401{
4402 const char *cur_ptr, *cur_next, *p;
4403 int old_idx, cur_idx;
4404 struct hdr_idx_elem *cur_hdr;
4405 const char *hn, *hv;
4406 int hnl, hvl;
4407 int type;
4408 const char *in;
4409 char *out;
4410 int len;
4411
4412 /* Create the table. */
4413 lua_newtable(L);
4414
4415 if (!htxn->s->txn)
4416 return 1;
4417
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004418 /* Check if a valid response is parsed */
4419 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4420 return 1;
4421
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004422 /* Build array of headers. */
4423 old_idx = 0;
4424 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4425
4426 while (1) {
4427 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4428 if (!cur_idx)
4429 break;
4430 old_idx = cur_idx;
4431
4432 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4433 cur_ptr = cur_next;
4434 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4435
4436 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4437 * and the next header starts at cur_next. We'll check
4438 * this header in the list as well as against the default
4439 * rule.
4440 */
4441
4442 /* look for ': *'. */
4443 hn = cur_ptr;
4444 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4445 if (p >= cur_ptr+cur_hdr->len)
4446 continue;
4447 hnl = p - hn;
4448 p++;
4449 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4450 p++;
4451 if (p >= cur_ptr+cur_hdr->len)
4452 continue;
4453 hv = p;
4454 hvl = cur_ptr+cur_hdr->len-p;
4455
4456 /* Lowercase the key. Don't check the size of trash, it have
4457 * the size of one buffer and the input data contains in one
4458 * buffer.
4459 */
4460 out = trash.str;
4461 for (in=hn; in<hn+hnl; in++, out++)
4462 *out = tolower(*in);
4463 *out = '\0';
4464
4465 /* Check for existing entry:
4466 * assume that the table is on the top of the stack, and
4467 * push the key in the stack, the function lua_gettable()
4468 * perform the lookup.
4469 */
4470 lua_pushlstring(L, trash.str, hnl);
4471 lua_gettable(L, -2);
4472 type = lua_type(L, -1);
4473
4474 switch (type) {
4475 case LUA_TNIL:
4476 /* Table not found, create it. */
4477 lua_pop(L, 1); /* remove the nil value. */
4478 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4479 lua_newtable(L); /* create and push empty table. */
4480 lua_pushlstring(L, hv, hvl); /* push header value. */
4481 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4482 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4483 break;
4484
4485 case LUA_TTABLE:
4486 /* Entry found: push the value in the table. */
4487 len = lua_rawlen(L, -1);
4488 lua_pushlstring(L, hv, hvl); /* push header value. */
4489 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4490 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4491 break;
4492
4493 default:
4494 /* Other cases are errors. */
4495 hlua_pusherror(L, "internal error during the parsing of headers.");
4496 WILL_LJMP(lua_error(L));
4497 }
4498 }
4499
4500 return 1;
4501}
4502
4503__LJMP static int hlua_http_req_get_headers(lua_State *L)
4504{
4505 struct hlua_txn *htxn;
4506
4507 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4508 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4509
4510 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4511}
4512
4513__LJMP static int hlua_http_res_get_headers(lua_State *L)
4514{
4515 struct hlua_txn *htxn;
4516
4517 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4518 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4519
4520 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4521}
4522
4523/* This function replace full header, or just a value in
4524 * the request or in the response. It is a wrapper fir the
4525 * 4 following functions.
4526 */
4527__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4528 struct http_msg *msg, int action)
4529{
4530 size_t name_len;
4531 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4532 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4533 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4534 struct my_regex re;
4535
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004536 /* Check if a valid response is parsed */
4537 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4538 return 0;
4539
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004540 if (!regex_comp(reg, &re, 1, 1, NULL))
4541 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4542
4543 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4544 regex_free(&re);
4545 return 0;
4546}
4547
4548__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4549{
4550 struct hlua_txn *htxn;
4551
4552 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4553 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4554
4555 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4556}
4557
4558__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4559{
4560 struct hlua_txn *htxn;
4561
4562 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4563 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4564
4565 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4566}
4567
4568__LJMP static int hlua_http_req_rep_val(lua_State *L)
4569{
4570 struct hlua_txn *htxn;
4571
4572 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4573 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4574
4575 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4576}
4577
4578__LJMP static int hlua_http_res_rep_val(lua_State *L)
4579{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004580 struct hlua_txn *htxn;
4581
4582 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4583 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4584
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004585 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004586}
4587
4588/* This function deletes all the occurences of an header.
4589 * It is a wrapper for the 2 following functions.
4590 */
4591__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4592{
4593 size_t len;
4594 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4595 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004596 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004597
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004598 /* Check if a valid response is parsed */
4599 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4600 return 0;
4601
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004602 ctx.idx = 0;
4603 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4604 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4605 return 0;
4606}
4607
4608__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4609{
4610 struct hlua_txn *htxn;
4611
4612 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4613 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4614
Willy Tarreaueee5b512015-04-03 23:46:31 +02004615 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004616}
4617
4618__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4619{
4620 struct hlua_txn *htxn;
4621
4622 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4623 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4624
Willy Tarreaueee5b512015-04-03 23:46:31 +02004625 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004626}
4627
4628/* This function adds an header. It is a wrapper used by
4629 * the 2 following functions.
4630 */
4631__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4632{
4633 size_t name_len;
4634 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4635 size_t value_len;
4636 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4637 char *p;
4638
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004639 /* Check if a valid message is parsed */
4640 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4641 return 0;
4642
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004643 /* Check length. */
4644 trash.len = value_len + name_len + 2;
4645 if (trash.len > trash.size)
4646 return 0;
4647
4648 /* Creates the header string. */
4649 p = trash.str;
4650 memcpy(p, name, name_len);
4651 p += name_len;
4652 *p = ':';
4653 p++;
4654 *p = ' ';
4655 p++;
4656 memcpy(p, value, value_len);
4657
Willy Tarreaueee5b512015-04-03 23:46:31 +02004658 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004659 trash.str, trash.len) != 0);
4660
4661 return 0;
4662}
4663
4664__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4665{
4666 struct hlua_txn *htxn;
4667
4668 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4669 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4670
Willy Tarreaueee5b512015-04-03 23:46:31 +02004671 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004672}
4673
4674__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4675{
4676 struct hlua_txn *htxn;
4677
4678 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4679 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4680
Willy Tarreaueee5b512015-04-03 23:46:31 +02004681 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004682}
4683
4684static int hlua_http_req_set_hdr(lua_State *L)
4685{
4686 struct hlua_txn *htxn;
4687
4688 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4689 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4690
Willy Tarreaueee5b512015-04-03 23:46:31 +02004691 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4692 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004693}
4694
4695static int hlua_http_res_set_hdr(lua_State *L)
4696{
4697 struct hlua_txn *htxn;
4698
4699 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4700 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4701
Willy Tarreaueee5b512015-04-03 23:46:31 +02004702 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4703 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004704}
4705
4706/* This function set the method. */
4707static int hlua_http_req_set_meth(lua_State *L)
4708{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004709 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004710 size_t name_len;
4711 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004712
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004713 /* Check if a valid request is parsed */
4714 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4715 lua_pushboolean(L, 0);
4716 return 1;
4717 }
4718
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004719 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004720 return 1;
4721}
4722
4723/* This function set the method. */
4724static int hlua_http_req_set_path(lua_State *L)
4725{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004726 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004727 size_t name_len;
4728 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004729
4730 /* Check if a valid request is parsed */
4731 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4732 lua_pushboolean(L, 0);
4733 return 1;
4734 }
4735
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004736 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004737 return 1;
4738}
4739
4740/* This function set the query-string. */
4741static int hlua_http_req_set_query(lua_State *L)
4742{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004743 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004744 size_t name_len;
4745 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004746
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004747 /* Check if a valid request is parsed */
4748 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4749 lua_pushboolean(L, 0);
4750 return 1;
4751 }
4752
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004753 /* Check length. */
4754 if (name_len > trash.size - 1) {
4755 lua_pushboolean(L, 0);
4756 return 1;
4757 }
4758
4759 /* Add the mark question as prefix. */
4760 chunk_reset(&trash);
4761 trash.str[trash.len++] = '?';
4762 memcpy(trash.str + trash.len, name, name_len);
4763 trash.len += name_len;
4764
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004765 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004766 return 1;
4767}
4768
4769/* This function set the uri. */
4770static int hlua_http_req_set_uri(lua_State *L)
4771{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004772 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004773 size_t name_len;
4774 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004775
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004776 /* Check if a valid request is parsed */
4777 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4778 lua_pushboolean(L, 0);
4779 return 1;
4780 }
4781
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004782 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004783 return 1;
4784}
4785
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004786/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004787static int hlua_http_res_set_status(lua_State *L)
4788{
4789 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4790 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004791 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004792
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004793 /* Check if a valid response is parsed */
4794 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4795 return 0;
4796
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004797 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004798 return 0;
4799}
4800
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004801/*
4802 *
4803 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004804 * Class TXN
4805 *
4806 *
4807 */
4808
4809/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004810 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004811 */
4812__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4813{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004814 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004815}
4816
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004817__LJMP static int hlua_set_var(lua_State *L)
4818{
4819 struct hlua_txn *htxn;
4820 const char *name;
4821 size_t len;
4822 struct sample smp;
4823
4824 MAY_LJMP(check_args(L, 3, "set_var"));
4825
4826 /* It is useles to retrieve the stream, but this function
4827 * runs only in a stream context.
4828 */
4829 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4830 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4831
4832 /* Converts the third argument in a sample. */
4833 hlua_lua2smp(L, 3, &smp);
4834
4835 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01004836 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004837 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004838 return 0;
4839}
4840
Christopher Faulet85d79c92016-11-09 16:54:56 +01004841__LJMP static int hlua_unset_var(lua_State *L)
4842{
4843 struct hlua_txn *htxn;
4844 const char *name;
4845 size_t len;
4846 struct sample smp;
4847
4848 MAY_LJMP(check_args(L, 2, "unset_var"));
4849
4850 /* It is useles to retrieve the stream, but this function
4851 * runs only in a stream context.
4852 */
4853 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4854 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4855
4856 /* Unset the variable. */
4857 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
4858 vars_unset_by_name(name, len, &smp);
4859 return 0;
4860}
4861
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004862__LJMP static int hlua_get_var(lua_State *L)
4863{
4864 struct hlua_txn *htxn;
4865 const char *name;
4866 size_t len;
4867 struct sample smp;
4868
4869 MAY_LJMP(check_args(L, 2, "get_var"));
4870
4871 /* It is useles to retrieve the stream, but this function
4872 * runs only in a stream context.
4873 */
4874 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4875 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4876
Willy Tarreau7560dd42016-03-10 16:28:58 +01004877 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004878 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004879 lua_pushnil(L);
4880 return 1;
4881 }
4882
4883 return hlua_smp2lua(L, &smp);
4884}
4885
Willy Tarreau59551662015-03-10 14:23:13 +01004886__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004887{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004888 struct hlua *hlua;
4889
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004890 MAY_LJMP(check_args(L, 2, "set_priv"));
4891
Willy Tarreau87b09662015-04-03 00:22:06 +02004892 /* It is useles to retrieve the stream, but this function
4893 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004894 */
4895 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004896 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004897
4898 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004899 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004900
4901 /* Get and store new value. */
4902 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4903 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4904
4905 return 0;
4906}
4907
Willy Tarreau59551662015-03-10 14:23:13 +01004908__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004909{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004910 struct hlua *hlua;
4911
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004912 MAY_LJMP(check_args(L, 1, "get_priv"));
4913
Willy Tarreau87b09662015-04-03 00:22:06 +02004914 /* It is useles to retrieve the stream, but this function
4915 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004916 */
4917 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004918 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004919
4920 /* Push configuration index in the stack. */
4921 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4922
4923 return 1;
4924}
4925
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004926/* Create stack entry containing a class TXN. This function
4927 * return 0 if the stack does not contains free slots,
4928 * otherwise it returns 1.
4929 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004930static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004931{
Willy Tarreaude491382015-04-06 11:04:28 +02004932 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004933
4934 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004935 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004936 return 0;
4937
4938 /* NOTE: The allocation never fails. The failure
4939 * throw an error, and the function never returns.
4940 * if the throw is not avalaible, the process is aborted.
4941 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004942 /* Create the object: obj[0] = userdata. */
4943 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004944 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004945 lua_rawseti(L, -2, 0);
4946
Willy Tarreaude491382015-04-06 11:04:28 +02004947 htxn->s = s;
4948 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004949 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004950 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004951
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004952 /* Create the "f" field that contains a list of fetches. */
4953 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004954 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004955 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004956 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004957
4958 /* Create the "sf" field that contains a list of stringsafe fetches. */
4959 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004960 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004961 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004962 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004963
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004964 /* Create the "c" field that contains a list of converters. */
4965 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004966 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004967 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004968 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004969
4970 /* Create the "sc" field that contains a list of stringsafe converters. */
4971 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004972 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004973 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004974 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004975
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004976 /* Create the "req" field that contains the request channel object. */
4977 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004978 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004979 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004980 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004981
4982 /* Create the "res" field that contains the response channel object. */
4983 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004984 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004985 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004986 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004987
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004988 /* Creates the HTTP object is the current proxy allows http. */
4989 lua_pushstring(L, "http");
4990 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02004991 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004992 return 0;
4993 }
4994 else
4995 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004996 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004997
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004998 /* Pop a class sesison metatable and affect it to the userdata. */
4999 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5000 lua_setmetatable(L, -2);
5001
5002 return 1;
5003}
5004
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005005__LJMP static int hlua_txn_deflog(lua_State *L)
5006{
5007 const char *msg;
5008 struct hlua_txn *htxn;
5009
5010 MAY_LJMP(check_args(L, 2, "deflog"));
5011 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5012 msg = MAY_LJMP(luaL_checkstring(L, 2));
5013
5014 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5015 return 0;
5016}
5017
5018__LJMP static int hlua_txn_log(lua_State *L)
5019{
5020 int level;
5021 const char *msg;
5022 struct hlua_txn *htxn;
5023
5024 MAY_LJMP(check_args(L, 3, "log"));
5025 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5026 level = MAY_LJMP(luaL_checkinteger(L, 2));
5027 msg = MAY_LJMP(luaL_checkstring(L, 3));
5028
5029 if (level < 0 || level >= NB_LOG_LEVELS)
5030 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5031
5032 hlua_sendlog(htxn->s->be, level, msg);
5033 return 0;
5034}
5035
5036__LJMP static int hlua_txn_log_debug(lua_State *L)
5037{
5038 const char *msg;
5039 struct hlua_txn *htxn;
5040
5041 MAY_LJMP(check_args(L, 2, "Debug"));
5042 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5043 msg = MAY_LJMP(luaL_checkstring(L, 2));
5044 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5045 return 0;
5046}
5047
5048__LJMP static int hlua_txn_log_info(lua_State *L)
5049{
5050 const char *msg;
5051 struct hlua_txn *htxn;
5052
5053 MAY_LJMP(check_args(L, 2, "Info"));
5054 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5055 msg = MAY_LJMP(luaL_checkstring(L, 2));
5056 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5057 return 0;
5058}
5059
5060__LJMP static int hlua_txn_log_warning(lua_State *L)
5061{
5062 const char *msg;
5063 struct hlua_txn *htxn;
5064
5065 MAY_LJMP(check_args(L, 2, "Warning"));
5066 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5067 msg = MAY_LJMP(luaL_checkstring(L, 2));
5068 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5069 return 0;
5070}
5071
5072__LJMP static int hlua_txn_log_alert(lua_State *L)
5073{
5074 const char *msg;
5075 struct hlua_txn *htxn;
5076
5077 MAY_LJMP(check_args(L, 2, "Alert"));
5078 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5079 msg = MAY_LJMP(luaL_checkstring(L, 2));
5080 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5081 return 0;
5082}
5083
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005084__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5085{
5086 struct hlua_txn *htxn;
5087 int ll;
5088
5089 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5090 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5091 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5092
5093 if (ll < 0 || ll > 7)
5094 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5095
5096 htxn->s->logs.level = ll;
5097 return 0;
5098}
5099
5100__LJMP static int hlua_txn_set_tos(lua_State *L)
5101{
5102 struct hlua_txn *htxn;
5103 struct connection *cli_conn;
5104 int tos;
5105
5106 MAY_LJMP(check_args(L, 2, "set_tos"));
5107 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5108 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5109
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005110 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Vincent Bernat6e615892016-05-18 16:17:44 +02005111 inet_set_tos(cli_conn->t.sock.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005112
5113 return 0;
5114}
5115
5116__LJMP static int hlua_txn_set_mark(lua_State *L)
5117{
5118#ifdef SO_MARK
5119 struct hlua_txn *htxn;
5120 struct connection *cli_conn;
5121 int mark;
5122
5123 MAY_LJMP(check_args(L, 2, "set_mark"));
5124 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5125 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5126
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005127 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02005128 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005129#endif
5130 return 0;
5131}
5132
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005133/* This function is an Lua binding that send pending data
5134 * to the client, and close the stream interface.
5135 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005136__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005137{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005138 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005139 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005140 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005141
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005142 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005143 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005144 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005145
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005146 /* If the flags NOTERM is set, we cannot terminate the http
5147 * session, so we just end the execution of the current
5148 * lua code.
5149 */
5150 if (htxn->flags & HLUA_TXN_NOTERM) {
5151 WILL_LJMP(hlua_done(L));
5152 return 0;
5153 }
5154
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005155 ic = &htxn->s->req;
5156 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005157
Willy Tarreau630ef452015-08-28 10:06:15 +02005158 if (htxn->s->txn) {
5159 /* HTTP mode, let's stay in sync with the stream */
5160 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
5161 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5162 htxn->s->txn->req.sov = 0;
5163 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5164 oc->analysers = AN_RES_HTTP_XFER_BODY;
5165 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5166 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5167
Willy Tarreau630ef452015-08-28 10:06:15 +02005168 /* Note that if we want to support keep-alive, we need
5169 * to bypass the close/shutr_now calls below, but that
5170 * may only be done if the HTTP request was already
5171 * processed and the connection header is known (ie
5172 * not during TCP rules).
5173 */
5174 }
5175
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005176 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005177 channel_abort(ic);
5178 channel_auto_close(ic);
5179 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005180
5181 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005182 channel_auto_read(oc);
5183 channel_auto_close(oc);
5184 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005185
Willy Tarreau0458b082015-08-28 09:40:04 +02005186 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005187
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005188 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005189 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005190 return 0;
5191}
5192
5193__LJMP static int hlua_log(lua_State *L)
5194{
5195 int level;
5196 const char *msg;
5197
5198 MAY_LJMP(check_args(L, 2, "log"));
5199 level = MAY_LJMP(luaL_checkinteger(L, 1));
5200 msg = MAY_LJMP(luaL_checkstring(L, 2));
5201
5202 if (level < 0 || level >= NB_LOG_LEVELS)
5203 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5204
5205 hlua_sendlog(NULL, level, msg);
5206 return 0;
5207}
5208
5209__LJMP static int hlua_log_debug(lua_State *L)
5210{
5211 const char *msg;
5212
5213 MAY_LJMP(check_args(L, 1, "debug"));
5214 msg = MAY_LJMP(luaL_checkstring(L, 1));
5215 hlua_sendlog(NULL, LOG_DEBUG, msg);
5216 return 0;
5217}
5218
5219__LJMP static int hlua_log_info(lua_State *L)
5220{
5221 const char *msg;
5222
5223 MAY_LJMP(check_args(L, 1, "info"));
5224 msg = MAY_LJMP(luaL_checkstring(L, 1));
5225 hlua_sendlog(NULL, LOG_INFO, msg);
5226 return 0;
5227}
5228
5229__LJMP static int hlua_log_warning(lua_State *L)
5230{
5231 const char *msg;
5232
5233 MAY_LJMP(check_args(L, 1, "warning"));
5234 msg = MAY_LJMP(luaL_checkstring(L, 1));
5235 hlua_sendlog(NULL, LOG_WARNING, msg);
5236 return 0;
5237}
5238
5239__LJMP static int hlua_log_alert(lua_State *L)
5240{
5241 const char *msg;
5242
5243 MAY_LJMP(check_args(L, 1, "alert"));
5244 msg = MAY_LJMP(luaL_checkstring(L, 1));
5245 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005246 return 0;
5247}
5248
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005249__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005250{
5251 int wakeup_ms = lua_tointeger(L, -1);
5252 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005253 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005254 return 0;
5255}
5256
5257__LJMP static int hlua_sleep(lua_State *L)
5258{
5259 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005260 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005261
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005262 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005263
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005264 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005265 wakeup_ms = tick_add(now_ms, delay);
5266 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005267
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005268 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5269 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005270}
5271
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005272__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005273{
5274 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005275 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005276
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005277 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005278
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005279 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005280 wakeup_ms = tick_add(now_ms, delay);
5281 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005282
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005283 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5284 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005285}
5286
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005287/* This functionis an LUA binding. it permits to give back
5288 * the hand at the HAProxy scheduler. It is used when the
5289 * LUA processing consumes a lot of time.
5290 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005291__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005292{
5293 return 0;
5294}
5295
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005296__LJMP static int hlua_yield(lua_State *L)
5297{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005298 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5299 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005300}
5301
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005302/* This function change the nice of the currently executed
5303 * task. It is used set low or high priority at the current
5304 * task.
5305 */
Willy Tarreau59551662015-03-10 14:23:13 +01005306__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005307{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005308 struct hlua *hlua;
5309 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005310
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005311 MAY_LJMP(check_args(L, 1, "set_nice"));
5312 hlua = hlua_gethlua(L);
5313 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005314
5315 /* If he task is not set, I'm in a start mode. */
5316 if (!hlua || !hlua->task)
5317 return 0;
5318
5319 if (nice < -1024)
5320 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005321 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005322 nice = 1024;
5323
5324 hlua->task->nice = nice;
5325 return 0;
5326}
5327
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005328/* This function is used as a calback of a task. It is called by the
5329 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5330 * return an E_AGAIN signal, the emmiter of this signal must set a
5331 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005332 *
5333 * Task wrapper are longjmp safe because the only one Lua code
5334 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005335 */
5336static struct task *hlua_process_task(struct task *task)
5337{
5338 struct hlua *hlua = task->context;
5339 enum hlua_exec status;
5340
5341 /* We need to remove the task from the wait queue before executing
5342 * the Lua code because we don't know if it needs to wait for
5343 * another timer or not in the case of E_AGAIN.
5344 */
5345 task_delete(task);
5346
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005347 /* If it is the first call to the task, we must initialize the
5348 * execution timeouts.
5349 */
5350 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005351 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005352
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005353 /* Execute the Lua code. */
5354 status = hlua_ctx_resume(hlua, 1);
5355
5356 switch (status) {
5357 /* finished or yield */
5358 case HLUA_E_OK:
5359 hlua_ctx_destroy(hlua);
5360 task_delete(task);
5361 task_free(task);
5362 break;
5363
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005364 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5365 if (hlua->wake_time != TICK_ETERNITY)
5366 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005367 break;
5368
5369 /* finished with error. */
5370 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005371 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005372 hlua_ctx_destroy(hlua);
5373 task_delete(task);
5374 task_free(task);
5375 break;
5376
5377 case HLUA_E_ERR:
5378 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005379 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005380 hlua_ctx_destroy(hlua);
5381 task_delete(task);
5382 task_free(task);
5383 break;
5384 }
5385 return NULL;
5386}
5387
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005388/* This function is an LUA binding that register LUA function to be
5389 * executed after the HAProxy configuration parsing and before the
5390 * HAProxy scheduler starts. This function expect only one LUA
5391 * argument that is a function. This function returns nothing, but
5392 * throws if an error is encountered.
5393 */
5394__LJMP static int hlua_register_init(lua_State *L)
5395{
5396 struct hlua_init_function *init;
5397 int ref;
5398
5399 MAY_LJMP(check_args(L, 1, "register_init"));
5400
5401 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5402
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005403 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005404 if (!init)
5405 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5406
5407 init->function_ref = ref;
5408 LIST_ADDQ(&hlua_init_functions, &init->l);
5409 return 0;
5410}
5411
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005412/* This functio is an LUA binding. It permits to register a task
5413 * executed in parallel of the main HAroxy activity. The task is
5414 * created and it is set in the HAProxy scheduler. It can be called
5415 * from the "init" section, "post init" or during the runtime.
5416 *
5417 * Lua prototype:
5418 *
5419 * <none> core.register_task(<function>)
5420 */
5421static int hlua_register_task(lua_State *L)
5422{
5423 struct hlua *hlua;
5424 struct task *task;
5425 int ref;
5426
5427 MAY_LJMP(check_args(L, 1, "register_task"));
5428
5429 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5430
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005431 hlua = pool_alloc2(pool2_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005432 if (!hlua)
5433 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5434
5435 task = task_new();
5436 task->context = hlua;
5437 task->process = hlua_process_task;
5438
5439 if (!hlua_ctx_init(hlua, task))
5440 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5441
5442 /* Restore the function in the stack. */
5443 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5444 hlua->nargs = 0;
5445
5446 /* Schedule task. */
5447 task_schedule(task, now_ms);
5448
5449 return 0;
5450}
5451
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005452/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5453 * doesn't allow "yield" functions because the HAProxy engine cannot
5454 * resume converters.
5455 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005456static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005457{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005458 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005459 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005460 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005461
Willy Tarreaube508f12016-03-10 11:47:01 +01005462 if (!stream)
5463 return 0;
5464
Willy Tarreau87b09662015-04-03 00:22:06 +02005465 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005466 * Lua context can be not initialized. This behavior
5467 * permits to save performances because a systematic
5468 * Lua initialization cause 5% performances loss.
5469 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005470 if (!stream->hlua) {
5471 stream->hlua = pool_alloc2(pool2_hlua);
5472 if (!stream->hlua) {
5473 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5474 return 0;
5475 }
5476 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5477 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5478 return 0;
5479 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005480 }
5481
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005482 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005483 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005484
5485 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005486 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5487 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5488 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005489 else
5490 error = "critical error";
5491 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005492 return 0;
5493 }
5494
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005495 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005496 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005497 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005498 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005499 return 0;
5500 }
5501
5502 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005503 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005504
5505 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005506 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005507 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005508 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005509 return 0;
5510 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005511 hlua_smp2lua(stream->hlua->T, smp);
5512 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005513
5514 /* push keywords in the stack. */
5515 if (arg_p) {
5516 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005517 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005518 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005519 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005520 return 0;
5521 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005522 hlua_arg2lua(stream->hlua->T, arg_p);
5523 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005524 }
5525 }
5526
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005527 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005528 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005529
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005530 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005531 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005532 }
5533
5534 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005535 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005536 /* finished. */
5537 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005538 /* If the stack is empty, the function fails. */
5539 if (lua_gettop(stream->hlua->T) <= 0)
5540 return 0;
5541
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005542 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005543 hlua_lua2smp(stream->hlua->T, -1, smp);
5544 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005545 return 1;
5546
5547 /* yield. */
5548 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005549 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005550 return 0;
5551
5552 /* finished with error. */
5553 case HLUA_E_ERRMSG:
5554 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005555 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005556 fcn->name, lua_tostring(stream->hlua->T, -1));
5557 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005558 return 0;
5559
5560 case HLUA_E_ERR:
5561 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005562 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005563
5564 default:
5565 return 0;
5566 }
5567}
5568
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005569/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5570 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005571 * resume sample-fetches. This function will be called by the sample
5572 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005573 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005574static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5575 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005576{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005577 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005578 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005579 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005580 const struct chunk msg = { .len = 0 };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005581
Willy Tarreaube508f12016-03-10 11:47:01 +01005582 if (!stream)
5583 return 0;
5584
Willy Tarreau87b09662015-04-03 00:22:06 +02005585 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005586 * Lua context can be not initialized. This behavior
5587 * permits to save performances because a systematic
5588 * Lua initialization cause 5% performances loss.
5589 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005590 if (!stream->hlua) {
5591 stream->hlua = pool_alloc2(pool2_hlua);
5592 if (!stream->hlua) {
5593 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5594 return 0;
5595 }
5596 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5597 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5598 return 0;
5599 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005600 }
5601
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005602 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005603
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005604 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005605 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005606
5607 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005608 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5609 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5610 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005611 else
5612 error = "critical error";
5613 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005614 return 0;
5615 }
5616
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005617 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005618 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005619 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005620 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005621 return 0;
5622 }
5623
5624 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005625 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005626
5627 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005628 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005629 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005630 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005631 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005632 return 0;
5633 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005634 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005635
5636 /* push keywords in the stack. */
5637 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5638 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005639 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005640 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005641 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005642 return 0;
5643 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005644 hlua_arg2lua(stream->hlua->T, arg_p);
5645 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005646 }
5647
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005648 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005649 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005650
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005651 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005652 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005653 }
5654
5655 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005656 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005657 /* finished. */
5658 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005659 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005660 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005661 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005662 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005663 /* If the stack is empty, the function fails. */
5664 if (lua_gettop(stream->hlua->T) <= 0)
5665 return 0;
5666
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005667 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005668 hlua_lua2smp(stream->hlua->T, -1, smp);
5669 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005670
5671 /* Set the end of execution flag. */
5672 smp->flags &= ~SMP_F_MAY_CHANGE;
5673 return 1;
5674
5675 /* yield. */
5676 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005677 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005678 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005679 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005680 return 0;
5681
5682 /* finished with error. */
5683 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005684 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005685 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005686 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005687 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005688 fcn->name, lua_tostring(stream->hlua->T, -1));
5689 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005690 return 0;
5691
5692 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005693 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005694 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005695 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005696 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005697
5698 default:
5699 return 0;
5700 }
5701}
5702
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005703/* This function is an LUA binding used for registering
5704 * "sample-conv" functions. It expects a converter name used
5705 * in the haproxy configuration file, and an LUA function.
5706 */
5707__LJMP static int hlua_register_converters(lua_State *L)
5708{
5709 struct sample_conv_kw_list *sck;
5710 const char *name;
5711 int ref;
5712 int len;
5713 struct hlua_function *fcn;
5714
5715 MAY_LJMP(check_args(L, 2, "register_converters"));
5716
5717 /* First argument : converter name. */
5718 name = MAY_LJMP(luaL_checkstring(L, 1));
5719
5720 /* Second argument : lua function. */
5721 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5722
5723 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005724 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005725 if (!sck)
5726 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005727 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005728 if (!fcn)
5729 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5730
5731 /* Fill fcn. */
5732 fcn->name = strdup(name);
5733 if (!fcn->name)
5734 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5735 fcn->function_ref = ref;
5736
5737 /* List head */
5738 sck->list.n = sck->list.p = NULL;
5739
5740 /* converter keyword. */
5741 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005742 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005743 if (!sck->kw[0].kw)
5744 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5745
5746 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5747 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005748 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 +01005749 sck->kw[0].val_args = NULL;
5750 sck->kw[0].in_type = SMP_T_STR;
5751 sck->kw[0].out_type = SMP_T_STR;
5752 sck->kw[0].private = fcn;
5753
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005754 /* Register this new converter */
5755 sample_register_convs(sck);
5756
5757 return 0;
5758}
5759
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005760/* This fucntion is an LUA binding used for registering
5761 * "sample-fetch" functions. It expects a converter name used
5762 * in the haproxy configuration file, and an LUA function.
5763 */
5764__LJMP static int hlua_register_fetches(lua_State *L)
5765{
5766 const char *name;
5767 int ref;
5768 int len;
5769 struct sample_fetch_kw_list *sfk;
5770 struct hlua_function *fcn;
5771
5772 MAY_LJMP(check_args(L, 2, "register_fetches"));
5773
5774 /* First argument : sample-fetch name. */
5775 name = MAY_LJMP(luaL_checkstring(L, 1));
5776
5777 /* Second argument : lua function. */
5778 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5779
5780 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005781 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005782 if (!sfk)
5783 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005784 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005785 if (!fcn)
5786 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5787
5788 /* Fill fcn. */
5789 fcn->name = strdup(name);
5790 if (!fcn->name)
5791 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5792 fcn->function_ref = ref;
5793
5794 /* List head */
5795 sfk->list.n = sfk->list.p = NULL;
5796
5797 /* sample-fetch keyword. */
5798 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005799 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005800 if (!sfk->kw[0].kw)
5801 return luaL_error(L, "lua out of memory error.");
5802
5803 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5804 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005805 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 +01005806 sfk->kw[0].val_args = NULL;
5807 sfk->kw[0].out_type = SMP_T_STR;
5808 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5809 sfk->kw[0].val = 0;
5810 sfk->kw[0].private = fcn;
5811
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005812 /* Register this new fetch. */
5813 sample_register_fetches(sfk);
5814
5815 return 0;
5816}
5817
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005818/* This function is a wrapper to execute each LUA function declared
5819 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005820 * return ACT_RET_CONT if the processing is finished (with or without
5821 * error) and return ACT_RET_YIELD if the function must be called again
5822 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005823 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005824static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005825 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005826{
5827 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005828 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005829 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005830 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005831 const struct chunk msg = { .len = 0 };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005832
5833 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01005834 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
5835 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
5836 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
5837 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005838 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005839 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005840 return ACT_RET_CONT;
5841 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005842
Willy Tarreau87b09662015-04-03 00:22:06 +02005843 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005844 * Lua context can be not initialized. This behavior
5845 * permits to save performances because a systematic
5846 * Lua initialization cause 5% performances loss.
5847 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005848 if (!s->hlua) {
5849 s->hlua = pool_alloc2(pool2_hlua);
5850 if (!s->hlua) {
5851 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
5852 rule->arg.hlua_rule->fcn.name);
5853 return ACT_RET_CONT;
5854 }
5855 if (!hlua_ctx_init(s->hlua, s->task)) {
5856 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
5857 rule->arg.hlua_rule->fcn.name);
5858 return ACT_RET_CONT;
5859 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005860 }
5861
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005862 consistency_set(s, dir, &s->hlua->cons);
5863
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005864 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005865 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005866
5867 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005868 if (!SET_SAFE_LJMP(s->hlua->T)) {
5869 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
5870 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005871 else
5872 error = "critical error";
5873 SEND_ERR(px, "Lua function '%s': %s.\n",
5874 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005875 return ACT_RET_CONT;
5876 }
5877
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005878 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005879 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005880 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005881 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005882 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005883 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005884 }
5885
5886 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005887 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005888
Willy Tarreau87b09662015-04-03 00:22:06 +02005889 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005890 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005891 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005892 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005893 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005894 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005895 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005896 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005897
5898 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005899 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005900 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005901 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005902 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005903 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005904 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005905 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005906 lua_pushstring(s->hlua->T, *arg);
5907 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005908 }
5909
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005910 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005911 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005912
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005913 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005914 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005915 }
5916
5917 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005918 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005919 /* finished. */
5920 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005921 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005922 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005923 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005924 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005925 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005926 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005927 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005928
5929 /* yield. */
5930 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005931 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005932 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005933 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005934 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005935 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005936 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005937 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005938 /* Some actions can be wake up when a "write" event
5939 * is detected on a response channel. This is useful
5940 * only for actions targetted on the requests.
5941 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005942 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005943 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005944 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005945 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005946 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005947 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005948 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005949 /* We can quit the fcuntion without consistency check
5950 * because HAProxy is not able to manipulate data, it
5951 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005952 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005953
5954 /* finished with error. */
5955 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005956 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005957 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005958 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005959 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005960 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005961 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005962 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
5963 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005964 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005965
5966 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005967 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005968 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005969 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005970 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005971 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005972 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005973 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005974
5975 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005976 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005977 }
5978}
5979
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005980struct task *hlua_applet_wakeup(struct task *t)
5981{
5982 struct appctx *ctx = t->context;
5983 struct stream_interface *si = ctx->owner;
5984
5985 /* If the applet is wake up without any expected work, the sheduler
5986 * remove it from the run queue. This flag indicate that the applet
5987 * is waiting for write. If the buffer is full, the main processing
5988 * will send some data and after call the applet, otherwise it call
5989 * the applet ASAP.
5990 */
5991 si_applet_cant_put(si);
5992 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02005993 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02005994 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005995}
5996
5997static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5998{
5999 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006000 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006001 struct task *task;
6002 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006003 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006004
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006005 hlua = pool_alloc2(pool2_hlua);
6006 if (!hlua) {
6007 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6008 ctx->rule->arg.hlua_rule->fcn.name);
6009 return 0;
6010 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006011 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006012 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006013 ctx->ctx.hlua_apptcp.flags = 0;
6014
6015 /* Create task used by signal to wakeup applets. */
6016 task = task_new();
6017 if (!task) {
6018 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6019 ctx->rule->arg.hlua_rule->fcn.name);
6020 return 0;
6021 }
6022 task->nice = 0;
6023 task->context = ctx;
6024 task->process = hlua_applet_wakeup;
6025 ctx->ctx.hlua_apptcp.task = task;
6026
6027 /* In the execution wrappers linked with a stream, the
6028 * Lua context can be not initialized. This behavior
6029 * permits to save performances because a systematic
6030 * Lua initialization cause 5% performances loss.
6031 */
6032 if (!hlua_ctx_init(hlua, task)) {
6033 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6034 ctx->rule->arg.hlua_rule->fcn.name);
6035 return 0;
6036 }
6037
6038 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006039 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006040
6041 /* The following Lua calls can fail. */
6042 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006043 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6044 error = lua_tostring(hlua->T, -1);
6045 else
6046 error = "critical error";
6047 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6048 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006049 RESET_SAFE_LJMP(hlua->T);
6050 return 0;
6051 }
6052
6053 /* Check stack available size. */
6054 if (!lua_checkstack(hlua->T, 1)) {
6055 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6056 ctx->rule->arg.hlua_rule->fcn.name);
6057 RESET_SAFE_LJMP(hlua->T);
6058 return 0;
6059 }
6060
6061 /* Restore the function in the stack. */
6062 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6063
6064 /* Create and and push object stream in the stack. */
6065 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6066 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6067 ctx->rule->arg.hlua_rule->fcn.name);
6068 RESET_SAFE_LJMP(hlua->T);
6069 return 0;
6070 }
6071 hlua->nargs = 1;
6072
6073 /* push keywords in the stack. */
6074 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6075 if (!lua_checkstack(hlua->T, 1)) {
6076 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6077 ctx->rule->arg.hlua_rule->fcn.name);
6078 RESET_SAFE_LJMP(hlua->T);
6079 return 0;
6080 }
6081 lua_pushstring(hlua->T, *arg);
6082 hlua->nargs++;
6083 }
6084
6085 RESET_SAFE_LJMP(hlua->T);
6086
6087 /* Wakeup the applet ASAP. */
6088 si_applet_cant_get(si);
6089 si_applet_cant_put(si);
6090
6091 return 1;
6092}
6093
6094static void hlua_applet_tcp_fct(struct appctx *ctx)
6095{
6096 struct stream_interface *si = ctx->owner;
6097 struct stream *strm = si_strm(si);
6098 struct channel *res = si_ic(si);
6099 struct act_rule *rule = ctx->rule;
6100 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006101 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006102
6103 /* The applet execution is already done. */
6104 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
6105 return;
6106
6107 /* If the stream is disconnect or closed, ldo nothing. */
6108 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6109 return;
6110
6111 /* Execute the function. */
6112 switch (hlua_ctx_resume(hlua, 1)) {
6113 /* finished. */
6114 case HLUA_E_OK:
6115 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6116
6117 /* log time */
6118 strm->logs.tv_request = now;
6119
6120 /* eat the whole request */
6121 bo_skip(si_oc(si), si_ob(si)->o);
6122 res->flags |= CF_READ_NULL;
6123 si_shutr(si);
6124 return;
6125
6126 /* yield. */
6127 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006128 if (hlua->wake_time != TICK_ETERNITY)
6129 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006130 return;
6131
6132 /* finished with error. */
6133 case HLUA_E_ERRMSG:
6134 /* Display log. */
6135 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6136 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6137 lua_pop(hlua->T, 1);
6138 goto error;
6139
6140 case HLUA_E_ERR:
6141 /* Display log. */
6142 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6143 rule->arg.hlua_rule->fcn.name);
6144 goto error;
6145
6146 default:
6147 goto error;
6148 }
6149
6150error:
6151
6152 /* For all other cases, just close the stream. */
6153 si_shutw(si);
6154 si_shutr(si);
6155 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6156}
6157
6158static void hlua_applet_tcp_release(struct appctx *ctx)
6159{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006160 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006161 task_free(ctx->ctx.hlua_apptcp.task);
6162 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006163 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006164 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006165}
6166
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006167/* The function returns 1 if the initialisation is complete, 0 if
6168 * an errors occurs and -1 if more data are required for initializing
6169 * the applet.
6170 */
6171static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6172{
6173 struct stream_interface *si = ctx->owner;
6174 struct channel *req = si_oc(si);
6175 struct http_msg *msg;
6176 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006177 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006178 char **arg;
6179 struct hdr_ctx hdr;
6180 struct task *task;
6181 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006182 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006183
6184 /* Wait for a full HTTP request. */
6185 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6186 if (smp.flags & SMP_F_MAY_CHANGE)
6187 return -1;
6188 return 0;
6189 }
6190 txn = strm->txn;
6191 msg = &txn->req;
6192
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006193 /* We want two things in HTTP mode :
6194 * - enforce server-close mode if we were in keep-alive, so that the
6195 * applet is released after each response ;
6196 * - enable request body transfer to the applet in order to resync
6197 * with the response body.
6198 */
6199 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6200 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006201
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006202 hlua = pool_alloc2(pool2_hlua);
6203 if (!hlua) {
6204 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6205 ctx->rule->arg.hlua_rule->fcn.name);
6206 return 0;
6207 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006208 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006209 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006210 ctx->ctx.hlua_apphttp.left_bytes = -1;
6211 ctx->ctx.hlua_apphttp.flags = 0;
6212
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006213 if (txn->req.flags & HTTP_MSGF_VER_11)
6214 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6215
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006216 /* Create task used by signal to wakeup applets. */
6217 task = task_new();
6218 if (!task) {
6219 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6220 ctx->rule->arg.hlua_rule->fcn.name);
6221 return 0;
6222 }
6223 task->nice = 0;
6224 task->context = ctx;
6225 task->process = hlua_applet_wakeup;
6226 ctx->ctx.hlua_apphttp.task = task;
6227
6228 /* In the execution wrappers linked with a stream, the
6229 * Lua context can be not initialized. This behavior
6230 * permits to save performances because a systematic
6231 * Lua initialization cause 5% performances loss.
6232 */
6233 if (!hlua_ctx_init(hlua, task)) {
6234 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6235 ctx->rule->arg.hlua_rule->fcn.name);
6236 return 0;
6237 }
6238
6239 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006240 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006241
6242 /* The following Lua calls can fail. */
6243 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006244 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6245 error = lua_tostring(hlua->T, -1);
6246 else
6247 error = "critical error";
6248 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6249 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006250 return 0;
6251 }
6252
6253 /* Check stack available size. */
6254 if (!lua_checkstack(hlua->T, 1)) {
6255 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6256 ctx->rule->arg.hlua_rule->fcn.name);
6257 RESET_SAFE_LJMP(hlua->T);
6258 return 0;
6259 }
6260
6261 /* Restore the function in the stack. */
6262 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6263
6264 /* Create and and push object stream in the stack. */
6265 if (!hlua_applet_http_new(hlua->T, ctx)) {
6266 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6267 ctx->rule->arg.hlua_rule->fcn.name);
6268 RESET_SAFE_LJMP(hlua->T);
6269 return 0;
6270 }
6271 hlua->nargs = 1;
6272
6273 /* Look for a 100-continue expected. */
6274 if (msg->flags & HTTP_MSGF_VER_11) {
6275 hdr.idx = 0;
6276 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
6277 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6278 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6279 }
6280
6281 /* push keywords in the stack. */
6282 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6283 if (!lua_checkstack(hlua->T, 1)) {
6284 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6285 ctx->rule->arg.hlua_rule->fcn.name);
6286 RESET_SAFE_LJMP(hlua->T);
6287 return 0;
6288 }
6289 lua_pushstring(hlua->T, *arg);
6290 hlua->nargs++;
6291 }
6292
6293 RESET_SAFE_LJMP(hlua->T);
6294
6295 /* Wakeup the applet when data is ready for read. */
6296 si_applet_cant_get(si);
6297
6298 return 1;
6299}
6300
6301static void hlua_applet_http_fct(struct appctx *ctx)
6302{
6303 struct stream_interface *si = ctx->owner;
6304 struct stream *strm = si_strm(si);
6305 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006306 struct act_rule *rule = ctx->rule;
6307 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006308 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006309 char *blk1;
6310 int len1;
6311 char *blk2;
6312 int len2;
6313 int ret;
6314
6315 /* If the stream is disconnect or closed, ldo nothing. */
6316 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6317 return;
6318
6319 /* Set the currently running flag. */
6320 if (!HLUA_IS_RUNNING(hlua) &&
6321 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6322
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006323 /* Wait for full HTTP analysys. */
6324 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6325 si_applet_cant_get(si);
6326 return;
6327 }
6328
6329 /* Store the max amount of bytes that we can read. */
6330 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6331
6332 /* We need to flush the request header. This left the body
6333 * for the Lua.
6334 */
6335
6336 /* Read the maximum amount of data avalaible. */
6337 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
6338 if (ret == -1)
6339 return;
6340
6341 /* No data available, ask for more data. */
6342 if (ret == 1)
6343 len2 = 0;
6344 if (ret == 0)
6345 len1 = 0;
6346 if (len1 + len2 < strm->txn->req.eoh + 2) {
6347 si_applet_cant_get(si);
6348 return;
6349 }
6350
6351 /* skip the requests bytes. */
6352 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
6353 }
6354
6355 /* Executes The applet if it is not done. */
6356 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6357
6358 /* Execute the function. */
6359 switch (hlua_ctx_resume(hlua, 1)) {
6360 /* finished. */
6361 case HLUA_E_OK:
6362 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6363 break;
6364
6365 /* yield. */
6366 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006367 if (hlua->wake_time != TICK_ETERNITY)
6368 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006369 return;
6370
6371 /* finished with error. */
6372 case HLUA_E_ERRMSG:
6373 /* Display log. */
6374 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6375 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6376 lua_pop(hlua->T, 1);
6377 goto error;
6378
6379 case HLUA_E_ERR:
6380 /* Display log. */
6381 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6382 rule->arg.hlua_rule->fcn.name);
6383 goto error;
6384
6385 default:
6386 goto error;
6387 }
6388 }
6389
6390 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6391
6392 /* We must send the final chunk. */
6393 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6394 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6395
6396 /* sent last chunk at once. */
6397 ret = bi_putblk(res, "0\r\n\r\n", 5);
6398
6399 /* critical error. */
6400 if (ret == -2 || ret == -3) {
6401 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6402 rule->arg.hlua_rule->fcn.name);
6403 goto error;
6404 }
6405
6406 /* no enough space error. */
6407 if (ret == -1) {
6408 si_applet_cant_put(si);
6409 return;
6410 }
6411
6412 /* set the last chunk sent. */
6413 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6414 }
6415
6416 /* close the connection. */
6417
6418 /* status / log */
6419 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6420 strm->logs.tv_request = now;
6421
6422 /* eat the whole request */
6423 bo_skip(si_oc(si), si_ob(si)->o);
6424 res->flags |= CF_READ_NULL;
6425 si_shutr(si);
6426
6427 return;
6428 }
6429
6430error:
6431
6432 /* If we are in HTTP mode, and we are not send any
6433 * data, return a 500 server error in best effort:
6434 * if there are no room avalaible in the buffer,
6435 * just close the connection.
6436 */
6437 bi_putblk(res, error_500, strlen(error_500));
6438 if (!(strm->flags & SF_ERR_MASK))
6439 strm->flags |= SF_ERR_RESOURCE;
6440 si_shutw(si);
6441 si_shutr(si);
6442 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6443}
6444
6445static void hlua_applet_http_release(struct appctx *ctx)
6446{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006447 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006448 task_free(ctx->ctx.hlua_apphttp.task);
6449 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006450 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006451 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006452}
6453
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006454/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6455 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006456 *
6457 * This function can fail with an abort() due to an Lua critical error.
6458 * We are in the configuration parsing process of HAProxy, this abort() is
6459 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006460 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006461static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6462 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006463{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006464 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006465 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006466
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006467 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006468 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006469 if (!rule->arg.hlua_rule) {
6470 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006471 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006472 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006473
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006474 /* Memory for arguments. */
6475 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6476 if (!rule->arg.hlua_rule->args) {
6477 memprintf(err, "out of memory error");
6478 return ACT_RET_PRS_ERR;
6479 }
6480
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006481 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006482 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006483
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006484 /* Expect some arguments */
6485 for (i = 0; i < fcn->nargs; i++) {
6486 if (*args[i+1] == '\0') {
6487 memprintf(err, "expect %d arguments", fcn->nargs);
6488 return ACT_RET_PRS_ERR;
6489 }
6490 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6491 if (!rule->arg.hlua_rule->args[i]) {
6492 memprintf(err, "out of memory error");
6493 return ACT_RET_PRS_ERR;
6494 }
6495 (*cur_arg)++;
6496 }
6497 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006498
Thierry FOURNIER42148732015-09-02 17:17:33 +02006499 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006500 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006501 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006502}
6503
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006504static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6505 struct act_rule *rule, char **err)
6506{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006507 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006508
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006509 /* HTTP applets are forbidden in tcp-request rules.
6510 * HTTP applet request requires everything initilized by
6511 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6512 * The applet will be immediately initilized, but its before
6513 * the call of this analyzer.
6514 */
6515 if (rule->from != ACT_F_HTTP_REQ) {
6516 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6517 return ACT_RET_PRS_ERR;
6518 }
6519
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006520 /* Memory for the rule. */
6521 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6522 if (!rule->arg.hlua_rule) {
6523 memprintf(err, "out of memory error");
6524 return ACT_RET_PRS_ERR;
6525 }
6526
6527 /* Reference the Lua function and store the reference. */
6528 rule->arg.hlua_rule->fcn = *fcn;
6529
6530 /* TODO: later accept arguments. */
6531 rule->arg.hlua_rule->args = NULL;
6532
6533 /* Add applet pointer in the rule. */
6534 rule->applet.obj_type = OBJ_TYPE_APPLET;
6535 rule->applet.name = fcn->name;
6536 rule->applet.init = hlua_applet_http_init;
6537 rule->applet.fct = hlua_applet_http_fct;
6538 rule->applet.release = hlua_applet_http_release;
6539 rule->applet.timeout = hlua_timeout_applet;
6540
6541 return ACT_RET_PRS_OK;
6542}
6543
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006544/* This function is an LUA binding used for registering
6545 * "sample-conv" functions. It expects a converter name used
6546 * in the haproxy configuration file, and an LUA function.
6547 */
6548__LJMP static int hlua_register_action(lua_State *L)
6549{
6550 struct action_kw_list *akl;
6551 const char *name;
6552 int ref;
6553 int len;
6554 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006555 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006556
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006557 /* Initialise the number of expected arguments at 0. */
6558 nargs = 0;
6559
6560 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6561 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006562
6563 /* First argument : converter name. */
6564 name = MAY_LJMP(luaL_checkstring(L, 1));
6565
6566 /* Second argument : environment. */
6567 if (lua_type(L, 2) != LUA_TTABLE)
6568 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6569
6570 /* Third argument : lua function. */
6571 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6572
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006573 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6574 if (lua_gettop(L) >= 4)
6575 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6576
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006577 /* browse the second argulent as an array. */
6578 lua_pushnil(L);
6579 while (lua_next(L, 2) != 0) {
6580 if (lua_type(L, -1) != LUA_TSTRING)
6581 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6582
6583 /* Check required environment. Only accepted "http" or "tcp". */
6584 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006585 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006586 if (!akl)
6587 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006588 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006589 if (!fcn)
6590 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6591
6592 /* Fill fcn. */
6593 fcn->name = strdup(name);
6594 if (!fcn->name)
6595 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6596 fcn->function_ref = ref;
6597
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006598 /* Set the expected number od arguments. */
6599 fcn->nargs = nargs;
6600
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006601 /* List head */
6602 akl->list.n = akl->list.p = NULL;
6603
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006604 /* action keyword. */
6605 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006606 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006607 if (!akl->kw[0].kw)
6608 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6609
6610 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6611
6612 akl->kw[0].match_pfx = 0;
6613 akl->kw[0].private = fcn;
6614 akl->kw[0].parse = action_register_lua;
6615
6616 /* select the action registering point. */
6617 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6618 tcp_req_cont_keywords_register(akl);
6619 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6620 tcp_res_cont_keywords_register(akl);
6621 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6622 http_req_keywords_register(akl);
6623 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6624 http_res_keywords_register(akl);
6625 else
6626 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6627 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6628 "are expected.", lua_tostring(L, -1)));
6629
6630 /* pop the environment string. */
6631 lua_pop(L, 1);
6632 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006633 return ACT_RET_PRS_OK;
6634}
6635
6636static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6637 struct act_rule *rule, char **err)
6638{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006639 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006640
6641 /* Memory for the rule. */
6642 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6643 if (!rule->arg.hlua_rule) {
6644 memprintf(err, "out of memory error");
6645 return ACT_RET_PRS_ERR;
6646 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006647
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006648 /* Reference the Lua function and store the reference. */
6649 rule->arg.hlua_rule->fcn = *fcn;
6650
6651 /* TODO: later accept arguments. */
6652 rule->arg.hlua_rule->args = NULL;
6653
6654 /* Add applet pointer in the rule. */
6655 rule->applet.obj_type = OBJ_TYPE_APPLET;
6656 rule->applet.name = fcn->name;
6657 rule->applet.init = hlua_applet_tcp_init;
6658 rule->applet.fct = hlua_applet_tcp_fct;
6659 rule->applet.release = hlua_applet_tcp_release;
6660 rule->applet.timeout = hlua_timeout_applet;
6661
6662 return 0;
6663}
6664
6665/* This function is an LUA binding used for registering
6666 * "sample-conv" functions. It expects a converter name used
6667 * in the haproxy configuration file, and an LUA function.
6668 */
6669__LJMP static int hlua_register_service(lua_State *L)
6670{
6671 struct action_kw_list *akl;
6672 const char *name;
6673 const char *env;
6674 int ref;
6675 int len;
6676 struct hlua_function *fcn;
6677
6678 MAY_LJMP(check_args(L, 3, "register_service"));
6679
6680 /* First argument : converter name. */
6681 name = MAY_LJMP(luaL_checkstring(L, 1));
6682
6683 /* Second argument : environment. */
6684 env = MAY_LJMP(luaL_checkstring(L, 2));
6685
6686 /* Third argument : lua function. */
6687 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6688
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006689 /* Allocate and fill the sample fetch keyword struct. */
6690 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6691 if (!akl)
6692 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6693 fcn = calloc(1, sizeof(*fcn));
6694 if (!fcn)
6695 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6696
6697 /* Fill fcn. */
6698 len = strlen("<lua.>") + strlen(name) + 1;
6699 fcn->name = calloc(1, len);
6700 if (!fcn->name)
6701 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6702 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6703 fcn->function_ref = ref;
6704
6705 /* List head */
6706 akl->list.n = akl->list.p = NULL;
6707
6708 /* converter keyword. */
6709 len = strlen("lua.") + strlen(name) + 1;
6710 akl->kw[0].kw = calloc(1, len);
6711 if (!akl->kw[0].kw)
6712 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6713
6714 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6715
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01006716 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006717 if (strcmp(env, "tcp") == 0)
6718 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006719 else if (strcmp(env, "http") == 0)
6720 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006721 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006722 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6723 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006724
6725 akl->kw[0].match_pfx = 0;
6726 akl->kw[0].private = fcn;
6727
6728 /* End of array. */
6729 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6730
6731 /* Register this new converter */
6732 service_keywords_register(akl);
6733
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006734 return 0;
6735}
6736
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006737/* This function initialises Lua cli handler. It copies the
6738 * arguments in the Lua stack and create channel IO objects.
6739 */
6740static int hlua_cli_parse_fct(char **args, struct appctx *appctx, void *private)
6741{
6742 struct hlua *hlua;
6743 struct hlua_function *fcn;
6744 int i;
6745 const char *error;
6746
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006747 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006748 appctx->ctx.hlua_cli.fcn = private;
6749
6750 hlua = pool_alloc2(pool2_hlua);
6751 if (!hlua) {
6752 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006753 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006754 }
6755 HLUA_INIT(hlua);
6756 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006757
6758 /* Create task used by signal to wakeup applets.
6759 * We use the same wakeup fonction than the Lua applet_tcp and
6760 * applet_http. It is absolutely compatible.
6761 */
6762 appctx->ctx.hlua_cli.task = task_new();
6763 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01006764 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006765 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006766 }
6767 appctx->ctx.hlua_cli.task->nice = 0;
6768 appctx->ctx.hlua_cli.task->context = appctx;
6769 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
6770
6771 /* Initialises the Lua context */
6772 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
6773 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006774 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006775 }
6776
6777 /* The following Lua calls can fail. */
6778 if (!SET_SAFE_LJMP(hlua->T)) {
6779 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6780 error = lua_tostring(hlua->T, -1);
6781 else
6782 error = "critical error";
6783 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
6784 goto error;
6785 }
6786
6787 /* Check stack available size. */
6788 if (!lua_checkstack(hlua->T, 2)) {
6789 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6790 goto error;
6791 }
6792
6793 /* Restore the function in the stack. */
6794 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
6795
6796 /* Once the arguments parsed, the CLI is like an AppletTCP,
6797 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006798 */
6799 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
6800 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6801 goto error;
6802 }
6803 hlua->nargs = 1;
6804
6805 /* push keywords in the stack. */
6806 for (i = 0; *args[i]; i++) {
6807 /* Check stack available size. */
6808 if (!lua_checkstack(hlua->T, 1)) {
6809 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6810 goto error;
6811 }
6812 lua_pushstring(hlua->T, args[i]);
6813 hlua->nargs++;
6814 }
6815
6816 /* We must initialize the execution timeouts. */
6817 hlua->max_time = hlua_timeout_session;
6818
6819 /* At this point the execution is safe. */
6820 RESET_SAFE_LJMP(hlua->T);
6821
6822 /* It's ok */
6823 return 0;
6824
6825 /* It's not ok. */
6826error:
6827 RESET_SAFE_LJMP(hlua->T);
6828 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006829 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006830 return 1;
6831}
6832
6833static int hlua_cli_io_handler_fct(struct appctx *appctx)
6834{
6835 struct hlua *hlua;
6836 struct stream_interface *si;
6837 struct hlua_function *fcn;
6838
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006839 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006840 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01006841 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006842
6843 /* If the stream is disconnect or closed, ldo nothing. */
6844 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6845 return 1;
6846
6847 /* Execute the function. */
6848 switch (hlua_ctx_resume(hlua, 1)) {
6849
6850 /* finished. */
6851 case HLUA_E_OK:
6852 return 1;
6853
6854 /* yield. */
6855 case HLUA_E_AGAIN:
6856 /* We want write. */
6857 if (HLUA_IS_WAKERESWR(hlua))
6858 si_applet_cant_put(si);
6859 /* Set the timeout. */
6860 if (hlua->wake_time != TICK_ETERNITY)
6861 task_schedule(hlua->task, hlua->wake_time);
6862 return 0;
6863
6864 /* finished with error. */
6865 case HLUA_E_ERRMSG:
6866 /* Display log. */
6867 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
6868 fcn->name, lua_tostring(hlua->T, -1));
6869 lua_pop(hlua->T, 1);
6870 return 1;
6871
6872 case HLUA_E_ERR:
6873 /* Display log. */
6874 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
6875 fcn->name);
6876 return 1;
6877
6878 default:
6879 return 1;
6880 }
6881
6882 return 1;
6883}
6884
6885static void hlua_cli_io_release_fct(struct appctx *appctx)
6886{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006887 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006888 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006889}
6890
6891/* This function is an LUA binding used for registering
6892 * new keywords in the cli. It expects a list of keywords
6893 * which are the "path". It is limited to 5 keywords. A
6894 * description of the command, a function to be executed
6895 * for the parsing and a function for io handlers.
6896 */
6897__LJMP static int hlua_register_cli(lua_State *L)
6898{
6899 struct cli_kw_list *cli_kws;
6900 const char *message;
6901 int ref_io;
6902 int len;
6903 struct hlua_function *fcn;
6904 int index;
6905 int i;
6906
6907 MAY_LJMP(check_args(L, 3, "register_cli"));
6908
6909 /* First argument : an array of maximum 5 keywords. */
6910 if (!lua_istable(L, 1))
6911 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
6912
6913 /* Second argument : string with contextual message. */
6914 message = MAY_LJMP(luaL_checkstring(L, 2));
6915
6916 /* Third and fourth argument : lua function. */
6917 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
6918
6919 /* Allocate and fill the sample fetch keyword struct. */
6920 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
6921 if (!cli_kws)
6922 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6923 fcn = calloc(1, sizeof(*fcn));
6924 if (!fcn)
6925 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6926
6927 /* Fill path. */
6928 index = 0;
6929 lua_pushnil(L);
6930 while(lua_next(L, 1) != 0) {
6931 if (index >= 5)
6932 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
6933 if (lua_type(L, -1) != LUA_TSTRING)
6934 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
6935 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
6936 if (!cli_kws->kw[0].str_kw[index])
6937 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6938 index++;
6939 lua_pop(L, 1);
6940 }
6941
6942 /* Copy help message. */
6943 cli_kws->kw[0].usage = strdup(message);
6944 if (!cli_kws->kw[0].usage)
6945 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6946
6947 /* Fill fcn io handler. */
6948 len = strlen("<lua.cli>") + 1;
6949 for (i = 0; i < index; i++)
6950 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
6951 fcn->name = calloc(1, len);
6952 if (!fcn->name)
6953 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6954 strncat((char *)fcn->name, "<lua.cli", len);
6955 for (i = 0; i < index; i++) {
6956 strncat((char *)fcn->name, ".", len);
6957 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
6958 }
6959 strncat((char *)fcn->name, ">", len);
6960 fcn->function_ref = ref_io;
6961
6962 /* Fill last entries. */
6963 cli_kws->kw[0].private = fcn;
6964 cli_kws->kw[0].parse = hlua_cli_parse_fct;
6965 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
6966 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
6967
6968 /* Register this new converter */
6969 cli_register_kw(cli_kws);
6970
6971 return 0;
6972}
6973
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006974static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
6975 struct proxy *defpx, const char *file, int line,
6976 char **err, unsigned int *timeout)
6977{
6978 const char *error;
6979
6980 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
6981 if (error && *error != '\0') {
6982 memprintf(err, "%s: invalid timeout", args[0]);
6983 return -1;
6984 }
6985 return 0;
6986}
6987
6988static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
6989 struct proxy *defpx, const char *file, int line,
6990 char **err)
6991{
6992 return hlua_read_timeout(args, section_type, curpx, defpx,
6993 file, line, err, &hlua_timeout_session);
6994}
6995
6996static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
6997 struct proxy *defpx, const char *file, int line,
6998 char **err)
6999{
7000 return hlua_read_timeout(args, section_type, curpx, defpx,
7001 file, line, err, &hlua_timeout_task);
7002}
7003
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007004static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7005 struct proxy *defpx, const char *file, int line,
7006 char **err)
7007{
7008 return hlua_read_timeout(args, section_type, curpx, defpx,
7009 file, line, err, &hlua_timeout_applet);
7010}
7011
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007012static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7013 struct proxy *defpx, const char *file, int line,
7014 char **err)
7015{
7016 char *error;
7017
7018 hlua_nb_instruction = strtoll(args[1], &error, 10);
7019 if (*error != '\0') {
7020 memprintf(err, "%s: invalid number", args[0]);
7021 return -1;
7022 }
7023 return 0;
7024}
7025
Willy Tarreau32f61e22015-03-18 17:54:59 +01007026static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7027 struct proxy *defpx, const char *file, int line,
7028 char **err)
7029{
7030 char *error;
7031
7032 if (*(args[1]) == 0) {
7033 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7034 return -1;
7035 }
7036 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7037 if (*error != '\0') {
7038 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7039 return -1;
7040 }
7041 return 0;
7042}
7043
7044
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007045/* This function is called by the main configuration key "lua-load". It loads and
7046 * execute an lua file during the parsing of the HAProxy configuration file. It is
7047 * the main lua entry point.
7048 *
7049 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7050 * occured, otherwise it returns 0.
7051 *
7052 * In some error case, LUA set an error message in top of the stack. This function
7053 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007054 *
7055 * This function can fail with an abort() due to an Lua critical error.
7056 * We are in the configuration parsing process of HAProxy, this abort() is
7057 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007058 */
7059static int hlua_load(char **args, int section_type, struct proxy *curpx,
7060 struct proxy *defpx, const char *file, int line,
7061 char **err)
7062{
7063 int error;
7064
7065 /* Just load and compile the file. */
7066 error = luaL_loadfile(gL.T, args[1]);
7067 if (error) {
7068 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
7069 lua_pop(gL.T, 1);
7070 return -1;
7071 }
7072
7073 /* If no syntax error where detected, execute the code. */
7074 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7075 switch (error) {
7076 case LUA_OK:
7077 break;
7078 case LUA_ERRRUN:
7079 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
7080 lua_pop(gL.T, 1);
7081 return -1;
7082 case LUA_ERRMEM:
7083 memprintf(err, "lua out of memory error\n");
7084 return -1;
7085 case LUA_ERRERR:
7086 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
7087 lua_pop(gL.T, 1);
7088 return -1;
7089 case LUA_ERRGCMM:
7090 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
7091 lua_pop(gL.T, 1);
7092 return -1;
7093 default:
7094 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
7095 lua_pop(gL.T, 1);
7096 return -1;
7097 }
7098
7099 return 0;
7100}
7101
7102/* configuration keywords declaration */
7103static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007104 { CFG_GLOBAL, "lua-load", hlua_load },
7105 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7106 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007107 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007108 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007109 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007110 { 0, NULL, NULL },
7111}};
7112
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007113/* This function can fail with an abort() due to an Lua critical error.
7114 * We are in the initialisation process of HAProxy, this abort() is
7115 * tolerated.
7116 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007117int hlua_post_init()
7118{
7119 struct hlua_init_function *init;
7120 const char *msg;
7121 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007122 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007123
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007124 /* Call post initialisation function in safe environement. */
7125 if (!SET_SAFE_LJMP(gL.T)) {
7126 if (lua_type(gL.T, -1) == LUA_TSTRING)
7127 error = lua_tostring(gL.T, -1);
7128 else
7129 error = "critical error";
7130 fprintf(stderr, "Lua post-init: %s.\n", error);
7131 exit(1);
7132 }
7133 hlua_fcn_post_init(gL.T);
7134 RESET_SAFE_LJMP(gL.T);
7135
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007136 list_for_each_entry(init, &hlua_init_functions, l) {
7137 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7138 ret = hlua_ctx_resume(&gL, 0);
7139 switch (ret) {
7140 case HLUA_E_OK:
7141 lua_pop(gL.T, -1);
7142 return 1;
7143 case HLUA_E_AGAIN:
7144 Alert("lua init: yield not allowed.\n");
7145 return 0;
7146 case HLUA_E_ERRMSG:
7147 msg = lua_tostring(gL.T, -1);
7148 Alert("lua init: %s.\n", msg);
7149 return 0;
7150 case HLUA_E_ERR:
7151 default:
7152 Alert("lua init: unknown runtime error.\n");
7153 return 0;
7154 }
7155 }
7156 return 1;
7157}
7158
Willy Tarreau32f61e22015-03-18 17:54:59 +01007159/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7160 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7161 * is the previously allocated size or the kind of object in case of a new
7162 * allocation. <nsize> is the requested new size.
7163 */
7164static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7165{
7166 struct hlua_mem_allocator *zone = ud;
7167
7168 if (nsize == 0) {
7169 /* it's a free */
7170 if (ptr)
7171 zone->allocated -= osize;
7172 free(ptr);
7173 return NULL;
7174 }
7175
7176 if (!ptr) {
7177 /* it's a new allocation */
7178 if (zone->limit && zone->allocated + nsize > zone->limit)
7179 return NULL;
7180
7181 ptr = malloc(nsize);
7182 if (ptr)
7183 zone->allocated += nsize;
7184 return ptr;
7185 }
7186
7187 /* it's a realloc */
7188 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7189 return NULL;
7190
7191 ptr = realloc(ptr, nsize);
7192 if (ptr)
7193 zone->allocated += nsize - osize;
7194 return ptr;
7195}
7196
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007197/* Ithis function can fail with an abort() due to an Lua critical error.
7198 * We are in the initialisation process of HAProxy, this abort() is
7199 * tolerated.
7200 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007201void hlua_init(void)
7202{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007203 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007204 int idx;
7205 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007206 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007207 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007208 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007209#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007210 struct srv_kw *kw;
7211 int tmp_error;
7212 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007213 char *args[] = { /* SSL client configuration. */
7214 "ssl",
7215 "verify",
7216 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007217 NULL
7218 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007219#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007220
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007221 /* Initialise struct hlua and com signals pool */
7222 pool2_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007223 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
7224
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007225 /* Register configuration keywords. */
7226 cfg_register_keywords(&cfg_kws);
7227
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007228 /* Init main lua stack. */
7229 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007230 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007231 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007232 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007233 hlua_sethlua(&gL);
7234 gL.Tref = LUA_REFNIL;
7235 gL.task = NULL;
7236
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007237 /* From this point, until the end of the initialisation fucntion,
7238 * the Lua function can fail with an abort. We are in the initialisation
7239 * process of HAProxy, this abort() is tolerated.
7240 */
7241
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007242 /* Initialise lua. */
7243 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007244
Thierry Fournier75933d42016-01-21 09:30:18 +01007245 /* Set safe environment for the initialisation. */
7246 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007247 if (lua_type(gL.T, -1) == LUA_TSTRING)
7248 error_msg = lua_tostring(gL.T, -1);
7249 else
7250 error_msg = "critical error";
7251 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007252 exit(1);
7253 }
7254
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007255 /*
7256 *
7257 * Create "core" object.
7258 *
7259 */
7260
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007261 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007262 lua_newtable(gL.T);
7263
7264 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007265 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007266 hlua_class_const_int(gL.T, log_levels[i], i);
7267
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007268 /* Register special functions. */
7269 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007270 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007271 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007272 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007273 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007274 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007275 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007276 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007277 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007278 hlua_class_function(gL.T, "sleep", hlua_sleep);
7279 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007280 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7281 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7282 hlua_class_function(gL.T, "set_map", hlua_set_map);
7283 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007284 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007285 hlua_class_function(gL.T, "log", hlua_log);
7286 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7287 hlua_class_function(gL.T, "Info", hlua_log_info);
7288 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7289 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007290 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007291 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007292
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007293 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007294
7295 /*
7296 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007297 * Register class Map
7298 *
7299 */
7300
7301 /* This table entry is the object "Map" base. */
7302 lua_newtable(gL.T);
7303
7304 /* register pattern types. */
7305 for (i=0; i<PAT_MATCH_NUM; i++)
7306 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007307 for (i=0; i<PAT_MATCH_NUM; i++) {
7308 snprintf(trash.str, trash.size, "_%s", pat_match_names[i]);
7309 hlua_class_const_int(gL.T, trash.str, i);
7310 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007311
7312 /* register constructor. */
7313 hlua_class_function(gL.T, "new", hlua_map_new);
7314
7315 /* Create and fill the metatable. */
7316 lua_newtable(gL.T);
7317
7318 /* Create and fille the __index entry. */
7319 lua_pushstring(gL.T, "__index");
7320 lua_newtable(gL.T);
7321
7322 /* Register . */
7323 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7324 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7325
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007326 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007327
Thierry Fournier45e78d72016-02-19 18:34:46 +01007328 /* Register previous table in the registry with reference and named entry.
7329 * The function hlua_register_metatable() pops the stack, so we
7330 * previously create a copy of the table.
7331 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007332 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007333 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007334
7335 /* Assign the metatable to the mai Map object. */
7336 lua_setmetatable(gL.T, -2);
7337
7338 /* Set a name to the table. */
7339 lua_setglobal(gL.T, "Map");
7340
7341 /*
7342 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007343 * Register class Channel
7344 *
7345 */
7346
7347 /* Create and fill the metatable. */
7348 lua_newtable(gL.T);
7349
7350 /* Create and fille the __index entry. */
7351 lua_pushstring(gL.T, "__index");
7352 lua_newtable(gL.T);
7353
7354 /* Register . */
7355 hlua_class_function(gL.T, "get", hlua_channel_get);
7356 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7357 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7358 hlua_class_function(gL.T, "set", hlua_channel_set);
7359 hlua_class_function(gL.T, "append", hlua_channel_append);
7360 hlua_class_function(gL.T, "send", hlua_channel_send);
7361 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7362 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7363 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007364 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007365
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007366 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007367
7368 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007369 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007370
7371 /*
7372 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007373 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007374 *
7375 */
7376
7377 /* Create and fill the metatable. */
7378 lua_newtable(gL.T);
7379
7380 /* Create and fille the __index entry. */
7381 lua_pushstring(gL.T, "__index");
7382 lua_newtable(gL.T);
7383
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007384 /* Browse existing fetches and create the associated
7385 * object method.
7386 */
7387 sf = NULL;
7388 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7389
7390 /* Dont register the keywork if the arguments check function are
7391 * not safe during the runtime.
7392 */
7393 if ((sf->val_args != NULL) &&
7394 (sf->val_args != val_payload_lv) &&
7395 (sf->val_args != val_hdr))
7396 continue;
7397
7398 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7399 * by an underscore.
7400 */
7401 strncpy(trash.str, sf->kw, trash.size);
7402 trash.str[trash.size - 1] = '\0';
7403 for (p = trash.str; *p; p++)
7404 if (*p == '.' || *p == '-' || *p == '+')
7405 *p = '_';
7406
7407 /* Register the function. */
7408 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007409 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007410 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007411 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007412 }
7413
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007414 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007415
7416 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007417 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007418
7419 /*
7420 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007421 * Register class Converters
7422 *
7423 */
7424
7425 /* Create and fill the metatable. */
7426 lua_newtable(gL.T);
7427
7428 /* Create and fill the __index entry. */
7429 lua_pushstring(gL.T, "__index");
7430 lua_newtable(gL.T);
7431
7432 /* Browse existing converters and create the associated
7433 * object method.
7434 */
7435 sc = NULL;
7436 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7437 /* Dont register the keywork if the arguments check function are
7438 * not safe during the runtime.
7439 */
7440 if (sc->val_args != NULL)
7441 continue;
7442
7443 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7444 * by an underscore.
7445 */
7446 strncpy(trash.str, sc->kw, trash.size);
7447 trash.str[trash.size - 1] = '\0';
7448 for (p = trash.str; *p; p++)
7449 if (*p == '.' || *p == '-' || *p == '+')
7450 *p = '_';
7451
7452 /* Register the function. */
7453 lua_pushstring(gL.T, trash.str);
7454 lua_pushlightuserdata(gL.T, sc);
7455 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007456 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007457 }
7458
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007459 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007460
7461 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007462 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007463
7464 /*
7465 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007466 * Register class HTTP
7467 *
7468 */
7469
7470 /* Create and fill the metatable. */
7471 lua_newtable(gL.T);
7472
7473 /* Create and fille the __index entry. */
7474 lua_pushstring(gL.T, "__index");
7475 lua_newtable(gL.T);
7476
7477 /* Register Lua functions. */
7478 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7479 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7480 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7481 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7482 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7483 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7484 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7485 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7486 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7487 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7488
7489 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7490 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7491 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7492 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7493 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7494 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007495 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007496
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007497 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007498
7499 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007500 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007501
7502 /*
7503 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007504 * Register class AppletTCP
7505 *
7506 */
7507
7508 /* Create and fill the metatable. */
7509 lua_newtable(gL.T);
7510
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007511 /* Create and fille the __index entry. */
7512 lua_pushstring(gL.T, "__index");
7513 lua_newtable(gL.T);
7514
7515 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007516 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7517 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7518 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7519 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7520 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007521 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7522 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7523 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007524
7525 lua_settable(gL.T, -3);
7526
7527 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007528 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007529
7530 /*
7531 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007532 * Register class AppletHTTP
7533 *
7534 */
7535
7536 /* Create and fill the metatable. */
7537 lua_newtable(gL.T);
7538
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007539 /* Create and fille the __index entry. */
7540 lua_pushstring(gL.T, "__index");
7541 lua_newtable(gL.T);
7542
7543 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007544 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7545 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007546 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7547 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7548 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007549 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7550 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7551 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7552 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7553 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7554 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7555
7556 lua_settable(gL.T, -3);
7557
7558 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007559 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007560
7561 /*
7562 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007563 * Register class TXN
7564 *
7565 */
7566
7567 /* Create and fill the metatable. */
7568 lua_newtable(gL.T);
7569
7570 /* Create and fille the __index entry. */
7571 lua_pushstring(gL.T, "__index");
7572 lua_newtable(gL.T);
7573
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007574 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007575 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7576 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007577 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007578 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007579 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007580 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007581 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7582 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7583 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007584 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7585 hlua_class_function(gL.T, "log", hlua_txn_log);
7586 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7587 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7588 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7589 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007590
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007591 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007592
7593 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007594 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007595
7596 /*
7597 *
7598 * Register class Socket
7599 *
7600 */
7601
7602 /* Create and fill the metatable. */
7603 lua_newtable(gL.T);
7604
7605 /* Create and fille the __index entry. */
7606 lua_pushstring(gL.T, "__index");
7607 lua_newtable(gL.T);
7608
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007609#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007610 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007611#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007612 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7613 hlua_class_function(gL.T, "send", hlua_socket_send);
7614 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7615 hlua_class_function(gL.T, "close", hlua_socket_close);
7616 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7617 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7618 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7619 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7620
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007621 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007622
7623 /* Register the garbage collector entry. */
7624 lua_pushstring(gL.T, "__gc");
7625 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007626 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007627
7628 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007629 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007630
7631 /* Proxy and server configuration initialisation. */
7632 memset(&socket_proxy, 0, sizeof(socket_proxy));
7633 init_new_proxy(&socket_proxy);
7634 socket_proxy.parent = NULL;
7635 socket_proxy.last_change = now.tv_sec;
7636 socket_proxy.id = "LUA-SOCKET";
7637 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7638 socket_proxy.maxconn = 0;
7639 socket_proxy.accept = NULL;
7640 socket_proxy.options2 |= PR_O2_INDEPSTR;
7641 socket_proxy.srv = NULL;
7642 socket_proxy.conn_retries = 0;
7643 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7644
7645 /* Init TCP server: unchanged parameters */
7646 memset(&socket_tcp, 0, sizeof(socket_tcp));
7647 socket_tcp.next = NULL;
7648 socket_tcp.proxy = &socket_proxy;
7649 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7650 LIST_INIT(&socket_tcp.actconns);
7651 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007652 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007653 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007654 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007655 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
7656 socket_tcp.last_change = 0;
7657 socket_tcp.id = "LUA-TCP-CONN";
7658 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7659 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7660 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7661
7662 /* XXX: Copy default parameter from default server,
7663 * but the default server is not initialized.
7664 */
7665 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7666 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7667 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7668 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7669 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7670 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7671 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7672 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7673 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7674 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7675
7676 socket_tcp.check.status = HCHK_STATUS_INI;
7677 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7678 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7679 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7680 socket_tcp.check.server = &socket_tcp;
7681
7682 socket_tcp.agent.status = HCHK_STATUS_INI;
7683 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7684 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7685 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7686 socket_tcp.agent.server = &socket_tcp;
7687
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007688 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007689
7690#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007691 /* Init TCP server: unchanged parameters */
7692 memset(&socket_ssl, 0, sizeof(socket_ssl));
7693 socket_ssl.next = NULL;
7694 socket_ssl.proxy = &socket_proxy;
7695 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7696 LIST_INIT(&socket_ssl.actconns);
7697 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007698 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007699 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007700 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007701 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
7702 socket_ssl.last_change = 0;
7703 socket_ssl.id = "LUA-SSL-CONN";
7704 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7705 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7706 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7707
7708 /* XXX: Copy default parameter from default server,
7709 * but the default server is not initialized.
7710 */
7711 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7712 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7713 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7714 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7715 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7716 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7717 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7718 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7719 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7720 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7721
7722 socket_ssl.check.status = HCHK_STATUS_INI;
7723 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7724 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7725 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7726 socket_ssl.check.server = &socket_ssl;
7727
7728 socket_ssl.agent.status = HCHK_STATUS_INI;
7729 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7730 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7731 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7732 socket_ssl.agent.server = &socket_ssl;
7733
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007734 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007735 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007736
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007737 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007738 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7739 /*
7740 *
7741 * If the keyword is not known, we can search in the registered
7742 * server keywords. This is usefull to configure special SSL
7743 * features like client certificates and ssl_verify.
7744 *
7745 */
7746 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7747 if (tmp_error != 0) {
7748 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7749 abort(); /* This must be never arrives because the command line
7750 not editable by the user. */
7751 }
7752 idx += kw->skip;
7753 }
7754 }
7755
7756 /* Initialize SSL server. */
Willy Tarreau17d45382016-12-22 21:16:08 +01007757 if (socket_ssl.xprt->prepare_srv)
7758 socket_ssl.xprt->prepare_srv(&socket_ssl);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007759#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007760
7761 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007762}
Willy Tarreaubb57d942016-12-21 19:04:56 +01007763
7764__attribute__((constructor))
7765static void __hlua_init(void)
7766{
7767 char *ptr = NULL;
7768 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
7769 hap_register_build_opts(ptr, 1);
7770}