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