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