blob: c29a7cc4ea2d0a4068c4e8f80d439f35ae49d2d8 [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>
Mark Lakes56cc1252018-03-27 09:48:06 +020014#include <limits.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020015#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010016
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010017#include <lauxlib.h>
18#include <lua.h>
19#include <lualib.h>
20
Thierry FOURNIER463119c2015-03-10 00:35:36 +010021#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
22#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010023#endif
24
Thierry FOURNIER380d0932015-01-23 14:27:52 +010025#include <ebpttree.h>
26
27#include <common/cfgparse.h>
Thierry FOURNIER2da788e2017-09-11 18:37:23 +020028#include <common/xref.h>
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +020029#include <common/hathreads.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010030
William Lallemand9ed62032016-11-21 17:49:11 +010031#include <types/cli.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010032#include <types/hlua.h>
33#include <types/proxy.h>
William Lallemand9ed62032016-11-21 17:49:11 +010034#include <types/stats.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010035
Thierry FOURNIER55da1652015-01-23 11:36:30 +010036#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020037#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010038#include <proto/channel.h>
William Lallemand9ed62032016-11-21 17:49:11 +010039#include <proto/cli.h>
Willy Tarreaua71f6422016-11-16 17:00:14 +010040#include <proto/connection.h>
William Lallemand9ed62032016-11-21 17:49:11 +010041#include <proto/stats.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010042#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010043#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010044#include <proto/hlua_fcn.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020045#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010046#include <proto/obj_type.h>
Patrick Hemmer268a7072018-05-11 12:52:31 -040047#include <proto/queue.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010048#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010049#include <proto/payload.h>
50#include <proto/proto_http.h>
51#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010052#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020053#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020054#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010055#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010056#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010057#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020058#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010059
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010060/* Lua uses longjmp to perform yield or throwing errors. This
61 * macro is used only for identifying the function that can
62 * not return because a longjmp is executed.
63 * __LJMP marks a prototype of hlua file that can use longjmp.
64 * WILL_LJMP() marks an lua function that will use longjmp.
65 * MAY_LJMP() marks an lua function that may use longjmp.
66 */
67#define __LJMP
68#define WILL_LJMP(func) func
69#define MAY_LJMP(func) func
70
Thierry FOURNIERbabae282015-09-17 11:36:37 +020071/* This couple of function executes securely some Lua calls outside of
72 * the lua runtime environment. Each Lua call can return a longjmp
73 * if it encounter a memory error.
74 *
75 * Lua documentation extract:
76 *
77 * If an error happens outside any protected environment, Lua calls
78 * a panic function (see lua_atpanic) and then calls abort, thus
79 * exiting the host application. Your panic function can avoid this
80 * exit by never returning (e.g., doing a long jump to your own
81 * recovery point outside Lua).
82 *
83 * The panic function runs as if it were a message handler (see
84 * §2.3); in particular, the error message is at the top of the
85 * stack. However, there is no guarantee about stack space. To push
86 * anything on the stack, the panic function must first check the
87 * available space (see §4.2).
88 *
89 * We must check all the Lua entry point. This includes:
90 * - The include/proto/hlua.h exported functions
91 * - the task wrapper function
92 * - The action wrapper function
93 * - The converters wrapper function
94 * - The sample-fetch wrapper functions
95 *
96 * It is tolerated that the initilisation function returns an abort.
97 * Before each Lua abort, an error message is writed on stderr.
98 *
99 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
100 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
101 * because they must be exists in the program stack when the longjmp
102 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200103 *
104 * Note that the Lua processing is not really thread safe. It provides
105 * heavy system which consists to add our own lock function in the Lua
106 * code and recompile the library. This system will probably not accepted
107 * by maintainers of various distribs.
108 *
109 * Our main excution point of the Lua is the function lua_resume(). A
110 * quick looking on the Lua sources displays a lua_lock() a the start
111 * of function and a lua_unlock() at the end of the function. So I
112 * conclude that the Lua thread safe mode just perform a mutex around
113 * all execution. So I prefer to do this in the HAProxy code, it will be
114 * easier for distro maintainers.
115 *
116 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
117 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
118 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200119 */
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100120__decl_hathreads(HA_SPINLOCK_T hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200121THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200122static int hlua_panic_safe(lua_State *L) { return 0; }
123static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
124
125#define SET_SAFE_LJMP(__L) \
126 ({ \
127 int ret; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100128 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200129 if (setjmp(safe_ljmp_env) != 0) { \
130 lua_atpanic(__L, hlua_panic_safe); \
131 ret = 0; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100132 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200133 } else { \
134 lua_atpanic(__L, hlua_panic_ljmp); \
135 ret = 1; \
136 } \
137 ret; \
138 })
139
140/* If we are the last function catching Lua errors, we
141 * must reset the panic function.
142 */
143#define RESET_SAFE_LJMP(__L) \
144 do { \
145 lua_atpanic(__L, hlua_panic_safe); \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100146 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200147 } while(0)
148
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200149/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200150#define APPLET_DONE 0x01 /* applet processing is done. */
151#define APPLET_100C 0x02 /* 100 continue expected. */
152#define APPLET_HDR_SENT 0x04 /* Response header sent. */
153#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
154#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100155#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200156
157#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200158
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100159/* The main Lua execution context. */
160struct hlua gL;
161
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100162/* This is the memory pool containing struct lua for applets
163 * (including cli).
164 */
Willy Tarreaubafbe012017-11-24 17:34:44 +0100165struct pool_head *pool_head_hlua;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100166
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100167/* Used for Socket connection. */
168static struct proxy socket_proxy;
169static struct server socket_tcp;
170#ifdef USE_OPENSSL
171static struct server socket_ssl;
172#endif
173
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100174/* List head of the function called at the initialisation time. */
175struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
176
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100177/* The following variables contains the reference of the different
178 * Lua classes. These references are useful for identify metadata
179 * associated with an object.
180 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100181static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100182static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100183static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100184static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100185static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100186static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200187static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200188static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200189static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100190
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100191/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200192 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100193 * short timeout. Lua linked with tasks doesn't have a timeout
194 * because a task may remain alive during all the haproxy execution.
195 */
196static unsigned int hlua_timeout_session = 4000; /* session timeout. */
197static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200198static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100199
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100200/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
201 * it is used for preventing infinite loops.
202 *
203 * I test the scheer with an infinite loop containing one incrementation
204 * and one test. I run this loop between 10 seconds, I raise a ceil of
205 * 710M loops from one interrupt each 9000 instructions, so I fix the value
206 * to one interrupt each 10 000 instructions.
207 *
208 * configured | Number of
209 * instructions | loops executed
210 * between two | in milions
211 * forced yields |
212 * ---------------+---------------
213 * 10 | 160
214 * 500 | 670
215 * 1000 | 680
216 * 5000 | 700
217 * 7000 | 700
218 * 8000 | 700
219 * 9000 | 710 <- ceil
220 * 10000 | 710
221 * 100000 | 710
222 * 1000000 | 710
223 *
224 */
225static unsigned int hlua_nb_instruction = 10000;
226
Willy Tarreau32f61e22015-03-18 17:54:59 +0100227/* Descriptor for the memory allocation state. If limit is not null, it will
228 * be enforced on any memory allocation.
229 */
230struct hlua_mem_allocator {
231 size_t allocated;
232 size_t limit;
233};
234
235static struct hlua_mem_allocator hlua_global_allocator;
236
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200237static const char error_500[] =
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200238 "HTTP/1.0 500 Internal Server Error\r\n"
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200239 "Cache-Control: no-cache\r\n"
240 "Connection: close\r\n"
241 "Content-Type: text/html\r\n"
242 "\r\n"
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200243 "<html><body><h1>500 Internal Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200244
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100245/* These functions converts types between HAProxy internal args or
246 * sample and LUA types. Another function permits to check if the
247 * LUA stack contains arguments according with an required ARG_T
248 * format.
249 */
250static int hlua_arg2lua(lua_State *L, const struct arg *arg);
251static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100252__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100253 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100254static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100255static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100256static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
257
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200258__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
259
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200260#define SEND_ERR(__be, __fmt, __args...) \
261 do { \
262 send_log(__be, LOG_ERR, __fmt, ## __args); \
263 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100264 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200265 } while (0)
266
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100267/* Used to check an Lua function type in the stack. It creates and
268 * returns a reference of the function. This function throws an
269 * error if the rgument is not a "function".
270 */
271__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
272{
273 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100274 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100275 WILL_LJMP(luaL_argerror(L, argno, msg));
276 }
277 lua_pushvalue(L, argno);
278 return luaL_ref(L, LUA_REGISTRYINDEX);
279}
280
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200281/* Return the string that is of the top of the stack. */
282const char *hlua_get_top_error_string(lua_State *L)
283{
284 if (lua_gettop(L) < 1)
285 return "unknown error";
286 if (lua_type(L, -1) != LUA_TSTRING)
287 return "unknown error";
288 return lua_tostring(L, -1);
289}
290
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200291__LJMP static const char *hlua_traceback(lua_State *L)
292{
293 lua_Debug ar;
294 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200295 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200296 int filled = 0;
297
298 while (lua_getstack(L, level++, &ar)) {
299
300 /* Add separator */
301 if (filled)
302 chunk_appendf(msg, ", ");
303 filled = 1;
304
305 /* Fill fields:
306 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
307 * 'l': fills in the field currentline;
308 * 'n': fills in the field name and namewhat;
309 * 't': fills in the field istailcall;
310 */
311 lua_getinfo(L, "Slnt", &ar);
312
313 /* Append code localisation */
314 if (ar.currentline > 0)
315 chunk_appendf(msg, "%s:%d ", ar.short_src, ar.currentline);
316 else
317 chunk_appendf(msg, "%s ", ar.short_src);
318
319 /*
320 * Get function name
321 *
322 * if namewhat is no empty, name is defined.
323 * what contains "Lua" for Lua function, "C" for C function,
324 * or "main" for main code.
325 */
326 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
327 chunk_appendf(msg, "%s '%s'", ar.namewhat, ar.name); /* use it */
328
329 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
330 chunk_appendf(msg, "main chunk");
331
332 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
333 chunk_appendf(msg, "C function line %d", ar.linedefined);
334
335 else /* nothing left... */
336 chunk_appendf(msg, "?");
337
338
339 /* Display tailed call */
340 if (ar.istailcall)
341 chunk_appendf(msg, " ...");
342 }
343
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200344 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200345}
346
347
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100348/* This function check the number of arguments available in the
349 * stack. If the number of arguments available is not the same
350 * then <nb> an error is throwed.
351 */
352__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
353{
354 if (lua_gettop(L) == nb)
355 return;
356 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
357}
358
Mark Lakes22154b42018-01-29 14:38:40 -0800359/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100360 * and the line number where the error is encountered.
361 */
362static int hlua_pusherror(lua_State *L, const char *fmt, ...)
363{
364 va_list argp;
365 va_start(argp, fmt);
366 luaL_where(L, 1);
367 lua_pushvfstring(L, fmt, argp);
368 va_end(argp);
369 lua_concat(L, 2);
370 return 1;
371}
372
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100373/* This functions is used with sample fetch and converters. It
374 * converts the HAProxy configuration argument in a lua stack
375 * values.
376 *
377 * It takes an array of "arg", and each entry of the array is
378 * converted and pushed in the LUA stack.
379 */
380static int hlua_arg2lua(lua_State *L, const struct arg *arg)
381{
382 switch (arg->type) {
383 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100384 case ARGT_TIME:
385 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100386 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100387 break;
388
389 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200390 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100391 break;
392
393 case ARGT_IPV4:
394 case ARGT_IPV6:
395 case ARGT_MSK4:
396 case ARGT_MSK6:
397 case ARGT_FE:
398 case ARGT_BE:
399 case ARGT_TAB:
400 case ARGT_SRV:
401 case ARGT_USR:
402 case ARGT_MAP:
403 default:
404 lua_pushnil(L);
405 break;
406 }
407 return 1;
408}
409
410/* This function take one entrie in an LUA stack at the index "ud",
411 * and try to convert it in an HAProxy argument entry. This is useful
412 * with sample fetch wrappers. The input arguments are gived to the
413 * lua wrapper and converted as arg list by thi function.
414 */
415static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
416{
417 switch (lua_type(L, ud)) {
418
419 case LUA_TNUMBER:
420 case LUA_TBOOLEAN:
421 arg->type = ARGT_SINT;
422 arg->data.sint = lua_tointeger(L, ud);
423 break;
424
425 case LUA_TSTRING:
426 arg->type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200427 arg->data.str.area = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100428 break;
429
430 case LUA_TUSERDATA:
431 case LUA_TNIL:
432 case LUA_TTABLE:
433 case LUA_TFUNCTION:
434 case LUA_TTHREAD:
435 case LUA_TLIGHTUSERDATA:
436 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200437 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100438 break;
439 }
440 return 1;
441}
442
443/* the following functions are used to convert a struct sample
444 * in Lua type. This useful to convert the return of the
445 * fetchs or converters.
446 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100447static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100448{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200449 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100450 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100451 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200452 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100453 break;
454
455 case SMP_T_BIN:
456 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200457 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100458 break;
459
460 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200461 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100462 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
463 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
464 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
465 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
466 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
467 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
468 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
469 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
470 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200471 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100472 break;
473 default:
474 lua_pushnil(L);
475 break;
476 }
477 break;
478
479 case SMP_T_IPV4:
480 case SMP_T_IPV6:
481 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200482 if (sample_casts[smp->data.type][SMP_T_STR] &&
483 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200484 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100485 else
486 lua_pushnil(L);
487 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100488 default:
489 lua_pushnil(L);
490 break;
491 }
492 return 1;
493}
494
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100495/* the following functions are used to convert a struct sample
496 * in Lua strings. This is useful to convert the return of the
497 * fetchs or converters.
498 */
499static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
500{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200501 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100502
503 case SMP_T_BIN:
504 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200505 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100506 break;
507
508 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200509 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100510 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
511 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
512 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
513 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
514 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
515 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
516 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
517 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
518 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200519 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100520 break;
521 default:
522 lua_pushstring(L, "");
523 break;
524 }
525 break;
526
527 case SMP_T_SINT:
528 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100529 case SMP_T_IPV4:
530 case SMP_T_IPV6:
531 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200532 if (sample_casts[smp->data.type][SMP_T_STR] &&
533 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200534 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100535 else
536 lua_pushstring(L, "");
537 break;
538 default:
539 lua_pushstring(L, "");
540 break;
541 }
542 return 1;
543}
544
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100545/* the following functions are used to convert an Lua type in a
546 * struct sample. This is useful to provide data from a converter
547 * to the LUA code.
548 */
549static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
550{
551 switch (lua_type(L, ud)) {
552
553 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200554 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200555 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100556 break;
557
558
559 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200560 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200561 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100562 break;
563
564 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200565 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100566 smp->flags |= SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200567 smp->data.u.str.area = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100568 break;
569
570 case LUA_TUSERDATA:
571 case LUA_TNIL:
572 case LUA_TTABLE:
573 case LUA_TFUNCTION:
574 case LUA_TTHREAD:
575 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200576 case LUA_TNONE:
577 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200578 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200579 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100580 break;
581 }
582 return 1;
583}
584
585/* This function check the "argp" builded by another conversion function
586 * is in accord with the expected argp defined by the "mask". The fucntion
587 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100588 *
589 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
590 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100591 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100592__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100593 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100594{
595 int min_arg;
596 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100597 struct proxy *px;
598 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100599
600 idx = 0;
601 min_arg = ARGM(mask);
602 mask >>= ARGM_BITS;
603
604 while (1) {
605
606 /* Check oversize. */
607 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100608 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100609 }
610
611 /* Check for mandatory arguments. */
612 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100613 if (idx < min_arg) {
614
615 /* If miss other argument than the first one, we return an error. */
616 if (idx > 0)
617 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
618
619 /* If first argument have a certain type, some default values
620 * may be used. See the function smp_resolve_args().
621 */
622 switch (mask & ARGT_MASK) {
623
624 case ARGT_FE:
625 if (!(p->cap & PR_CAP_FE))
626 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
627 argp[idx].data.prx = p;
628 argp[idx].type = ARGT_FE;
629 argp[idx+1].type = ARGT_STOP;
630 break;
631
632 case ARGT_BE:
633 if (!(p->cap & PR_CAP_BE))
634 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
635 argp[idx].data.prx = p;
636 argp[idx].type = ARGT_BE;
637 argp[idx+1].type = ARGT_STOP;
638 break;
639
640 case ARGT_TAB:
641 argp[idx].data.prx = p;
642 argp[idx].type = ARGT_TAB;
643 argp[idx+1].type = ARGT_STOP;
644 break;
645
646 default:
647 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
648 break;
649 }
650 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100651 return 0;
652 }
653
654 /* Check for exceed the number of requiered argument. */
655 if ((mask & ARGT_MASK) == ARGT_STOP &&
656 argp[idx].type != ARGT_STOP) {
657 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
658 }
659
660 if ((mask & ARGT_MASK) == ARGT_STOP &&
661 argp[idx].type == ARGT_STOP) {
662 return 0;
663 }
664
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100665 /* Convert some argument types. */
666 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100667 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100668 if (argp[idx].type != ARGT_SINT)
669 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
670 argp[idx].type = ARGT_SINT;
671 break;
672
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100673 case ARGT_TIME:
674 if (argp[idx].type != ARGT_SINT)
675 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200676 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100677 break;
678
679 case ARGT_SIZE:
680 if (argp[idx].type != ARGT_SINT)
681 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200682 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100683 break;
684
685 case ARGT_FE:
686 if (argp[idx].type != ARGT_STR)
687 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200688 memcpy(trash.area, argp[idx].data.str.area,
689 argp[idx].data.str.data);
690 trash.area[argp[idx].data.str.data] = 0;
691 argp[idx].data.prx = proxy_fe_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100692 if (!argp[idx].data.prx)
693 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
694 argp[idx].type = ARGT_FE;
695 break;
696
697 case ARGT_BE:
698 if (argp[idx].type != ARGT_STR)
699 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200700 memcpy(trash.area, argp[idx].data.str.area,
701 argp[idx].data.str.data);
702 trash.area[argp[idx].data.str.data] = 0;
703 argp[idx].data.prx = proxy_be_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100704 if (!argp[idx].data.prx)
705 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
706 argp[idx].type = ARGT_BE;
707 break;
708
709 case ARGT_TAB:
710 if (argp[idx].type != ARGT_STR)
711 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200712 memcpy(trash.area, argp[idx].data.str.area,
713 argp[idx].data.str.data);
714 trash.area[argp[idx].data.str.data] = 0;
715 argp[idx].data.prx = proxy_tbl_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100716 if (!argp[idx].data.prx)
717 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
718 argp[idx].type = ARGT_TAB;
719 break;
720
721 case ARGT_SRV:
722 if (argp[idx].type != ARGT_STR)
723 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200724 memcpy(trash.area, argp[idx].data.str.area,
725 argp[idx].data.str.data);
726 trash.area[argp[idx].data.str.data] = 0;
727 sname = strrchr(trash.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100728 if (sname) {
729 *sname++ = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200730 pname = trash.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200731 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100732 if (!px)
733 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
734 }
735 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200736 sname = trash.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100737 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100738 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100739 argp[idx].data.srv = findserver(px, sname);
740 if (!argp[idx].data.srv)
741 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
742 argp[idx].type = ARGT_SRV;
743 break;
744
745 case ARGT_IPV4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200746 memcpy(trash.area, argp[idx].data.str.area,
747 argp[idx].data.str.data);
748 trash.area[argp[idx].data.str.data] = 0;
749 if (inet_pton(AF_INET, trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100750 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
751 argp[idx].type = ARGT_IPV4;
752 break;
753
754 case ARGT_MSK4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200755 memcpy(trash.area, argp[idx].data.str.area,
756 argp[idx].data.str.data);
757 trash.area[argp[idx].data.str.data] = 0;
758 if (!str2mask(trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100759 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
760 argp[idx].type = ARGT_MSK4;
761 break;
762
763 case ARGT_IPV6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200764 memcpy(trash.area, argp[idx].data.str.area,
765 argp[idx].data.str.data);
766 trash.area[argp[idx].data.str.data] = 0;
767 if (inet_pton(AF_INET6, trash.area, &argp[idx].data.ipv6))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100768 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
769 argp[idx].type = ARGT_IPV6;
770 break;
771
772 case ARGT_MSK6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200773 memcpy(trash.area, argp[idx].data.str.area,
774 argp[idx].data.str.data);
775 trash.area[argp[idx].data.str.data] = 0;
776 if (!str2mask6(trash.area, &argp[idx].data.ipv6))
Tim Duesterhusb814da62018-01-25 16:24:50 +0100777 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 mask"));
778 argp[idx].type = ARGT_MSK6;
779 break;
780
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100781 case ARGT_MAP:
782 case ARGT_REG:
783 case ARGT_USR:
784 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100785 break;
786 }
787
788 /* Check for type of argument. */
789 if ((mask & ARGT_MASK) != argp[idx].type) {
790 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
791 arg_type_names[(mask & ARGT_MASK)],
792 arg_type_names[argp[idx].type & ARGT_MASK]);
793 WILL_LJMP(luaL_argerror(L, first + idx, msg));
794 }
795
796 /* Next argument. */
797 mask >>= ARGT_BITS;
798 idx++;
799 }
800}
801
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100802/*
803 * The following functions are used to make correspondance between the the
804 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100805 *
806 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100807 * - hlua_sethlua : create the association between hlua context and lua_state.
808 */
809static inline struct hlua *hlua_gethlua(lua_State *L)
810{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100811 struct hlua **hlua = lua_getextraspace(L);
812 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100813}
814static inline void hlua_sethlua(struct hlua *hlua)
815{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100816 struct hlua **hlua_store = lua_getextraspace(hlua->T);
817 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100818}
819
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100820/* This function is used to send logs. It try to send on screen (stderr)
821 * and on the default syslog server.
822 */
823static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
824{
825 struct tm tm;
826 char *p;
827
828 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200829 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100830 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200831 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200832 /* Break the message if exceed the buffer size. */
833 *(p-4) = ' ';
834 *(p-3) = '.';
835 *(p-2) = '.';
836 *(p-1) = '.';
837 break;
838 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100839 if (isprint(*msg))
840 *p = *msg;
841 else
842 *p = '.';
843 }
844 *p = '\0';
845
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200846 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100847 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200848 get_localtime(date.tv_sec, &tm);
849 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100850 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200851 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100852 fflush(stderr);
853 }
854}
855
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100856/* This function just ensure that the yield will be always
857 * returned with a timeout and permit to set some flags
858 */
859__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100860 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100861{
862 struct hlua *hlua = hlua_gethlua(L);
863
864 /* Set the wake timeout. If timeout is required, we set
865 * the expiration time.
866 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200867 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100868
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100869 hlua->flags |= flags;
870
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100871 /* Process the yield. */
872 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
873}
874
Willy Tarreau87b09662015-04-03 00:22:06 +0200875/* This function initialises the Lua environment stored in the stream.
876 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100877 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200878 *
879 * This function is particular. it initialises a new Lua thread. If the
880 * initialisation fails (example: out of memory error), the lua function
881 * throws an error (longjmp).
882 *
883 * This function manipulates two Lua stack: the main and the thread. Only
884 * the main stack can fail. The thread is not manipulated. This function
885 * MUST NOT manipulate the created thread stack state, because is not
886 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100887 */
888int hlua_ctx_init(struct hlua *lua, struct task *task)
889{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200890 if (!SET_SAFE_LJMP(gL.T)) {
891 lua->Tref = LUA_REFNIL;
892 return 0;
893 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100894 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100895 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100896 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100897 lua->T = lua_newthread(gL.T);
898 if (!lua->T) {
899 lua->Tref = LUA_REFNIL;
Thierry FOURNIER0a976202017-07-12 11:18:00 +0200900 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100901 return 0;
902 }
903 hlua_sethlua(lua);
904 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
905 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200906 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100907 return 1;
908}
909
Willy Tarreau87b09662015-04-03 00:22:06 +0200910/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100911 * is destroyed. The destroy also the memory context. The struct "lua"
912 * is not freed.
913 */
914void hlua_ctx_destroy(struct hlua *lua)
915{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100916 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100917 return;
918
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100919 if (!lua->T)
920 goto end;
921
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100922 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +0200923 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100924
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200925 if (!SET_SAFE_LJMP(lua->T))
926 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100927 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200928 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200929
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200930 if (!SET_SAFE_LJMP(gL.T))
931 return;
932 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
933 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200934 /* Forces a garbage collecting process. If the Lua program is finished
935 * without error, we run the GC on the thread pointer. Its freed all
936 * the unused memory.
937 * If the thread is finnish with an error or is currently yielded,
938 * it seems that the GC applied on the thread doesn't clean anything,
939 * so e run the GC on the main thread.
940 * NOTE: maybe this action locks all the Lua threads untiml the en of
941 * the garbage collection.
942 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200943 if (lua->flags & HLUA_MUST_GC) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200944 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200945 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200946 lua_gc(gL.T, LUA_GCCOLLECT, 0);
947 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200948 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200949
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200950 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100951
952end:
Willy Tarreaubafbe012017-11-24 17:34:44 +0100953 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100954}
955
956/* This function is used to restore the Lua context when a coroutine
957 * fails. This function copy the common memory between old coroutine
958 * and the new coroutine. The old coroutine is destroyed, and its
959 * replaced by the new coroutine.
960 * If the flag "keep_msg" is set, the last entry of the old is assumed
961 * as string error message and it is copied in the new stack.
962 */
963static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
964{
965 lua_State *T;
966 int new_ref;
967
968 /* Renew the main LUA stack doesn't have sense. */
969 if (lua == &gL)
970 return 0;
971
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100972 /* New Lua coroutine. */
973 T = lua_newthread(gL.T);
974 if (!T)
975 return 0;
976
977 /* Copy last error message. */
978 if (keep_msg)
979 lua_xmove(lua->T, T, 1);
980
981 /* Copy data between the coroutines. */
982 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
983 lua_xmove(lua->T, T, 1);
984 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
985
986 /* Destroy old data. */
987 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
988
989 /* The thread is garbage collected by Lua. */
990 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
991
992 /* Fill the struct with the new coroutine values. */
993 lua->Mref = new_ref;
994 lua->T = T;
995 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
996
997 /* Set context. */
998 hlua_sethlua(lua);
999
1000 return 1;
1001}
1002
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001003void hlua_hook(lua_State *L, lua_Debug *ar)
1004{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001005 struct hlua *hlua = hlua_gethlua(L);
1006
1007 /* Lua cannot yield when its returning from a function,
1008 * so, we can fix the interrupt hook to 1 instruction,
1009 * expecting that the function is finnished.
1010 */
1011 if (lua_gethookmask(L) & LUA_MASKRET) {
1012 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1013 return;
1014 }
1015
1016 /* restore the interrupt condition. */
1017 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1018
1019 /* If we interrupt the Lua processing in yieldable state, we yield.
1020 * If the state is not yieldable, trying yield causes an error.
1021 */
1022 if (lua_isyieldable(L))
1023 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
1024
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001025 /* If we cannot yield, update the clock and check the timeout. */
1026 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001027 hlua->run_time += now_ms - hlua->start_time;
1028 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001029 lua_pushfstring(L, "execution timeout");
1030 WILL_LJMP(lua_error(L));
1031 }
1032
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001033 /* Update the start time. */
1034 hlua->start_time = now_ms;
1035
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001036 /* Try to interrupt the process at the end of the current
1037 * unyieldable function.
1038 */
1039 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001040}
1041
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001042/* This function start or resumes the Lua stack execution. If the flag
1043 * "yield_allowed" if no set and the LUA stack execution returns a yield
1044 * The function return an error.
1045 *
1046 * The function can returns 4 values:
1047 * - HLUA_E_OK : The execution is terminated without any errors.
1048 * - HLUA_E_AGAIN : The execution must continue at the next associated
1049 * task wakeup.
1050 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
1051 * the top of the stack.
1052 * - HLUA_E_ERR : An error has occured without error message.
1053 *
1054 * If an error occured, the stack is renewed and it is ready to run new
1055 * LUA code.
1056 */
1057static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1058{
1059 int ret;
1060 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001061 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001062
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001063 /* Initialise run time counter. */
1064 if (!HLUA_IS_RUNNING(lua))
1065 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001066
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001067 /* Lock the whole Lua execution. This lock must be before the
1068 * label "resume_execution".
1069 */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001070 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001071
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001072resume_execution:
1073
1074 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1075 * instructions. it is used for preventing infinite loops.
1076 */
1077 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1078
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001079 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001080 HLUA_SET_RUN(lua);
1081 HLUA_CLR_CTRLYIELD(lua);
1082 HLUA_CLR_WAKERESWR(lua);
1083 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001084
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001085 /* Update the start time. */
1086 lua->start_time = now_ms;
1087
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001088 /* Call the function. */
1089 ret = lua_resume(lua->T, gL.T, lua->nargs);
1090 switch (ret) {
1091
1092 case LUA_OK:
1093 ret = HLUA_E_OK;
1094 break;
1095
1096 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001097 /* Check if the execution timeout is expired. It it is the case, we
1098 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001099 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001100 tv_update_date(0, 1);
1101 lua->run_time += now_ms - lua->start_time;
1102 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001103 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001104 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001105 break;
1106 }
1107 /* Process the forced yield. if the general yield is not allowed or
1108 * if no task were associated this the current Lua execution
1109 * coroutine, we resume the execution. Else we want to return in the
1110 * scheduler and we want to be waked up again, to continue the
1111 * current Lua execution. So we schedule our own task.
1112 */
1113 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001114 if (!yield_allowed || !lua->task)
1115 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001116 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001117 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001118 if (!yield_allowed) {
1119 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001120 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001121 break;
1122 }
1123 ret = HLUA_E_AGAIN;
1124 break;
1125
1126 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001127
1128 /* Special exit case. The traditionnal exit is returned as an error
1129 * because the errors ares the only one mean to return immediately
1130 * from and lua execution.
1131 */
1132 if (lua->flags & HLUA_EXIT) {
1133 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001134 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001135 break;
1136 }
1137
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001138 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001139 if (!lua_checkstack(lua->T, 1)) {
1140 ret = HLUA_E_ERR;
1141 break;
1142 }
1143 msg = lua_tostring(lua->T, -1);
1144 lua_settop(lua->T, 0); /* Empty the stack. */
1145 lua_pop(lua->T, 1);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001146 trace = hlua_traceback(lua->T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001147 if (msg)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001148 lua_pushfstring(lua->T, "runtime error: %s from %s", msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001149 else
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001150 lua_pushfstring(lua->T, "unknown runtime error from %s", trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001151 ret = HLUA_E_ERRMSG;
1152 break;
1153
1154 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001155 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001156 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001157 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001158 break;
1159
1160 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001161 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001162 if (!lua_checkstack(lua->T, 1)) {
1163 ret = HLUA_E_ERR;
1164 break;
1165 }
1166 msg = lua_tostring(lua->T, -1);
1167 lua_settop(lua->T, 0); /* Empty the stack. */
1168 lua_pop(lua->T, 1);
1169 if (msg)
1170 lua_pushfstring(lua->T, "message handler error: %s", msg);
1171 else
1172 lua_pushfstring(lua->T, "message handler error");
1173 ret = HLUA_E_ERRMSG;
1174 break;
1175
1176 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001177 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001178 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001179 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001180 break;
1181 }
1182
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001183 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001184 if (lua->flags & HLUA_MUST_GC &&
1185 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001186 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1187
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001188 switch (ret) {
1189 case HLUA_E_AGAIN:
1190 break;
1191
1192 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001193 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001194 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001195 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001196 break;
1197
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001198 case HLUA_E_ETMOUT:
1199 case HLUA_E_NOMEM:
1200 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001201 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001202 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001203 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001204 hlua_ctx_renew(lua, 0);
1205 break;
1206
1207 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001208 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001209 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001210 break;
1211 }
1212
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001213 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001214 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001215
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001216 return ret;
1217}
1218
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001219/* This function exit the current code. */
1220__LJMP static int hlua_done(lua_State *L)
1221{
1222 struct hlua *hlua = hlua_gethlua(L);
1223
1224 hlua->flags |= HLUA_EXIT;
1225 WILL_LJMP(lua_error(L));
1226
1227 return 0;
1228}
1229
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001230/* This function is an LUA binding. It provides a function
1231 * for deleting ACL from a referenced ACL file.
1232 */
1233__LJMP static int hlua_del_acl(lua_State *L)
1234{
1235 const char *name;
1236 const char *key;
1237 struct pat_ref *ref;
1238
1239 MAY_LJMP(check_args(L, 2, "del_acl"));
1240
1241 name = MAY_LJMP(luaL_checkstring(L, 1));
1242 key = MAY_LJMP(luaL_checkstring(L, 2));
1243
1244 ref = pat_ref_lookup(name);
1245 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001246 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001247
1248 pat_ref_delete(ref, key);
1249 return 0;
1250}
1251
1252/* This function is an LUA binding. It provides a function
1253 * for deleting map entry from a referenced map file.
1254 */
1255static int hlua_del_map(lua_State *L)
1256{
1257 const char *name;
1258 const char *key;
1259 struct pat_ref *ref;
1260
1261 MAY_LJMP(check_args(L, 2, "del_map"));
1262
1263 name = MAY_LJMP(luaL_checkstring(L, 1));
1264 key = MAY_LJMP(luaL_checkstring(L, 2));
1265
1266 ref = pat_ref_lookup(name);
1267 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001268 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001269
1270 pat_ref_delete(ref, key);
1271 return 0;
1272}
1273
1274/* This function is an LUA binding. It provides a function
1275 * for adding ACL pattern from a referenced ACL file.
1276 */
1277static int hlua_add_acl(lua_State *L)
1278{
1279 const char *name;
1280 const char *key;
1281 struct pat_ref *ref;
1282
1283 MAY_LJMP(check_args(L, 2, "add_acl"));
1284
1285 name = MAY_LJMP(luaL_checkstring(L, 1));
1286 key = MAY_LJMP(luaL_checkstring(L, 2));
1287
1288 ref = pat_ref_lookup(name);
1289 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001290 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001291
1292 if (pat_ref_find_elt(ref, key) == NULL)
1293 pat_ref_add(ref, key, NULL, NULL);
1294 return 0;
1295}
1296
1297/* This function is an LUA binding. It provides a function
1298 * for setting map pattern and sample from a referenced map
1299 * file.
1300 */
1301static int hlua_set_map(lua_State *L)
1302{
1303 const char *name;
1304 const char *key;
1305 const char *value;
1306 struct pat_ref *ref;
1307
1308 MAY_LJMP(check_args(L, 3, "set_map"));
1309
1310 name = MAY_LJMP(luaL_checkstring(L, 1));
1311 key = MAY_LJMP(luaL_checkstring(L, 2));
1312 value = MAY_LJMP(luaL_checkstring(L, 3));
1313
1314 ref = pat_ref_lookup(name);
1315 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001316 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001317
1318 if (pat_ref_find_elt(ref, key) != NULL)
1319 pat_ref_set(ref, key, value, NULL);
1320 else
1321 pat_ref_add(ref, key, value, NULL);
1322 return 0;
1323}
1324
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001325/* A class is a lot of memory that contain data. This data can be a table,
1326 * an integer or user data. This data is associated with a metatable. This
1327 * metatable have an original version registred in the global context with
1328 * the name of the object (_G[<name>] = <metable> ).
1329 *
1330 * A metable is a table that modify the standard behavior of a standard
1331 * access to the associated data. The entries of this new metatable are
1332 * defined as is:
1333 *
1334 * http://lua-users.org/wiki/MetatableEvents
1335 *
1336 * __index
1337 *
1338 * we access an absent field in a table, the result is nil. This is
1339 * true, but it is not the whole truth. Actually, such access triggers
1340 * the interpreter to look for an __index metamethod: If there is no
1341 * such method, as usually happens, then the access results in nil;
1342 * otherwise, the metamethod will provide the result.
1343 *
1344 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1345 * the key does not appear in the table, but the metatable has an __index
1346 * property:
1347 *
1348 * - if the value is a function, the function is called, passing in the
1349 * table and the key; the return value of that function is returned as
1350 * the result.
1351 *
1352 * - if the value is another table, the value of the key in that table is
1353 * asked for and returned (and if it doesn't exist in that table, but that
1354 * table's metatable has an __index property, then it continues on up)
1355 *
1356 * - Use "rawget(myTable,key)" to skip this metamethod.
1357 *
1358 * http://www.lua.org/pil/13.4.1.html
1359 *
1360 * __newindex
1361 *
1362 * Like __index, but control property assignment.
1363 *
1364 * __mode - Control weak references. A string value with one or both
1365 * of the characters 'k' and 'v' which specifies that the the
1366 * keys and/or values in the table are weak references.
1367 *
1368 * __call - Treat a table like a function. When a table is followed by
1369 * parenthesis such as "myTable( 'foo' )" and the metatable has
1370 * a __call key pointing to a function, that function is invoked
1371 * (passing any specified arguments) and the return value is
1372 * returned.
1373 *
1374 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1375 * called, if the metatable for myTable has a __metatable
1376 * key, the value of that key is returned instead of the
1377 * actual metatable.
1378 *
1379 * __tostring - Control string representation. When the builtin
1380 * "tostring( myTable )" function is called, if the metatable
1381 * for myTable has a __tostring property set to a function,
1382 * that function is invoked (passing myTable to it) and the
1383 * return value is used as the string representation.
1384 *
1385 * __len - Control table length. When the table length is requested using
1386 * the length operator ( '#' ), if the metatable for myTable has
1387 * a __len key pointing to a function, that function is invoked
1388 * (passing myTable to it) and the return value used as the value
1389 * of "#myTable".
1390 *
1391 * __gc - Userdata finalizer code. When userdata is set to be garbage
1392 * collected, if the metatable has a __gc field pointing to a
1393 * function, that function is first invoked, passing the userdata
1394 * to it. The __gc metamethod is not called for tables.
1395 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1396 *
1397 * Special metamethods for redefining standard operators:
1398 * http://www.lua.org/pil/13.1.html
1399 *
1400 * __add "+"
1401 * __sub "-"
1402 * __mul "*"
1403 * __div "/"
1404 * __unm "!"
1405 * __pow "^"
1406 * __concat ".."
1407 *
1408 * Special methods for redfining standar relations
1409 * http://www.lua.org/pil/13.2.html
1410 *
1411 * __eq "=="
1412 * __lt "<"
1413 * __le "<="
1414 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001415
1416/*
1417 *
1418 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001419 * Class Map
1420 *
1421 *
1422 */
1423
1424/* Returns a struct hlua_map if the stack entry "ud" is
1425 * a class session, otherwise it throws an error.
1426 */
1427__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1428{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001429 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001430}
1431
1432/* This function is the map constructor. It don't need
1433 * the class Map object. It creates and return a new Map
1434 * object. It must be called only during "body" or "init"
1435 * context because it process some filesystem accesses.
1436 */
1437__LJMP static int hlua_map_new(struct lua_State *L)
1438{
1439 const char *fn;
1440 int match = PAT_MATCH_STR;
1441 struct sample_conv conv;
1442 const char *file = "";
1443 int line = 0;
1444 lua_Debug ar;
1445 char *err = NULL;
1446 struct arg args[2];
1447
1448 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1449 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1450
1451 fn = MAY_LJMP(luaL_checkstring(L, 1));
1452
1453 if (lua_gettop(L) >= 2) {
1454 match = MAY_LJMP(luaL_checkinteger(L, 2));
1455 if (match < 0 || match >= PAT_MATCH_NUM)
1456 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1457 }
1458
1459 /* Get Lua filename and line number. */
1460 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1461 lua_getinfo(L, "Sl", &ar); /* get info about it */
1462 if (ar.currentline > 0) { /* is there info? */
1463 file = ar.short_src;
1464 line = ar.currentline;
1465 }
1466 }
1467
1468 /* fill fake sample_conv struct. */
1469 conv.kw = ""; /* unused. */
1470 conv.process = NULL; /* unused. */
1471 conv.arg_mask = 0; /* unused. */
1472 conv.val_args = NULL; /* unused. */
1473 conv.out_type = SMP_T_STR;
1474 conv.private = (void *)(long)match;
1475 switch (match) {
1476 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1477 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1478 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1479 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1480 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1481 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1482 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001483 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001484 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1485 default:
1486 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1487 }
1488
1489 /* fill fake args. */
1490 args[0].type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001491 args[0].data.str.area = (char *)fn;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001492 args[1].type = ARGT_STOP;
1493
1494 /* load the map. */
1495 if (!sample_load_map(args, &conv, file, line, &err)) {
1496 /* error case: we cant use luaL_error because we must
1497 * free the err variable.
1498 */
1499 luaL_where(L, 1);
1500 lua_pushfstring(L, "'new': %s.", err);
1501 lua_concat(L, 2);
1502 free(err);
1503 WILL_LJMP(lua_error(L));
1504 }
1505
1506 /* create the lua object. */
1507 lua_newtable(L);
1508 lua_pushlightuserdata(L, args[0].data.map);
1509 lua_rawseti(L, -2, 0);
1510
1511 /* Pop a class Map metatable and affect it to the userdata. */
1512 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1513 lua_setmetatable(L, -2);
1514
1515
1516 return 1;
1517}
1518
1519__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1520{
1521 struct map_descriptor *desc;
1522 struct pattern *pat;
1523 struct sample smp;
1524
1525 MAY_LJMP(check_args(L, 2, "lookup"));
1526 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001527 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001528 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001529 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001530 }
1531 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001532 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001533 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001534 smp.data.u.str.area = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.data));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001535 }
1536
1537 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001538 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001539 if (str)
1540 lua_pushstring(L, "");
1541 else
1542 lua_pushnil(L);
1543 return 1;
1544 }
1545
1546 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001547 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001548 return 1;
1549}
1550
1551__LJMP static int hlua_map_lookup(struct lua_State *L)
1552{
1553 return _hlua_map_lookup(L, 0);
1554}
1555
1556__LJMP static int hlua_map_slookup(struct lua_State *L)
1557{
1558 return _hlua_map_lookup(L, 1);
1559}
1560
1561/*
1562 *
1563 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001564 * Class Socket
1565 *
1566 *
1567 */
1568
1569__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1570{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001571 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001572}
1573
1574/* This function is the handler called for each I/O on the established
1575 * connection. It is used for notify space avalaible to send or data
1576 * received.
1577 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001578static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001579{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001580 struct stream_interface *si = appctx->owner;
Olivier Houchard9aaf7782017-09-13 18:30:23 +02001581 struct connection *c = cs_conn(objt_cs(si_opposite(si)->end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001582
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001583 if (appctx->ctx.hlua_cosocket.die) {
1584 si_shutw(si);
1585 si_shutr(si);
1586 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001587 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1588 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001589 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1590 }
1591
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001592 /* If the connection object is not avalaible, close all the
1593 * streams and wakeup everithing waiting for.
1594 */
1595 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001596 si_shutw(si);
1597 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001598 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001599 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1600 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001601 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001602 }
1603
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001604 /* If we cant write, wakeup the pending write signals. */
1605 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001606 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001607
1608 /* If we cant read, wakeup the pending read signals. */
1609 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001610 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001611
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001612 /* if the connection is not estabkished, inform the stream that we want
1613 * to be notified whenever the connection completes.
1614 */
1615 if (!(c->flags & CO_FL_CONNECTED)) {
1616 si_applet_cant_get(si);
1617 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001618 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001619 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001620
1621 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001622 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001623
1624 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001625 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001626 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001627
1628 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001629 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001630 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001631
1632 /* Some data were injected in the buffer, notify the stream
1633 * interface.
1634 */
1635 if (!channel_is_empty(si_ic(si)))
1636 stream_int_update(si);
1637
1638 /* If write notifications are registered, we considers we want
1639 * to write, so we set the flag cant put
1640 */
1641 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
1642 si_applet_cant_put(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001643}
1644
Willy Tarreau87b09662015-04-03 00:22:06 +02001645/* This function is called when the "struct stream" is destroyed.
1646 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001647 * Wake all the pending signals.
1648 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001649static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001650{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001651 struct xref *peer;
1652
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001653 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001654 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1655 if (peer)
1656 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001657
1658 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001659 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1660 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001661}
1662
1663/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001664 * uses this object. If the stream does not exists, just quit.
1665 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001666 * pending signal can rest in the read and write lists. destroy
1667 * it.
1668 */
1669__LJMP static int hlua_socket_gc(lua_State *L)
1670{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001671 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001672 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001673 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001674
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001675 MAY_LJMP(check_args(L, 1, "__gc"));
1676
1677 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001678 peer = xref_get_peer_and_lock(&socket->xref);
1679 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001680 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001681 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001682
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001683 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001684 appctx->ctx.hlua_cosocket.die = 1;
1685 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001686
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001687 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001688 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001689 return 0;
1690}
1691
1692/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001693 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001694 */
sada05ed3302018-05-11 11:48:18 -07001695__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001696{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001697 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001698 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001699 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001700
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001701 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001702
1703 /* Check if we run on the same thread than the xreator thread.
1704 * We cannot access to the socket if the thread is different.
1705 */
1706 if (socket->tid != tid)
1707 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1708
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001709 peer = xref_get_peer_and_lock(&socket->xref);
1710 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001711 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001712 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001713
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001714 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001715 appctx->ctx.hlua_cosocket.die = 1;
1716 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001717
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001718 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001719 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001720 return 0;
1721}
1722
sada05ed3302018-05-11 11:48:18 -07001723/* The close function calls close_helper.
1724 */
1725__LJMP static int hlua_socket_close(lua_State *L)
1726{
1727 MAY_LJMP(check_args(L, 1, "close"));
1728 return hlua_socket_close_helper(L);
1729}
1730
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001731/* This Lua function assumes that the stack contain three parameters.
1732 * 1 - USERDATA containing a struct socket
1733 * 2 - INTEGER with values of the macro defined below
1734 * If the integer is -1, we must read at most one line.
1735 * If the integer is -2, we ust read all the data until the
1736 * end of the stream.
1737 * If the integer is positive value, we must read a number of
1738 * bytes corresponding to this value.
1739 */
1740#define HLSR_READ_LINE (-1)
1741#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001742__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001743{
1744 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1745 int wanted = lua_tointeger(L, 2);
1746 struct hlua *hlua = hlua_gethlua(L);
1747 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001748 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001749 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02001750 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001751 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02001752 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001753 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001754 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001755 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001756 struct stream_interface *si;
1757 struct stream *s;
1758 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001759 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001760
1761 /* Check if this lua stack is schedulable. */
1762 if (!hlua || !hlua->task)
1763 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1764 "'frontend', 'backend' or 'task'"));
1765
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001766 /* Check if we run on the same thread than the xreator thread.
1767 * We cannot access to the socket if the thread is different.
1768 */
1769 if (socket->tid != tid)
1770 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1771
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001772 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001773 peer = xref_get_peer_and_lock(&socket->xref);
1774 if (!peer)
1775 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001776 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1777 si = appctx->owner;
1778 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001779
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001780 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001781 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001782 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001783 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001784 if (nblk < 0) /* Connection close. */
1785 goto connection_closed;
1786 if (nblk == 0) /* No data avalaible. */
1787 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001788
1789 /* remove final \r\n. */
1790 if (nblk == 1) {
1791 if (blk1[len1-1] == '\n') {
1792 len1--;
1793 skip_at_end++;
1794 if (blk1[len1-1] == '\r') {
1795 len1--;
1796 skip_at_end++;
1797 }
1798 }
1799 }
1800 else {
1801 if (blk2[len2-1] == '\n') {
1802 len2--;
1803 skip_at_end++;
1804 if (blk2[len2-1] == '\r') {
1805 len2--;
1806 skip_at_end++;
1807 }
1808 }
1809 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001810 }
1811
1812 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001813 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001814 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001815 if (nblk < 0) /* Connection close. */
1816 goto connection_closed;
1817 if (nblk == 0) /* No data avalaible. */
1818 goto connection_empty;
1819 }
1820
1821 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001822 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001823 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001824 if (nblk < 0) /* Connection close. */
1825 goto connection_closed;
1826 if (nblk == 0) /* No data avalaible. */
1827 goto connection_empty;
1828
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001829 missing_bytes = wanted - socket->b.n;
1830 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001831 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001832 len1 = missing_bytes;
1833 } if (nblk == 2 && len1 + len2 > missing_bytes)
1834 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001835 }
1836
1837 len = len1;
1838
1839 luaL_addlstring(&socket->b, blk1, len1);
1840 if (nblk == 2) {
1841 len += len2;
1842 luaL_addlstring(&socket->b, blk2, len2);
1843 }
1844
1845 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001846 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001847
1848 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02001849 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001850
1851 /* If the pattern reclaim to read all the data
1852 * in the connection, got out.
1853 */
1854 if (wanted == HLSR_READ_ALL)
1855 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001856 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001857 goto connection_empty;
1858
1859 /* Return result. */
1860 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001861 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001862 return 1;
1863
1864connection_closed:
1865
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001866 xref_unlock(&socket->xref, peer);
1867
1868no_peer:
1869
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001870 /* If the buffer containds data. */
1871 if (socket->b.n > 0) {
1872 luaL_pushresult(&socket->b);
1873 return 1;
1874 }
1875 lua_pushnil(L);
1876 lua_pushstring(L, "connection closed.");
1877 return 2;
1878
1879connection_empty:
1880
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001881 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1882 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001883 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001884 }
1885 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001886 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001887 return 0;
1888}
1889
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001890/* This Lua function gets two parameters. The first one can be string
1891 * or a number. If the string is "*l", the user requires one line. If
1892 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001893 * If the value is a number, the user require a number of bytes equal
1894 * to the value. The default value is "*l" (a line).
1895 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001896 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001897 * integer takes this values:
1898 * -1 : read a line
1899 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001900 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001901 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001902 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001903 * concatenated with the read data.
1904 */
1905__LJMP static int hlua_socket_receive(struct lua_State *L)
1906{
1907 int wanted = HLSR_READ_LINE;
1908 const char *pattern;
1909 int type;
1910 char *error;
1911 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001912 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001913
1914 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1915 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1916
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001917 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001918
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001919 /* Check if we run on the same thread than the xreator thread.
1920 * We cannot access to the socket if the thread is different.
1921 */
1922 if (socket->tid != tid)
1923 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1924
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001925 /* check for pattern. */
1926 if (lua_gettop(L) >= 2) {
1927 type = lua_type(L, 2);
1928 if (type == LUA_TSTRING) {
1929 pattern = lua_tostring(L, 2);
1930 if (strcmp(pattern, "*a") == 0)
1931 wanted = HLSR_READ_ALL;
1932 else if (strcmp(pattern, "*l") == 0)
1933 wanted = HLSR_READ_LINE;
1934 else {
1935 wanted = strtoll(pattern, &error, 10);
1936 if (*error != '\0')
1937 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1938 }
1939 }
1940 else if (type == LUA_TNUMBER) {
1941 wanted = lua_tointeger(L, 2);
1942 if (wanted < 0)
1943 WILL_LJMP(luaL_error(L, "Unsupported size."));
1944 }
1945 }
1946
1947 /* Set pattern. */
1948 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01001949
1950 /* Check if we would replace the top by itself. */
1951 if (lua_gettop(L) != 2)
1952 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001953
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001954 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001955 luaL_buffinit(L, &socket->b);
1956
1957 /* Check prefix. */
1958 if (lua_gettop(L) >= 3) {
1959 if (lua_type(L, 3) != LUA_TSTRING)
1960 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1961 pattern = lua_tolstring(L, 3, &len);
1962 luaL_addlstring(&socket->b, pattern, len);
1963 }
1964
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001965 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001966}
1967
1968/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08001969 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001970 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001971static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001972{
1973 struct hlua_socket *socket;
1974 struct hlua *hlua = hlua_gethlua(L);
1975 struct appctx *appctx;
1976 size_t buf_len;
1977 const char *buf;
1978 int len;
1979 int send_len;
1980 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001981 struct xref *peer;
1982 struct stream_interface *si;
1983 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001984
1985 /* Check if this lua stack is schedulable. */
1986 if (!hlua || !hlua->task)
1987 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1988 "'frontend', 'backend' or 'task'"));
1989
1990 /* Get object */
1991 socket = MAY_LJMP(hlua_checksocket(L, 1));
1992 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001993 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001994
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001995 /* Check if we run on the same thread than the xreator thread.
1996 * We cannot access to the socket if the thread is different.
1997 */
1998 if (socket->tid != tid)
1999 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2000
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002001 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002002 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002003 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002004 lua_pushinteger(L, -1);
2005 return 1;
2006 }
2007 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2008 si = appctx->owner;
2009 s = si_strm(si);
2010
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002011 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002012 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002013 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002014 lua_pushinteger(L, -1);
2015 return 1;
2016 }
2017
2018 /* Update the input buffer data. */
2019 buf += sent;
2020 send_len = buf_len - sent;
2021
2022 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002023 if (sent >= buf_len) {
2024 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002025 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002026 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002027
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002028 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2029 * the request buffer if its not required.
2030 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002031 if (s->req.buf.size == 0) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002032 if (!channel_alloc_buffer(&s->req, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002033 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002034 }
2035
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002036 /* Check for avalaible space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002037 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002038 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002039 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002040 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002041
2042 /* send data */
2043 if (len < send_len)
2044 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002045 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002046
2047 /* "Not enough space" (-1), "Buffer too little to contain
2048 * the data" (-2) are not expected because the available length
2049 * is tested.
2050 * Other unknown error are also not expected.
2051 */
2052 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002053 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002054 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002055
sada05ed3302018-05-11 11:48:18 -07002056 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002057 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002058 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002059 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002060 return 1;
2061 }
2062
2063 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002064 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002065
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002066 s->req.rex = TICK_ETERNITY;
2067 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002068
2069 /* Update length sent. */
2070 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002071 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002072
2073 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002074 if (sent + len >= buf_len) {
2075 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002076 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002077 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002078
2079hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002080 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2081 xref_unlock(&socket->xref, peer);
2082 WILL_LJMP(luaL_error(L, "out of memory"));
2083 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002084 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002085 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002086 return 0;
2087}
2088
2089/* This function initiate the send of data. It just check the input
2090 * parameters and push an integer in the Lua stack that contain the
2091 * amount of data writed in the buffer. This is used by the function
2092 * "hlua_socket_write_yield" that can yield.
2093 *
2094 * The Lua function gets between 3 and 4 parameters. The first one is
2095 * the associated object. The second is a string buffer. The third is
2096 * a facultative integer that represents where is the buffer position
2097 * of the start of the data that can send. The first byte is the
2098 * position "1". The default value is "1". The fourth argument is a
2099 * facultative integer that represents where is the buffer position
2100 * of the end of the data that can send. The default is the last byte.
2101 */
2102static int hlua_socket_send(struct lua_State *L)
2103{
2104 int i;
2105 int j;
2106 const char *buf;
2107 size_t buf_len;
2108
2109 /* Check number of arguments. */
2110 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2111 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2112
2113 /* Get the string. */
2114 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2115
2116 /* Get and check j. */
2117 if (lua_gettop(L) == 4) {
2118 j = MAY_LJMP(luaL_checkinteger(L, 4));
2119 if (j < 0)
2120 j = buf_len + j + 1;
2121 if (j > buf_len)
2122 j = buf_len + 1;
2123 lua_pop(L, 1);
2124 }
2125 else
2126 j = buf_len;
2127
2128 /* Get and check i. */
2129 if (lua_gettop(L) == 3) {
2130 i = MAY_LJMP(luaL_checkinteger(L, 3));
2131 if (i < 0)
2132 i = buf_len + i + 1;
2133 if (i > buf_len)
2134 i = buf_len + 1;
2135 lua_pop(L, 1);
2136 } else
2137 i = 1;
2138
2139 /* Check bth i and j. */
2140 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002141 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002142 return 1;
2143 }
2144 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002145 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002146 return 1;
2147 }
2148 if (i == 0)
2149 i = 1;
2150 if (j == 0)
2151 j = 1;
2152
2153 /* Pop the string. */
2154 lua_pop(L, 1);
2155
2156 /* Update the buffer length. */
2157 buf += i - 1;
2158 buf_len = j - i + 1;
2159 lua_pushlstring(L, buf, buf_len);
2160
2161 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002162 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002163
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002164 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002165}
2166
Willy Tarreau22b0a682015-06-17 19:43:49 +02002167#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002168__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2169{
2170 static char buffer[SOCKET_INFO_MAX_LEN];
2171 int ret;
2172 int len;
2173 char *p;
2174
2175 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2176 if (ret <= 0) {
2177 lua_pushnil(L);
2178 return 1;
2179 }
2180
2181 if (ret == AF_UNIX) {
2182 lua_pushstring(L, buffer+1);
2183 return 1;
2184 }
2185 else if (ret == AF_INET6) {
2186 buffer[0] = '[';
2187 len = strlen(buffer);
2188 buffer[len] = ']';
2189 len++;
2190 buffer[len] = ':';
2191 len++;
2192 p = buffer;
2193 }
2194 else if (ret == AF_INET) {
2195 p = buffer + 1;
2196 len = strlen(p);
2197 p[len] = ':';
2198 len++;
2199 }
2200 else {
2201 lua_pushnil(L);
2202 return 1;
2203 }
2204
2205 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2206 lua_pushnil(L);
2207 return 1;
2208 }
2209
2210 lua_pushstring(L, p);
2211 return 1;
2212}
2213
2214/* Returns information about the peer of the connection. */
2215__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2216{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002217 struct hlua_socket *socket;
2218 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002219 struct xref *peer;
2220 struct appctx *appctx;
2221 struct stream_interface *si;
2222 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002223 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002224
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002225 MAY_LJMP(check_args(L, 1, "getpeername"));
2226
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002227 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002228
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002229 /* Check if we run on the same thread than the xreator thread.
2230 * We cannot access to the socket if the thread is different.
2231 */
2232 if (socket->tid != tid)
2233 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2234
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002235 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002236 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002237 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002238 lua_pushnil(L);
2239 return 1;
2240 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002241 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2242 si = appctx->owner;
2243 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002244
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002245 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002246 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002247 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002248 lua_pushnil(L);
2249 return 1;
2250 }
2251
Willy Tarreaua71f6422016-11-16 17:00:14 +01002252 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002253 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002254 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002255 lua_pushnil(L);
2256 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002257 }
2258
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002259 ret = MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2260 xref_unlock(&socket->xref, peer);
2261 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002262}
2263
2264/* Returns information about my connection side. */
2265static int hlua_socket_getsockname(struct lua_State *L)
2266{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002267 struct hlua_socket *socket;
2268 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002269 struct appctx *appctx;
2270 struct xref *peer;
2271 struct stream_interface *si;
2272 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002273 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002274
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002275 MAY_LJMP(check_args(L, 1, "getsockname"));
2276
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002277 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002278
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002279 /* Check if we run on the same thread than the xreator thread.
2280 * We cannot access to the socket if the thread is different.
2281 */
2282 if (socket->tid != tid)
2283 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2284
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002285 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002286 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002287 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002288 lua_pushnil(L);
2289 return 1;
2290 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002291 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2292 si = appctx->owner;
2293 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002294
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002295 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002296 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002297 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002298 lua_pushnil(L);
2299 return 1;
2300 }
2301
Willy Tarreaua71f6422016-11-16 17:00:14 +01002302 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002303 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002304 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002305 lua_pushnil(L);
2306 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002307 }
2308
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002309 ret = hlua_socket_info(L, &conn->addr.from);
2310 xref_unlock(&socket->xref, peer);
2311 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002312}
2313
2314/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002315static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002316 .obj_type = OBJ_TYPE_APPLET,
2317 .name = "<LUA_TCP>",
2318 .fct = hlua_socket_handler,
2319 .release = hlua_socket_release,
2320};
2321
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002322__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323{
2324 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2325 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002326 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002327 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002328 struct stream_interface *si;
2329 struct stream *s;
2330
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002331 /* Check if we run on the same thread than the xreator thread.
2332 * We cannot access to the socket if the thread is different.
2333 */
2334 if (socket->tid != tid)
2335 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2336
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002337 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002338 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002339 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002340 lua_pushnil(L);
2341 lua_pushstring(L, "Can't connect");
2342 return 2;
2343 }
2344 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2345 si = appctx->owner;
2346 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002347
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002348 /* Check if we run on the same thread than the xreator thread.
2349 * We cannot access to the socket if the thread is different.
2350 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002351 if (socket->tid != tid) {
2352 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002353 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002354 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002355
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002356 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002357 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002358 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002359 lua_pushnil(L);
2360 lua_pushstring(L, "Can't connect");
2361 return 2;
2362 }
2363
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002364 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002365
2366 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002367 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002368 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002369 lua_pushinteger(L, 1);
2370 return 1;
2371 }
2372
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002373 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2374 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002375 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002376 }
2377 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002378 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002379 return 0;
2380}
2381
2382/* This function fail or initite the connection. */
2383__LJMP static int hlua_socket_connect(struct lua_State *L)
2384{
2385 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002386 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002387 const char *ip;
2388 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002389 struct hlua *hlua;
2390 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002391 int low, high;
2392 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002393 struct xref *peer;
2394 struct stream_interface *si;
2395 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002396
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002397 if (lua_gettop(L) < 2)
2398 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002399
2400 /* Get args. */
2401 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002402
2403 /* Check if we run on the same thread than the xreator thread.
2404 * We cannot access to the socket if the thread is different.
2405 */
2406 if (socket->tid != tid)
2407 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2408
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002409 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002410 if (lua_gettop(L) >= 3) {
2411 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002412 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002413
Tim Duesterhus6edab862018-01-06 19:04:45 +01002414 /* Force the ip to end with a colon, to support IPv6 addresses
2415 * that are not enclosed within square brackets.
2416 */
2417 if (port > 0) {
2418 luaL_buffinit(L, &b);
2419 luaL_addstring(&b, ip);
2420 luaL_addchar(&b, ':');
2421 luaL_pushresult(&b);
2422 ip = lua_tolstring(L, lua_gettop(L), NULL);
2423 }
2424 }
2425
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002426 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002427 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002428 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002429 lua_pushnil(L);
2430 return 1;
2431 }
2432 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2433 si = appctx->owner;
2434 s = si_strm(si);
2435
2436 /* Initialise connection. */
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002437 conn = cs_conn(si_alloc_cs(&s->si[1], NULL));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002438 if (!conn) {
2439 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002440 WILL_LJMP(luaL_error(L, "connect: internal error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002441 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002442
Willy Tarreau3adac082015-09-26 17:51:09 +02002443 /* needed for the connection not to be closed */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002444 conn->target = s->target;
Willy Tarreau3adac082015-09-26 17:51:09 +02002445
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002446 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002447 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002448 if (!addr) {
2449 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002450 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002451 }
2452 if (low != high) {
2453 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002454 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002455 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002456 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002457
2458 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002459 if (low == 0) {
2460 if (conn->addr.to.ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002461 if (port == -1) {
2462 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002463 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002464 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002465 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2466 } else if (conn->addr.to.ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002467 if (port == -1) {
2468 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002469 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002470 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002471 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2472 }
2473 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002474
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002475 hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002476 appctx = objt_appctx(s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002477
2478 /* inform the stream that we want to be notified whenever the
2479 * connection completes.
2480 */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002481 si_applet_cant_get(&s->si[0]);
2482 si_applet_cant_put(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002483 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002484
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002485 hlua->flags |= HLUA_MUST_GC;
2486
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002487 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2488 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002489 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002490 }
2491 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002492
2493 task_wakeup(s->task, TASK_WOKEN_INIT);
2494 /* Return yield waiting for connection. */
2495
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002496 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002497
2498 return 0;
2499}
2500
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002501#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002502__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2503{
2504 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002505 struct xref *peer;
2506 struct appctx *appctx;
2507 struct stream_interface *si;
2508 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002509
2510 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2511 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002512
2513 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002514 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002515 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002516 lua_pushnil(L);
2517 return 1;
2518 }
2519 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2520 si = appctx->owner;
2521 s = si_strm(si);
2522
2523 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002524 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002525 return MAY_LJMP(hlua_socket_connect(L));
2526}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002527#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002528
2529__LJMP static int hlua_socket_setoption(struct lua_State *L)
2530{
2531 return 0;
2532}
2533
2534__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2535{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002536 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002537 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002538 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002539 struct xref *peer;
2540 struct appctx *appctx;
2541 struct stream_interface *si;
2542 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002543
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002544 MAY_LJMP(check_args(L, 2, "settimeout"));
2545
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002546 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002547
2548 /* round up for inputs that are fractions and convert to millis */
2549 dtmout = (0.5 + MAY_LJMP(luaL_checknumber(L, 2))) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002550
Thierry Fournier17a921b2018-03-08 09:59:02 +01002551 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002552 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002553 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2554
Mark Lakes56cc1252018-03-27 09:48:06 +02002555 if (dtmout > INT_MAX) /* overflow check */
2556 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d", INT_MAX));
2557
2558 tmout = MS_TO_TICKS((int)dtmout);
2559
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002560 /* Check if we run on the same thread than the xreator thread.
2561 * We cannot access to the socket if the thread is different.
2562 */
2563 if (socket->tid != tid)
2564 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2565
Mark Lakes56cc1252018-03-27 09:48:06 +02002566 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002567 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002568 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002569 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2570 WILL_LJMP(lua_error(L));
2571 return 0;
2572 }
2573 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2574 si = appctx->owner;
2575 s = si_strm(si);
2576
2577 s->req.rto = tmout;
2578 s->req.wto = tmout;
2579 s->res.rto = tmout;
2580 s->res.wto = tmout;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002581 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002582
Thierry Fourniere9636f12018-03-08 09:54:32 +01002583 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002584 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002585}
2586
2587__LJMP static int hlua_socket_new(lua_State *L)
2588{
2589 struct hlua_socket *socket;
2590 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002591 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002592 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002593
2594 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002595 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002596 hlua_pusherror(L, "socket: full stack");
2597 goto out_fail_conf;
2598 }
2599
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002600 /* Create the object: obj[0] = userdata. */
2601 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002602 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002603 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002604 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002605 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002606
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002607 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002608 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002609 hlua_pusherror(L, "socket: uninitialized pools.");
2610 goto out_fail_conf;
2611 }
2612
Willy Tarreau87b09662015-04-03 00:22:06 +02002613 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002614 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2615 lua_setmetatable(L, -2);
2616
Willy Tarreaud420a972015-04-06 00:39:18 +02002617 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002618 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002619 if (!appctx) {
2620 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002621 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002622 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002623
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002624 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002625 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002626 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2627 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002628
Willy Tarreaud420a972015-04-06 00:39:18 +02002629 /* Now create a session, task and stream for this applet */
2630 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2631 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002632 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002633 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002634 }
2635
Willy Tarreau87787ac2017-08-28 16:22:54 +02002636 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002637 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002638 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002639 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002640 }
2641
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002642 /* Initialise cross reference between stream and Lua socket object. */
2643 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002644
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002645 /* Configure "right" stream interface. this "si" is used to connect
2646 * and retrieve data from the server. The connection is initialized
2647 * with the "struct server".
2648 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002649 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002650
2651 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002652 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2653 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002654
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002655 return 1;
2656
Willy Tarreaud420a972015-04-06 00:39:18 +02002657 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002658 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002659 out_fail_sess:
2660 appctx_free(appctx);
2661 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002662 WILL_LJMP(lua_error(L));
2663 return 0;
2664}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002665
2666/*
2667 *
2668 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002669 * Class Channel
2670 *
2671 *
2672 */
2673
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002674/* The state between the channel data and the HTTP parser state can be
2675 * unconsistent, so reset the parser and call it again. Warning, this
2676 * action not revalidate the request and not send a 400 if the modified
2677 * resuest is not valid.
2678 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002679 * This function never fails. The direction is set using dir, which equals
2680 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002681 */
2682static void hlua_resynchonize_proto(struct stream *stream, int dir)
2683{
2684 /* Protocol HTTP. */
2685 if (stream->be->mode == PR_MODE_HTTP) {
2686
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002687 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002688 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002689 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002690 http_txn_reset_res(stream->txn);
2691
2692 if (stream->txn->hdr_idx.v)
2693 hdr_idx_init(&stream->txn->hdr_idx);
2694
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002695 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002696 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002697 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002698 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2699 }
2700}
2701
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002702/* This function is called before the Lua execution. It stores
2703 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002704 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002705static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002706{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002707 c->mode = stream->be->mode;
2708 switch (c->mode) {
2709 case PR_MODE_HTTP:
2710 c->data.http.dir = opt & SMP_OPT_DIR;
2711 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2712 c->data.http.state = stream->txn->req.msg_state;
2713 else
2714 c->data.http.state = stream->txn->rsp.msg_state;
2715 break;
2716 default:
2717 break;
2718 }
2719}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002720
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002721/* This function is called after the Lua execution. it
2722 * returns true if the parser state is consistent, otherwise,
2723 * it return false.
2724 *
2725 * In HTTP mode, the parser state must be in the same state
2726 * or greater when we exit the function. Even if we do a
2727 * control yield. This prevent to break the HTTP message
2728 * from the Lua code.
2729 */
2730static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2731{
2732 if (c->mode != stream->be->mode)
2733 return 0;
2734
2735 switch (c->mode) {
2736 case PR_MODE_HTTP:
2737 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002738 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002739 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2740 return stream->txn->req.msg_state >= c->data.http.state;
2741 else
2742 return stream->txn->rsp.msg_state >= c->data.http.state;
2743 default:
2744 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002745 }
2746 return 1;
2747}
2748
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002749/* Returns the struct hlua_channel join to the class channel in the
2750 * stack entry "ud" or throws an argument error.
2751 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002752__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002753{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002754 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002755}
2756
Willy Tarreau47860ed2015-03-10 14:07:50 +01002757/* Pushes the channel onto the top of the stack. If the stask does not have a
2758 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002759 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002760static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002761{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002762 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002763 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002764 return 0;
2765
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002766 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002767 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002768 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002769
2770 /* Pop a class sesison metatable and affect it to the userdata. */
2771 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2772 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002773 return 1;
2774}
2775
2776/* Duplicate all the data present in the input channel and put it
2777 * in a string LUA variables. Returns -1 and push a nil value in
2778 * the stack if the channel is closed and all the data are consumed,
2779 * returns 0 if no data are available, otherwise it returns the length
2780 * of the builded string.
2781 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002782static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002783{
2784 char *blk1;
2785 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002786 size_t len1;
2787 size_t len2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002788 int ret;
2789 luaL_Buffer b;
2790
Willy Tarreau06d80a92017-10-19 14:32:15 +02002791 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002792 if (unlikely(ret == 0))
2793 return 0;
2794
2795 if (unlikely(ret < 0)) {
2796 lua_pushnil(L);
2797 return -1;
2798 }
2799
2800 luaL_buffinit(L, &b);
2801 luaL_addlstring(&b, blk1, len1);
2802 if (unlikely(ret == 2))
2803 luaL_addlstring(&b, blk2, len2);
2804 luaL_pushresult(&b);
2805
2806 if (unlikely(ret == 2))
2807 return len1 + len2;
2808 return len1;
2809}
2810
2811/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2812 * a yield. This function keep the data in the buffer.
2813 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002814__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002815{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002816 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002817
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002818 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2819
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002820 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002821 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002822 return 1;
2823}
2824
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002825/* Check arguments for the function "hlua_channel_dup_yield". */
2826__LJMP static int hlua_channel_dup(lua_State *L)
2827{
2828 MAY_LJMP(check_args(L, 1, "dup"));
2829 MAY_LJMP(hlua_checkchannel(L, 1));
2830 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2831}
2832
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002833/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2834 * a yield. This function consumes the data in the buffer. It returns
2835 * a string containing the data or a nil pointer if no data are available
2836 * and the channel is closed.
2837 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002838__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002839{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002840 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002841 int ret;
2842
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002843 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002844
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002845 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002846 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002847 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002848
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002849 if (unlikely(ret == -1))
2850 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002851
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002852 b_sub(&chn->buf, ret);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002853 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002854 return 1;
2855}
2856
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002857/* Check arguments for the fucntion "hlua_channel_get_yield". */
2858__LJMP static int hlua_channel_get(lua_State *L)
2859{
2860 MAY_LJMP(check_args(L, 1, "get"));
2861 MAY_LJMP(hlua_checkchannel(L, 1));
2862 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2863}
2864
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002865/* This functions consumes and returns one line. If the channel is closed,
2866 * and the last data does not contains a final '\n', the data are returned
2867 * without the final '\n'. When no more data are avalaible, it returns nil
2868 * value.
2869 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002870__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002871{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002872 char *blk1;
2873 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002874 size_t len1;
2875 size_t len2;
2876 size_t len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002877 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002878 int ret;
2879 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002880
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002881 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2882
Willy Tarreau06d80a92017-10-19 14:32:15 +02002883 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002884 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002885 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002886
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002887 if (ret == -1) {
2888 lua_pushnil(L);
2889 return 1;
2890 }
2891
2892 luaL_buffinit(L, &b);
2893 luaL_addlstring(&b, blk1, len1);
2894 len = len1;
2895 if (unlikely(ret == 2)) {
2896 luaL_addlstring(&b, blk2, len2);
2897 len += len2;
2898 }
2899 luaL_pushresult(&b);
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002900 b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn) + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002901 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002902 return 1;
2903}
2904
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002905/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2906__LJMP static int hlua_channel_getline(lua_State *L)
2907{
2908 MAY_LJMP(check_args(L, 1, "getline"));
2909 MAY_LJMP(hlua_checkchannel(L, 1));
2910 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2911}
2912
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002913/* This function takes a string as input, and append it at the
2914 * input side of channel. If the data is too big, but a space
2915 * is probably available after sending some data, the function
2916 * yield. If the data is bigger than the buffer, or if the
2917 * channel is closed, it returns -1. otherwise, it returns the
2918 * amount of data writed.
2919 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002920__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002921{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002922 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002923 size_t len;
2924 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2925 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2926 int ret;
2927 int max;
2928
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002929 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2930 * the request buffer if its not required.
2931 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002932 if (chn->buf.size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002933 si_applet_cant_put(chn_prod(chn));
2934 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2935 }
2936
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002937 max = channel_recv_limit(chn) - b_data(&chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002938 if (max > len - l)
2939 max = len - l;
2940
Willy Tarreau06d80a92017-10-19 14:32:15 +02002941 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002942 if (ret == -2 || ret == -3) {
2943 lua_pushinteger(L, -1);
2944 return 1;
2945 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002946 if (ret == -1) {
2947 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002948 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002949 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002950 l += ret;
2951 lua_pop(L, 1);
2952 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002953 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002954
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002955 max = channel_recv_limit(chn) - b_data(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02002956 if (max == 0 && co_data(chn) == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002957 /* There are no space avalaible, and the output buffer is empty.
2958 * in this case, we cannot add more data, so we cannot yield,
2959 * we return the amount of copyied data.
2960 */
2961 return 1;
2962 }
2963 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002964 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002965 return 1;
2966}
2967
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002968/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002969 * of the writed string, or -1 if the channel is closed or if the
2970 * buffer size is too little for the data.
2971 */
2972__LJMP static int hlua_channel_append(lua_State *L)
2973{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002974 size_t len;
2975
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002976 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002977 MAY_LJMP(hlua_checkchannel(L, 1));
2978 MAY_LJMP(luaL_checklstring(L, 2, &len));
2979 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002980 lua_pushinteger(L, 0);
2981
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002982 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002983}
2984
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002985/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002986 * his process by cleaning the buffer. The result is a replacement
2987 * of the current data. It returns the length of the writed string,
2988 * or -1 if the channel is closed or if the buffer size is too
2989 * little for the data.
2990 */
2991__LJMP static int hlua_channel_set(lua_State *L)
2992{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002993 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002994
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002995 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002996 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002997 lua_pushinteger(L, 0);
2998
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002999 b_set_data(&chn->buf, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003000
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003001 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003002}
3003
3004/* Append data in the output side of the buffer. This data is immediatly
3005 * sent. The fcuntion returns the ammount of data writed. If the buffer
3006 * cannot contains the data, the function yield. The function returns -1
3007 * if the channel is closed.
3008 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003009__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003010{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003011 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003012 size_t len;
3013 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3014 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3015 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003016 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003017
Willy Tarreau47860ed2015-03-10 14:07:50 +01003018 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003019 lua_pushinteger(L, -1);
3020 return 1;
3021 }
3022
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003023 /* Check if the buffer is avalaible because HAProxy doesn't allocate
3024 * the request buffer if its not required.
3025 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003026 if (chn->buf.size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01003027 si_applet_cant_put(chn_prod(chn));
3028 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003029 }
3030
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003031 /* the writed data will be immediatly sent, so we can check
3032 * the avalaible space without taking in account the reserve.
3033 * The reserve is guaranted for the processing of incoming
3034 * data, because the buffer will be flushed.
3035 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003036 max = b_room(&chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003037
3038 /* If there are no space avalaible, and the output buffer is empty.
3039 * in this case, we cannot add more data, so we cannot yield,
3040 * we return the amount of copyied data.
3041 */
Willy Tarreaua79021a2018-06-15 18:07:57 +02003042 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003043 return 1;
3044
3045 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003046 if (max > len - l)
3047 max = len - l;
3048
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003049 /* The buffer avalaible size may be not contiguous. This test
3050 * detects a non contiguous buffer and realign it.
3051 */
Willy Tarreau3f679992018-06-15 15:06:42 +02003052 if (ci_space_for_replace(chn) < max)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003053 channel_slow_realign(chn, trash.area);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003054
3055 /* Copy input data in the buffer. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003056 max = b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn), str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003057
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003058 /* buffer replace considers that the input part is filled.
3059 * so, I must forward these new data in the output part.
3060 */
Willy Tarreaubcbd3932018-06-06 07:13:22 +02003061 c_adv(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003062
3063 l += max;
3064 lua_pop(L, 1);
3065 lua_pushinteger(L, l);
3066
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003067 /* If there are no space avalaible, and the output buffer is empty.
3068 * in this case, we cannot add more data, so we cannot yield,
3069 * we return the amount of copyied data.
3070 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003071 max = b_room(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003072 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003073 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003074
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003075 if (l < len) {
3076 /* If we are waiting for space in the response buffer, we
3077 * must set the flag WAKERESWR. This flag required the task
3078 * wake up if any activity is detected on the response buffer.
3079 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003080 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003081 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003082 else
3083 HLUA_SET_WAKEREQWR(hlua);
3084 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003085 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003086
3087 return 1;
3088}
3089
3090/* Just a wraper of "_hlua_channel_send". This wrapper permits
3091 * yield the LUA process, and resume it without checking the
3092 * input arguments.
3093 */
3094__LJMP static int hlua_channel_send(lua_State *L)
3095{
3096 MAY_LJMP(check_args(L, 2, "send"));
3097 lua_pushinteger(L, 0);
3098
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003099 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003100}
3101
3102/* This function forward and amount of butes. The data pass from
3103 * the input side of the buffer to the output side, and can be
3104 * forwarded. This function never fails.
3105 *
3106 * The Lua function takes an amount of bytes to be forwarded in
3107 * imput. It returns the number of bytes forwarded.
3108 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003109__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003110{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003111 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003112 int len;
3113 int l;
3114 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003115 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003116
3117 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3118 len = MAY_LJMP(luaL_checkinteger(L, 2));
3119 l = MAY_LJMP(luaL_checkinteger(L, -1));
3120
3121 max = len - l;
Willy Tarreaua79021a2018-06-15 18:07:57 +02003122 if (max > ci_data(chn))
3123 max = ci_data(chn);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003124 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003125 l += max;
3126
3127 lua_pop(L, 1);
3128 lua_pushinteger(L, l);
3129
3130 /* Check if it miss bytes to forward. */
3131 if (l < len) {
3132 /* The the input channel or the output channel are closed, we
3133 * must return the amount of data forwarded.
3134 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003135 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003136 return 1;
3137
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003138 /* If we are waiting for space data in the response buffer, we
3139 * must set the flag WAKERESWR. This flag required the task
3140 * wake up if any activity is detected on the response buffer.
3141 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003142 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003143 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003144 else
3145 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003146
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003147 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01003148 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003149 }
3150
3151 return 1;
3152}
3153
3154/* Just check the input and prepare the stack for the previous
3155 * function "hlua_channel_forward_yield"
3156 */
3157__LJMP static int hlua_channel_forward(lua_State *L)
3158{
3159 MAY_LJMP(check_args(L, 2, "forward"));
3160 MAY_LJMP(hlua_checkchannel(L, 1));
3161 MAY_LJMP(luaL_checkinteger(L, 2));
3162
3163 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003164 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003165}
3166
3167/* Just returns the number of bytes available in the input
3168 * side of the buffer. This function never fails.
3169 */
3170__LJMP static int hlua_channel_get_in_len(lua_State *L)
3171{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003172 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003173
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003174 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003175 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003176 lua_pushinteger(L, ci_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003177 return 1;
3178}
3179
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003180/* Returns true if the channel is full. */
3181__LJMP static int hlua_channel_is_full(lua_State *L)
3182{
3183 struct channel *chn;
3184 int rem;
3185
3186 MAY_LJMP(check_args(L, 1, "is_full"));
3187 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3188
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003189 rem = b_room(&chn->buf);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003190 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
3191
3192 lua_pushboolean(L, rem <= 0);
3193 return 1;
3194}
3195
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003196/* Just returns the number of bytes available in the output
3197 * side of the buffer. This function never fails.
3198 */
3199__LJMP static int hlua_channel_get_out_len(lua_State *L)
3200{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003201 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003202
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003203 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003204 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003205 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003206 return 1;
3207}
3208
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003209/*
3210 *
3211 *
3212 * Class Fetches
3213 *
3214 *
3215 */
3216
3217/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003218 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003219 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003220__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003221{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003222 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003223}
3224
3225/* This function creates and push in the stack a fetch object according
3226 * with a current TXN.
3227 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003228static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003229{
Willy Tarreau7073c472015-04-06 11:15:40 +02003230 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003231
3232 /* Check stack size. */
3233 if (!lua_checkstack(L, 3))
3234 return 0;
3235
3236 /* Create the object: obj[0] = userdata.
3237 * Note that the base of the Fetches object is the
3238 * transaction object.
3239 */
3240 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003241 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003242 lua_rawseti(L, -2, 0);
3243
Willy Tarreau7073c472015-04-06 11:15:40 +02003244 hsmp->s = txn->s;
3245 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003246 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003247 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003248
3249 /* Pop a class sesison metatable and affect it to the userdata. */
3250 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3251 lua_setmetatable(L, -2);
3252
3253 return 1;
3254}
3255
3256/* This function is an LUA binding. It is called with each sample-fetch.
3257 * It uses closure argument to store the associated sample-fetch. It
3258 * returns only one argument or throws an error. An error is thrown
3259 * only if an error is encountered during the argument parsing. If
3260 * the "sample-fetch" function fails, nil is returned.
3261 */
3262__LJMP static int hlua_run_sample_fetch(lua_State *L)
3263{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003264 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003265 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003266 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003267 int i;
3268 struct sample smp;
3269
3270 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003271 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003272
3273 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003274 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003275
Thierry FOURNIERca988662015-12-20 18:43:03 +01003276 /* Check execution authorization. */
3277 if (f->use & SMP_USE_HTTP_ANY &&
3278 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3279 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3280 "is not available in Lua services", f->kw);
3281 WILL_LJMP(lua_error(L));
3282 }
3283
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003284 /* Get extra arguments. */
3285 for (i = 0; i < lua_gettop(L) - 1; i++) {
3286 if (i >= ARGM_NBARGS)
3287 break;
3288 hlua_lua2arg(L, i + 2, &args[i]);
3289 }
3290 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003291 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003292
3293 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003294 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003295
3296 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003297 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003298 lua_pushfstring(L, "error in arguments");
3299 WILL_LJMP(lua_error(L));
3300 }
3301
3302 /* Initialise the sample. */
3303 memset(&smp, 0, sizeof(smp));
3304
3305 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003306 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003307 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003308 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003309 lua_pushstring(L, "");
3310 else
3311 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003312 return 1;
3313 }
3314
3315 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003316 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003317 hlua_smp2lua_str(L, &smp);
3318 else
3319 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003320 return 1;
3321}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003322
3323/*
3324 *
3325 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003326 * Class Converters
3327 *
3328 *
3329 */
3330
3331/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003332 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003333 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003334__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003335{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003336 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003337}
3338
3339/* This function creates and push in the stack a Converters object
3340 * according with a current TXN.
3341 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003342static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003343{
Willy Tarreau7073c472015-04-06 11:15:40 +02003344 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003345
3346 /* Check stack size. */
3347 if (!lua_checkstack(L, 3))
3348 return 0;
3349
3350 /* Create the object: obj[0] = userdata.
3351 * Note that the base of the Converters object is the
3352 * same than the TXN object.
3353 */
3354 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003355 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003356 lua_rawseti(L, -2, 0);
3357
Willy Tarreau7073c472015-04-06 11:15:40 +02003358 hsmp->s = txn->s;
3359 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003360 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003361 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003362
Willy Tarreau87b09662015-04-03 00:22:06 +02003363 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003364 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3365 lua_setmetatable(L, -2);
3366
3367 return 1;
3368}
3369
3370/* This function is an LUA binding. It is called with each converter.
3371 * It uses closure argument to store the associated converter. It
3372 * returns only one argument or throws an error. An error is thrown
3373 * only if an error is encountered during the argument parsing. If
3374 * the converter function function fails, nil is returned.
3375 */
3376__LJMP static int hlua_run_sample_conv(lua_State *L)
3377{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003378 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003379 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003380 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003381 int i;
3382 struct sample smp;
3383
3384 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003385 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003386
3387 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003388 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003389
3390 /* Get extra arguments. */
3391 for (i = 0; i < lua_gettop(L) - 2; i++) {
3392 if (i >= ARGM_NBARGS)
3393 break;
3394 hlua_lua2arg(L, i + 3, &args[i]);
3395 }
3396 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003397 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003398
3399 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003400 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003401
3402 /* Run the special args checker. */
3403 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3404 hlua_pusherror(L, "error in arguments");
3405 WILL_LJMP(lua_error(L));
3406 }
3407
3408 /* Initialise the sample. */
3409 if (!hlua_lua2smp(L, 2, &smp)) {
3410 hlua_pusherror(L, "error in the input argument");
3411 WILL_LJMP(lua_error(L));
3412 }
3413
Willy Tarreau1777ea62016-03-10 16:15:46 +01003414 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3415
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003416 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003417 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003418 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003419 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003420 WILL_LJMP(lua_error(L));
3421 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003422 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3423 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003424 hlua_pusherror(L, "error during the input argument casting");
3425 WILL_LJMP(lua_error(L));
3426 }
3427
3428 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003429 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003430 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003431 lua_pushstring(L, "");
3432 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003433 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003434 return 1;
3435 }
3436
3437 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003438 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003439 hlua_smp2lua_str(L, &smp);
3440 else
3441 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003442 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003443}
3444
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003445/*
3446 *
3447 *
3448 * Class AppletTCP
3449 *
3450 *
3451 */
3452
3453/* Returns a struct hlua_txn if the stack entry "ud" is
3454 * a class stream, otherwise it throws an error.
3455 */
3456__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3457{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003458 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003459}
3460
3461/* This function creates and push in the stack an Applet object
3462 * according with a current TXN.
3463 */
3464static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3465{
3466 struct hlua_appctx *appctx;
3467 struct stream_interface *si = ctx->owner;
3468 struct stream *s = si_strm(si);
3469 struct proxy *p = s->be;
3470
3471 /* Check stack size. */
3472 if (!lua_checkstack(L, 3))
3473 return 0;
3474
3475 /* Create the object: obj[0] = userdata.
3476 * Note that the base of the Converters object is the
3477 * same than the TXN object.
3478 */
3479 lua_newtable(L);
3480 appctx = lua_newuserdata(L, sizeof(*appctx));
3481 lua_rawseti(L, -2, 0);
3482 appctx->appctx = ctx;
3483 appctx->htxn.s = s;
3484 appctx->htxn.p = p;
3485
3486 /* Create the "f" field that contains a list of fetches. */
3487 lua_pushstring(L, "f");
3488 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3489 return 0;
3490 lua_settable(L, -3);
3491
3492 /* Create the "sf" field that contains a list of stringsafe fetches. */
3493 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003494 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003495 return 0;
3496 lua_settable(L, -3);
3497
3498 /* Create the "c" field that contains a list of converters. */
3499 lua_pushstring(L, "c");
3500 if (!hlua_converters_new(L, &appctx->htxn, 0))
3501 return 0;
3502 lua_settable(L, -3);
3503
3504 /* Create the "sc" field that contains a list of stringsafe converters. */
3505 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003506 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003507 return 0;
3508 lua_settable(L, -3);
3509
3510 /* Pop a class stream metatable and affect it to the table. */
3511 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3512 lua_setmetatable(L, -2);
3513
3514 return 1;
3515}
3516
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003517__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3518{
3519 struct hlua_appctx *appctx;
3520 struct stream *s;
3521 const char *name;
3522 size_t len;
3523 struct sample smp;
3524
3525 MAY_LJMP(check_args(L, 3, "set_var"));
3526
3527 /* It is useles to retrieve the stream, but this function
3528 * runs only in a stream context.
3529 */
3530 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3531 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3532 s = appctx->htxn.s;
3533
3534 /* Converts the third argument in a sample. */
3535 hlua_lua2smp(L, 3, &smp);
3536
3537 /* Store the sample in a variable. */
3538 smp_set_owner(&smp, s->be, s->sess, s, 0);
3539 vars_set_by_name(name, len, &smp);
3540 return 0;
3541}
3542
3543__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3544{
3545 struct hlua_appctx *appctx;
3546 struct stream *s;
3547 const char *name;
3548 size_t len;
3549 struct sample smp;
3550
3551 MAY_LJMP(check_args(L, 2, "unset_var"));
3552
3553 /* It is useles to retrieve the stream, but this function
3554 * runs only in a stream context.
3555 */
3556 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3557 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3558 s = appctx->htxn.s;
3559
3560 /* Unset the variable. */
3561 smp_set_owner(&smp, s->be, s->sess, s, 0);
3562 vars_unset_by_name(name, len, &smp);
3563 return 0;
3564}
3565
3566__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3567{
3568 struct hlua_appctx *appctx;
3569 struct stream *s;
3570 const char *name;
3571 size_t len;
3572 struct sample smp;
3573
3574 MAY_LJMP(check_args(L, 2, "get_var"));
3575
3576 /* It is useles to retrieve the stream, but this function
3577 * runs only in a stream context.
3578 */
3579 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3580 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3581 s = appctx->htxn.s;
3582
3583 smp_set_owner(&smp, s->be, s->sess, s, 0);
3584 if (!vars_get_by_name(name, len, &smp)) {
3585 lua_pushnil(L);
3586 return 1;
3587 }
3588
3589 return hlua_smp2lua(L, &smp);
3590}
3591
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003592__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3593{
3594 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3595 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003596 struct hlua *hlua;
3597
3598 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003599 if (!s->hlua)
3600 return 0;
3601 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003602
3603 MAY_LJMP(check_args(L, 2, "set_priv"));
3604
3605 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003606 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003607
3608 /* Get and store new value. */
3609 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3610 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3611
3612 return 0;
3613}
3614
3615__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3616{
3617 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3618 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003619 struct hlua *hlua;
3620
3621 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003622 if (!s->hlua) {
3623 lua_pushnil(L);
3624 return 1;
3625 }
3626 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003627
3628 /* Push configuration index in the stack. */
3629 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3630
3631 return 1;
3632}
3633
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003634/* If expected data not yet available, it returns a yield. This function
3635 * consumes the data in the buffer. It returns a string containing the
3636 * data. This string can be empty.
3637 */
3638__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3639{
3640 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3641 struct stream_interface *si = appctx->appctx->owner;
3642 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003643 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003644 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003645 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003646 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003647
3648 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003649 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003650
3651 /* Data not yet avalaible. return yield. */
3652 if (ret == 0) {
3653 si_applet_cant_get(si);
3654 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3655 }
3656
3657 /* End of data: commit the total strings and return. */
3658 if (ret < 0) {
3659 luaL_pushresult(&appctx->b);
3660 return 1;
3661 }
3662
3663 /* Ensure that the block 2 length is usable. */
3664 if (ret == 1)
3665 len2 = 0;
3666
3667 /* dont check the max length read and dont check. */
3668 luaL_addlstring(&appctx->b, blk1, len1);
3669 luaL_addlstring(&appctx->b, blk2, len2);
3670
3671 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003672 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003673 luaL_pushresult(&appctx->b);
3674 return 1;
3675}
3676
3677/* Check arguments for the fucntion "hlua_channel_get_yield". */
3678__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3679{
3680 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3681
3682 /* Initialise the string catenation. */
3683 luaL_buffinit(L, &appctx->b);
3684
3685 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3686}
3687
3688/* If expected data not yet available, it returns a yield. This function
3689 * consumes the data in the buffer. It returns a string containing the
3690 * data. This string can be empty.
3691 */
3692__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3693{
3694 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3695 struct stream_interface *si = appctx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003696 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003697 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003698 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003699 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003700 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003701 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003702
3703 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003704 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003705
3706 /* Data not yet avalaible. return yield. */
3707 if (ret == 0) {
3708 si_applet_cant_get(si);
3709 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3710 }
3711
3712 /* End of data: commit the total strings and return. */
3713 if (ret < 0) {
3714 luaL_pushresult(&appctx->b);
3715 return 1;
3716 }
3717
3718 /* Ensure that the block 2 length is usable. */
3719 if (ret == 1)
3720 len2 = 0;
3721
3722 if (len == -1) {
3723
3724 /* If len == -1, catenate all the data avalaile and
3725 * yield because we want to get all the data until
3726 * the end of data stream.
3727 */
3728 luaL_addlstring(&appctx->b, blk1, len1);
3729 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003730 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003731 si_applet_cant_get(si);
3732 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3733
3734 } else {
3735
3736 /* Copy the fisrt block caping to the length required. */
3737 if (len1 > len)
3738 len1 = len;
3739 luaL_addlstring(&appctx->b, blk1, len1);
3740 len -= len1;
3741
3742 /* Copy the second block. */
3743 if (len2 > len)
3744 len2 = len;
3745 luaL_addlstring(&appctx->b, blk2, len2);
3746 len -= len2;
3747
3748 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003749 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003750
3751 /* If we are no other data avalaible, yield waiting for new data. */
3752 if (len > 0) {
3753 lua_pushinteger(L, len);
3754 lua_replace(L, 2);
3755 si_applet_cant_get(si);
3756 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3757 }
3758
3759 /* return the result. */
3760 luaL_pushresult(&appctx->b);
3761 return 1;
3762 }
3763
3764 /* we never executes this */
3765 hlua_pusherror(L, "Lua: internal error");
3766 WILL_LJMP(lua_error(L));
3767 return 0;
3768}
3769
3770/* Check arguments for the fucntion "hlua_channel_get_yield". */
3771__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3772{
3773 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3774 int len = -1;
3775
3776 if (lua_gettop(L) > 2)
3777 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3778 if (lua_gettop(L) >= 2) {
3779 len = MAY_LJMP(luaL_checkinteger(L, 2));
3780 lua_pop(L, 1);
3781 }
3782
3783 /* Confirm or set the required length */
3784 lua_pushinteger(L, len);
3785
3786 /* Initialise the string catenation. */
3787 luaL_buffinit(L, &appctx->b);
3788
3789 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3790}
3791
3792/* Append data in the output side of the buffer. This data is immediatly
3793 * sent. The fcuntion returns the ammount of data writed. If the buffer
3794 * cannot contains the data, the function yield. The function returns -1
3795 * if the channel is closed.
3796 */
3797__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3798{
3799 size_t len;
3800 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3801 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3802 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3803 struct stream_interface *si = appctx->appctx->owner;
3804 struct channel *chn = si_ic(si);
3805 int max;
3806
3807 /* Get the max amount of data which can write as input in the channel. */
3808 max = channel_recv_max(chn);
3809 if (max > (len - l))
3810 max = len - l;
3811
3812 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003813 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003814
3815 /* update counters. */
3816 l += max;
3817 lua_pop(L, 1);
3818 lua_pushinteger(L, l);
3819
3820 /* If some data is not send, declares the situation to the
3821 * applet, and returns a yield.
3822 */
3823 if (l < len) {
3824 si_applet_cant_put(si);
3825 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3826 }
3827
3828 return 1;
3829}
3830
3831/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3832 * yield the LUA process, and resume it without checking the
3833 * input arguments.
3834 */
3835__LJMP static int hlua_applet_tcp_send(lua_State *L)
3836{
3837 MAY_LJMP(check_args(L, 2, "send"));
3838 lua_pushinteger(L, 0);
3839
3840 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3841}
3842
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003843/*
3844 *
3845 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003846 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003847 *
3848 *
3849 */
3850
3851/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003852 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003853 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003854__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003855{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003856 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003857}
3858
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003859/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003860 * according with a current TXN.
3861 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003862static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003863{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003864 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003865 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003866 struct stream_interface *si = ctx->owner;
3867 struct stream *s = si_strm(si);
3868 struct proxy *px = s->be;
3869 struct http_txn *txn = s->txn;
3870 const char *path;
3871 const char *end;
3872 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003873
3874 /* Check stack size. */
3875 if (!lua_checkstack(L, 3))
3876 return 0;
3877
3878 /* Create the object: obj[0] = userdata.
3879 * Note that the base of the Converters object is the
3880 * same than the TXN object.
3881 */
3882 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003883 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003884 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003885 appctx->appctx = ctx;
3886 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003887 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003888 appctx->htxn.s = s;
3889 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003890
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003891 /* Create the "f" field that contains a list of fetches. */
3892 lua_pushstring(L, "f");
3893 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3894 return 0;
3895 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003896
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003897 /* Create the "sf" field that contains a list of stringsafe fetches. */
3898 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003899 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003900 return 0;
3901 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003902
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003903 /* Create the "c" field that contains a list of converters. */
3904 lua_pushstring(L, "c");
3905 if (!hlua_converters_new(L, &appctx->htxn, 0))
3906 return 0;
3907 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003908
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003909 /* Create the "sc" field that contains a list of stringsafe converters. */
3910 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003911 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003912 return 0;
3913 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003914
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003915 /* Stores the request method. */
3916 lua_pushstring(L, "method");
Willy Tarreaua79021a2018-06-15 18:07:57 +02003917 lua_pushlstring(L, ci_head(txn->req.chn), txn->req.sl.rq.m_l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003918 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003919
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003920 /* Stores the http version. */
3921 lua_pushstring(L, "version");
Willy Tarreaua79021a2018-06-15 18:07:57 +02003922 lua_pushlstring(L, ci_head(txn->req.chn) + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003923 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003924
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003925 /* creates an array of headers. hlua_http_get_headers() crates and push
3926 * the array on the top of the stack.
3927 */
3928 lua_pushstring(L, "headers");
3929 htxn.s = s;
3930 htxn.p = px;
3931 htxn.dir = SMP_OPT_DIR_REQ;
3932 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3933 return 0;
3934 lua_settable(L, -3);
3935
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003936 /* Get path and qs */
3937 path = http_get_path(txn);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003938 if (path) {
Willy Tarreaua79021a2018-06-15 18:07:57 +02003939 end = ci_head(txn->req.chn) + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003940 p = path;
3941 while (p < end && *p != '?')
3942 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003943
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003944 /* Stores the request path. */
3945 lua_pushstring(L, "path");
3946 lua_pushlstring(L, path, p - path);
3947 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003948
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003949 /* Stores the query string. */
3950 lua_pushstring(L, "qs");
3951 if (*p == '?')
3952 p++;
3953 lua_pushlstring(L, p, end - p);
3954 lua_settable(L, -3);
3955 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003956
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003957 /* Stores the request path. */
3958 lua_pushstring(L, "length");
3959 lua_pushinteger(L, txn->req.body_len);
3960 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003961
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003962 /* Create an array of HTTP request headers. */
3963 lua_pushstring(L, "headers");
3964 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3965 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003966
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003967 /* Create an empty array of HTTP request headers. */
3968 lua_pushstring(L, "response");
3969 lua_newtable(L);
3970 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003971
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003972 /* Pop a class stream metatable and affect it to the table. */
3973 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3974 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003975
3976 return 1;
3977}
3978
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003979__LJMP static int hlua_applet_http_set_var(lua_State *L)
3980{
3981 struct hlua_appctx *appctx;
3982 struct stream *s;
3983 const char *name;
3984 size_t len;
3985 struct sample smp;
3986
3987 MAY_LJMP(check_args(L, 3, "set_var"));
3988
3989 /* It is useles to retrieve the stream, but this function
3990 * runs only in a stream context.
3991 */
3992 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3993 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3994 s = appctx->htxn.s;
3995
3996 /* Converts the third argument in a sample. */
3997 hlua_lua2smp(L, 3, &smp);
3998
3999 /* Store the sample in a variable. */
4000 smp_set_owner(&smp, s->be, s->sess, s, 0);
4001 vars_set_by_name(name, len, &smp);
4002 return 0;
4003}
4004
4005__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4006{
4007 struct hlua_appctx *appctx;
4008 struct stream *s;
4009 const char *name;
4010 size_t len;
4011 struct sample smp;
4012
4013 MAY_LJMP(check_args(L, 2, "unset_var"));
4014
4015 /* It is useles to retrieve the stream, but this function
4016 * runs only in a stream context.
4017 */
4018 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4019 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4020 s = appctx->htxn.s;
4021
4022 /* Unset the variable. */
4023 smp_set_owner(&smp, s->be, s->sess, s, 0);
4024 vars_unset_by_name(name, len, &smp);
4025 return 0;
4026}
4027
4028__LJMP static int hlua_applet_http_get_var(lua_State *L)
4029{
4030 struct hlua_appctx *appctx;
4031 struct stream *s;
4032 const char *name;
4033 size_t len;
4034 struct sample smp;
4035
4036 MAY_LJMP(check_args(L, 2, "get_var"));
4037
4038 /* It is useles to retrieve the stream, but this function
4039 * runs only in a stream context.
4040 */
4041 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4042 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4043 s = appctx->htxn.s;
4044
4045 smp_set_owner(&smp, s->be, s->sess, s, 0);
4046 if (!vars_get_by_name(name, len, &smp)) {
4047 lua_pushnil(L);
4048 return 1;
4049 }
4050
4051 return hlua_smp2lua(L, &smp);
4052}
4053
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004054__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4055{
4056 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4057 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004058 struct hlua *hlua;
4059
4060 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004061 if (!s->hlua)
4062 return 0;
4063 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004064
4065 MAY_LJMP(check_args(L, 2, "set_priv"));
4066
4067 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004068 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004069
4070 /* Get and store new value. */
4071 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4072 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4073
4074 return 0;
4075}
4076
4077__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4078{
4079 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4080 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004081 struct hlua *hlua;
4082
4083 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004084 if (!s->hlua) {
4085 lua_pushnil(L);
4086 return 1;
4087 }
4088 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004089
4090 /* Push configuration index in the stack. */
4091 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4092
4093 return 1;
4094}
4095
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004096/* If expected data not yet available, it returns a yield. This function
4097 * consumes the data in the buffer. It returns a string containing the
4098 * data. This string can be empty.
4099 */
4100__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004101{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004102 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4103 struct stream_interface *si = appctx->appctx->owner;
4104 struct channel *chn = si_ic(si);
4105 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004106 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004107 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004108 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004109 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004110
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004111 /* Maybe we cant send a 100-continue ? */
4112 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau06d80a92017-10-19 14:32:15 +02004113 ret = ci_putblk(chn, HTTP_100C, strlen(HTTP_100C));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004114 /* if ret == -2 or -3 the channel closed or the message si too
4115 * big for the buffers. We cant send anything. So, we ignoring
4116 * the error, considers that the 100-continue is sent, and try
4117 * to receive.
4118 * If ret is -1, we dont have room in the buffer, so we yield.
4119 */
4120 if (ret == -1) {
4121 si_applet_cant_put(si);
4122 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4123 }
4124 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4125 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004126
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004127 /* Check for the end of the data. */
4128 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4129 luaL_pushresult(&appctx->b);
4130 return 1;
4131 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004132
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004133 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004134 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004135
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004136 /* Data not yet avalaible. return yield. */
4137 if (ret == 0) {
4138 si_applet_cant_get(si);
4139 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4140 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004141
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004142 /* End of data: commit the total strings and return. */
4143 if (ret < 0) {
4144 luaL_pushresult(&appctx->b);
4145 return 1;
4146 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004147
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004148 /* Ensure that the block 2 length is usable. */
4149 if (ret == 1)
4150 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004151
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004152 /* Copy the fisrt block caping to the length required. */
4153 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4154 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4155 luaL_addlstring(&appctx->b, blk1, len1);
4156 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004157
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004158 /* Copy the second block. */
4159 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4160 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4161 luaL_addlstring(&appctx->b, blk2, len2);
4162 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004163
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004164 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004165 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004166 luaL_pushresult(&appctx->b);
4167 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004168}
4169
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004170/* Check arguments for the fucntion "hlua_channel_get_yield". */
4171__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004172{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004173 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004174
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004175 /* Initialise the string catenation. */
4176 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004177
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004178 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004179}
4180
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004181/* If expected data not yet available, it returns a yield. This function
4182 * consumes the data in the buffer. It returns a string containing the
4183 * data. This string can be empty.
4184 */
4185__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004186{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004187 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4188 struct stream_interface *si = appctx->appctx->owner;
4189 int len = MAY_LJMP(luaL_checkinteger(L, 2));
4190 struct channel *chn = si_ic(si);
4191 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004192 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004193 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004194 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004195 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004196
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004197 /* Maybe we cant send a 100-continue ? */
4198 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau06d80a92017-10-19 14:32:15 +02004199 ret = ci_putblk(chn, HTTP_100C, strlen(HTTP_100C));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004200 /* if ret == -2 or -3 the channel closed or the message si too
4201 * big for the buffers. We cant send anything. So, we ignoring
4202 * the error, considers that the 100-continue is sent, and try
4203 * to receive.
4204 * If ret is -1, we dont have room in the buffer, so we yield.
4205 */
4206 if (ret == -1) {
4207 si_applet_cant_put(si);
4208 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4209 }
4210 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4211 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004212
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004213 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004214 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004215
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004216 /* Data not yet avalaible. return yield. */
4217 if (ret == 0) {
4218 si_applet_cant_get(si);
4219 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4220 }
4221
4222 /* End of data: commit the total strings and return. */
4223 if (ret < 0) {
4224 luaL_pushresult(&appctx->b);
4225 return 1;
4226 }
4227
4228 /* Ensure that the block 2 length is usable. */
4229 if (ret == 1)
4230 len2 = 0;
4231
4232 /* Copy the fisrt block caping to the length required. */
4233 if (len1 > len)
4234 len1 = len;
4235 luaL_addlstring(&appctx->b, blk1, len1);
4236 len -= len1;
4237
4238 /* Copy the second block. */
4239 if (len2 > len)
4240 len2 = len;
4241 luaL_addlstring(&appctx->b, blk2, len2);
4242 len -= len2;
4243
4244 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004245 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004246 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4247 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4248
4249 /* If we are no other data avalaible, yield waiting for new data. */
4250 if (len > 0) {
4251 lua_pushinteger(L, len);
4252 lua_replace(L, 2);
4253 si_applet_cant_get(si);
4254 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4255 }
4256
4257 /* return the result. */
4258 luaL_pushresult(&appctx->b);
4259 return 1;
4260}
4261
4262/* Check arguments for the fucntion "hlua_channel_get_yield". */
4263__LJMP static int hlua_applet_http_recv(lua_State *L)
4264{
4265 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4266 int len = -1;
4267
4268 /* Check arguments. */
4269 if (lua_gettop(L) > 2)
4270 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4271 if (lua_gettop(L) >= 2) {
4272 len = MAY_LJMP(luaL_checkinteger(L, 2));
4273 lua_pop(L, 1);
4274 }
4275
4276 /* Check the required length */
4277 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4278 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4279 lua_pushinteger(L, len);
4280
4281 /* Initialise the string catenation. */
4282 luaL_buffinit(L, &appctx->b);
4283
4284 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4285}
4286
4287/* Append data in the output side of the buffer. This data is immediatly
4288 * sent. The fcuntion returns the ammount of data writed. If the buffer
4289 * cannot contains the data, the function yield. The function returns -1
4290 * if the channel is closed.
4291 */
4292__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4293{
4294 size_t len;
4295 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4296 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4297 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4298 struct stream_interface *si = appctx->appctx->owner;
4299 struct channel *chn = si_ic(si);
4300 int max;
4301
4302 /* Get the max amount of data which can write as input in the channel. */
4303 max = channel_recv_max(chn);
4304 if (max > (len - l))
4305 max = len - l;
4306
4307 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004308 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004309
4310 /* update counters. */
4311 l += max;
4312 lua_pop(L, 1);
4313 lua_pushinteger(L, l);
4314
4315 /* If some data is not send, declares the situation to the
4316 * applet, and returns a yield.
4317 */
4318 if (l < len) {
4319 si_applet_cant_put(si);
4320 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
4321 }
4322
4323 return 1;
4324}
4325
4326/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4327 * yield the LUA process, and resume it without checking the
4328 * input arguments.
4329 */
4330__LJMP static int hlua_applet_http_send(lua_State *L)
4331{
4332 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4333 size_t len;
4334 char hex[10];
4335
4336 MAY_LJMP(luaL_checklstring(L, 2, &len));
4337
4338 /* If transfer encoding chunked is selected, we surround the data
4339 * by chunk data.
4340 */
4341 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4342 snprintf(hex, 9, "%x", (unsigned int)len);
4343 lua_pushfstring(L, "%s\r\n", hex);
4344 lua_insert(L, 2); /* swap the last 2 entries. */
4345 lua_pushstring(L, "\r\n");
4346 lua_concat(L, 3);
4347 }
4348
4349 /* This interger is used for followinf the amount of data sent. */
4350 lua_pushinteger(L, 0);
4351
4352 /* We want to send some data. Headers must be sent. */
4353 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4354 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4355 WILL_LJMP(lua_error(L));
4356 }
4357
4358 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4359}
4360
4361__LJMP static int hlua_applet_http_addheader(lua_State *L)
4362{
4363 const char *name;
4364 int ret;
4365
4366 MAY_LJMP(hlua_checkapplet_http(L, 1));
4367 name = MAY_LJMP(luaL_checkstring(L, 2));
4368 MAY_LJMP(luaL_checkstring(L, 3));
4369
4370 /* Push in the stack the "response" entry. */
4371 ret = lua_getfield(L, 1, "response");
4372 if (ret != LUA_TTABLE) {
4373 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4374 "is expected as an array. %s found", lua_typename(L, ret));
4375 WILL_LJMP(lua_error(L));
4376 }
4377
4378 /* check if the header is already registered if it is not
4379 * the case, register it.
4380 */
4381 ret = lua_getfield(L, -1, name);
4382 if (ret == LUA_TNIL) {
4383
4384 /* Entry not found. */
4385 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4386
4387 /* Insert the new header name in the array in the top of the stack.
4388 * It left the new array in the top of the stack.
4389 */
4390 lua_newtable(L);
4391 lua_pushvalue(L, 2);
4392 lua_pushvalue(L, -2);
4393 lua_settable(L, -4);
4394
4395 } else if (ret != LUA_TTABLE) {
4396
4397 /* corruption error. */
4398 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4399 "is expected as an array. %s found", name, lua_typename(L, ret));
4400 WILL_LJMP(lua_error(L));
4401 }
4402
4403 /* Now the top od thestack is an array of values. We push
4404 * the header value as new entry.
4405 */
4406 lua_pushvalue(L, 3);
4407 ret = lua_rawlen(L, -2);
4408 lua_rawseti(L, -2, ret + 1);
4409 lua_pushboolean(L, 1);
4410 return 1;
4411}
4412
4413__LJMP static int hlua_applet_http_status(lua_State *L)
4414{
4415 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4416 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004417 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004418
4419 if (status < 100 || status > 599) {
4420 lua_pushboolean(L, 0);
4421 return 1;
4422 }
4423
4424 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004425 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004426 lua_pushboolean(L, 1);
4427 return 1;
4428}
4429
4430/* We will build the status line and the headers of the HTTP response.
4431 * We will try send at once if its not possible, we give back the hand
4432 * waiting for more room.
4433 */
4434__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4435{
4436 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4437 struct stream_interface *si = appctx->appctx->owner;
4438 struct channel *chn = si_ic(si);
4439 int ret;
4440 size_t len;
4441 const char *msg;
4442
4443 /* Get the message as the first argument on the stack. */
4444 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4445
4446 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004447 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004448
4449 /* if ret == -2 or -3 the channel closed or the message si too
4450 * big for the buffers.
4451 */
4452 if (ret == -2 || ret == -3) {
4453 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4454 WILL_LJMP(lua_error(L));
4455 }
4456
4457 /* If ret is -1, we dont have room in the buffer, so we yield. */
4458 if (ret == -1) {
4459 si_applet_cant_put(si);
4460 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4461 }
4462
4463 /* Headers sent, set the flag. */
4464 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4465 return 0;
4466}
4467
4468__LJMP static int hlua_applet_http_start_response(lua_State *L)
4469{
Willy Tarreau83061a82018-07-13 11:56:34 +02004470 struct buffer *tmp = get_trash_chunk();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004471 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004472 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02004473 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004474 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02004475 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004476 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004477 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004478 int hdr_chunked = 0;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004479 const char *reason = appctx->appctx->ctx.hlua_apphttp.reason;
4480
4481 if (reason == NULL)
4482 reason = get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004483
4484 /* Use the same http version than the request. */
4485 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004486 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004487 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004488 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004489
4490 /* Get the array associated to the field "response" in the object AppletHTTP. */
4491 lua_pushvalue(L, 0);
4492 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4493 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4494 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4495 WILL_LJMP(lua_error(L));
4496 }
4497
4498 /* Browse the list of headers. */
4499 lua_pushnil(L);
4500 while(lua_next(L, -2) != 0) {
4501
4502 /* We expect a string as -2. */
4503 if (lua_type(L, -2) != LUA_TSTRING) {
4504 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4505 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4506 lua_typename(L, lua_type(L, -2)));
4507 WILL_LJMP(lua_error(L));
4508 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004509 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004510
4511 /* We expect an array as -1. */
4512 if (lua_type(L, -1) != LUA_TTABLE) {
4513 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4514 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4515 name,
4516 lua_typename(L, lua_type(L, -1)));
4517 WILL_LJMP(lua_error(L));
4518 }
4519
4520 /* Browse the table who is on the top of the stack. */
4521 lua_pushnil(L);
4522 while(lua_next(L, -2) != 0) {
4523
4524 /* We expect a number as -2. */
4525 if (lua_type(L, -2) != LUA_TNUMBER) {
4526 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4527 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4528 name,
4529 lua_typename(L, lua_type(L, -2)));
4530 WILL_LJMP(lua_error(L));
4531 }
4532 id = lua_tointeger(L, -2);
4533
4534 /* We expect a string as -2. */
4535 if (lua_type(L, -1) != LUA_TSTRING) {
4536 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4537 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4538 name, id,
4539 lua_typename(L, lua_type(L, -1)));
4540 WILL_LJMP(lua_error(L));
4541 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004542 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004543
4544 /* Catenate a new header. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004545 if (tmp->data + name_len + 2 + value_len + 2 < tmp->size) {
4546 memcpy(tmp->area + tmp->data, name, name_len);
4547 tmp->data += name_len;
4548 tmp->area[tmp->data++] = ':';
4549 tmp->area[tmp->data++] = ' ';
Willy Tarreaua3294632017-08-23 11:24:47 +02004550
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004551 memcpy(tmp->area + tmp->data, value,
4552 value_len);
4553 tmp->data += value_len;
4554 tmp->area[tmp->data++] = '\r';
4555 tmp->area[tmp->data++] = '\n';
Willy Tarreaua3294632017-08-23 11:24:47 +02004556 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004557
4558 /* Protocol checks. */
4559
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004560 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004561 * is done without control. If it contains a bad value,
4562 * the content-length remains negative so that we can
4563 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004564 */
Willy Tarreaua3294632017-08-23 11:24:47 +02004565 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004566 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004567
4568 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004569 if (name_len == 17 && value_len == 7 &&
4570 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004571 strcasecmp("chunked", value) == 0)
4572 hdr_chunked = 1;
4573
4574 /* Remove the array from the stack, and get next element with a remaining string. */
4575 lua_pop(L, 1);
4576 }
4577
4578 /* Remove the array from the stack, and get next element with a remaining string. */
4579 lua_pop(L, 1);
4580 }
4581
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004582 /* If we dont have a content-length set, and the HTTP version is 1.1
4583 * and the status code implies the presence of a message body, we must
4584 * announce a transfer encoding chunked. This is required by haproxy
4585 * for the keepalive compliance. If the applet annouces a transfer-encoding
4586 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004587 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004588 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004589 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
4590 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4591 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4592 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004593 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4594 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4595 }
4596
4597 /* Finalize headers. */
4598 chunk_appendf(tmp, "\r\n");
4599
4600 /* Remove the last entry and the array of headers */
4601 lua_pop(L, 2);
4602
4603 /* Push the headers block. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004604 lua_pushlstring(L, tmp->area, tmp->data);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004605
4606 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4607}
4608
4609/*
4610 *
4611 *
4612 * Class HTTP
4613 *
4614 *
4615 */
4616
4617/* Returns a struct hlua_txn if the stack entry "ud" is
4618 * a class stream, otherwise it throws an error.
4619 */
4620__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4621{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004622 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004623}
4624
4625/* This function creates and push in the stack a HTTP object
4626 * according with a current TXN.
4627 */
4628static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4629{
4630 struct hlua_txn *htxn;
4631
4632 /* Check stack size. */
4633 if (!lua_checkstack(L, 3))
4634 return 0;
4635
4636 /* Create the object: obj[0] = userdata.
4637 * Note that the base of the Converters object is the
4638 * same than the TXN object.
4639 */
4640 lua_newtable(L);
4641 htxn = lua_newuserdata(L, sizeof(*htxn));
4642 lua_rawseti(L, -2, 0);
4643
4644 htxn->s = txn->s;
4645 htxn->p = txn->p;
4646
4647 /* Pop a class stream metatable and affect it to the table. */
4648 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4649 lua_setmetatable(L, -2);
4650
4651 return 1;
4652}
4653
4654/* This function creates ans returns an array of HTTP headers.
4655 * This function does not fails. It is used as wrapper with the
4656 * 2 following functions.
4657 */
4658__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4659{
4660 const char *cur_ptr, *cur_next, *p;
4661 int old_idx, cur_idx;
4662 struct hdr_idx_elem *cur_hdr;
4663 const char *hn, *hv;
4664 int hnl, hvl;
4665 int type;
4666 const char *in;
4667 char *out;
4668 int len;
4669
4670 /* Create the table. */
4671 lua_newtable(L);
4672
4673 if (!htxn->s->txn)
4674 return 1;
4675
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004676 /* Check if a valid response is parsed */
4677 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4678 return 1;
4679
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004680 /* Build array of headers. */
4681 old_idx = 0;
Willy Tarreaua79021a2018-06-15 18:07:57 +02004682 cur_next = ci_head(msg->chn) + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004683
4684 while (1) {
4685 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4686 if (!cur_idx)
4687 break;
4688 old_idx = cur_idx;
4689
4690 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4691 cur_ptr = cur_next;
4692 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4693
4694 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4695 * and the next header starts at cur_next. We'll check
4696 * this header in the list as well as against the default
4697 * rule.
4698 */
4699
4700 /* look for ': *'. */
4701 hn = cur_ptr;
4702 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4703 if (p >= cur_ptr+cur_hdr->len)
4704 continue;
4705 hnl = p - hn;
4706 p++;
4707 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4708 p++;
4709 if (p >= cur_ptr+cur_hdr->len)
4710 continue;
4711 hv = p;
4712 hvl = cur_ptr+cur_hdr->len-p;
4713
4714 /* Lowercase the key. Don't check the size of trash, it have
4715 * the size of one buffer and the input data contains in one
4716 * buffer.
4717 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004718 out = trash.area;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004719 for (in=hn; in<hn+hnl; in++, out++)
4720 *out = tolower(*in);
4721 *out = '\0';
4722
4723 /* Check for existing entry:
4724 * assume that the table is on the top of the stack, and
4725 * push the key in the stack, the function lua_gettable()
4726 * perform the lookup.
4727 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004728 lua_pushlstring(L, trash.area, hnl);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004729 lua_gettable(L, -2);
4730 type = lua_type(L, -1);
4731
4732 switch (type) {
4733 case LUA_TNIL:
4734 /* Table not found, create it. */
4735 lua_pop(L, 1); /* remove the nil value. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004736 lua_pushlstring(L, trash.area, hnl); /* push the header name as key. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004737 lua_newtable(L); /* create and push empty table. */
4738 lua_pushlstring(L, hv, hvl); /* push header value. */
4739 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4740 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4741 break;
4742
4743 case LUA_TTABLE:
4744 /* Entry found: push the value in the table. */
4745 len = lua_rawlen(L, -1);
4746 lua_pushlstring(L, hv, hvl); /* push header value. */
4747 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4748 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4749 break;
4750
4751 default:
4752 /* Other cases are errors. */
4753 hlua_pusherror(L, "internal error during the parsing of headers.");
4754 WILL_LJMP(lua_error(L));
4755 }
4756 }
4757
4758 return 1;
4759}
4760
4761__LJMP static int hlua_http_req_get_headers(lua_State *L)
4762{
4763 struct hlua_txn *htxn;
4764
4765 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4766 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4767
4768 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4769}
4770
4771__LJMP static int hlua_http_res_get_headers(lua_State *L)
4772{
4773 struct hlua_txn *htxn;
4774
4775 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4776 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4777
4778 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4779}
4780
4781/* This function replace full header, or just a value in
4782 * the request or in the response. It is a wrapper fir the
4783 * 4 following functions.
4784 */
4785__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4786 struct http_msg *msg, int action)
4787{
4788 size_t name_len;
4789 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4790 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4791 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4792 struct my_regex re;
4793
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004794 /* Check if a valid response is parsed */
4795 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4796 return 0;
4797
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004798 if (!regex_comp(reg, &re, 1, 1, NULL))
4799 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4800
4801 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4802 regex_free(&re);
4803 return 0;
4804}
4805
4806__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4807{
4808 struct hlua_txn *htxn;
4809
4810 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4811 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4812
4813 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4814}
4815
4816__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4817{
4818 struct hlua_txn *htxn;
4819
4820 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4821 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4822
4823 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4824}
4825
4826__LJMP static int hlua_http_req_rep_val(lua_State *L)
4827{
4828 struct hlua_txn *htxn;
4829
4830 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4831 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4832
4833 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4834}
4835
4836__LJMP static int hlua_http_res_rep_val(lua_State *L)
4837{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004838 struct hlua_txn *htxn;
4839
4840 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4841 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4842
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004843 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004844}
4845
4846/* This function deletes all the occurences of an header.
4847 * It is a wrapper for the 2 following functions.
4848 */
4849__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4850{
4851 size_t len;
4852 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4853 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004854 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004855
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004856 /* Check if a valid response is parsed */
4857 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4858 return 0;
4859
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004860 ctx.idx = 0;
Willy Tarreaua79021a2018-06-15 18:07:57 +02004861 while (http_find_header2(name, len, ci_head(msg->chn), &txn->hdr_idx, &ctx))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004862 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4863 return 0;
4864}
4865
4866__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4867{
4868 struct hlua_txn *htxn;
4869
4870 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4871 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4872
Willy Tarreaueee5b512015-04-03 23:46:31 +02004873 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004874}
4875
4876__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4877{
4878 struct hlua_txn *htxn;
4879
4880 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4881 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4882
Willy Tarreaueee5b512015-04-03 23:46:31 +02004883 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004884}
4885
4886/* This function adds an header. It is a wrapper used by
4887 * the 2 following functions.
4888 */
4889__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4890{
4891 size_t name_len;
4892 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4893 size_t value_len;
4894 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4895 char *p;
4896
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004897 /* Check if a valid message is parsed */
4898 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4899 return 0;
4900
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004901 /* Check length. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004902 trash.data = value_len + name_len + 2;
4903 if (trash.data > trash.size)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004904 return 0;
4905
4906 /* Creates the header string. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004907 p = trash.area;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004908 memcpy(p, name, name_len);
4909 p += name_len;
4910 *p = ':';
4911 p++;
4912 *p = ' ';
4913 p++;
4914 memcpy(p, value, value_len);
4915
Willy Tarreaueee5b512015-04-03 23:46:31 +02004916 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004917 trash.area, trash.data) != 0);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004918
4919 return 0;
4920}
4921
4922__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4923{
4924 struct hlua_txn *htxn;
4925
4926 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4927 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4928
Willy Tarreaueee5b512015-04-03 23:46:31 +02004929 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004930}
4931
4932__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4933{
4934 struct hlua_txn *htxn;
4935
4936 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4937 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4938
Willy Tarreaueee5b512015-04-03 23:46:31 +02004939 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004940}
4941
4942static int hlua_http_req_set_hdr(lua_State *L)
4943{
4944 struct hlua_txn *htxn;
4945
4946 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4947 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4948
Willy Tarreaueee5b512015-04-03 23:46:31 +02004949 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4950 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004951}
4952
4953static int hlua_http_res_set_hdr(lua_State *L)
4954{
4955 struct hlua_txn *htxn;
4956
4957 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4958 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4959
Willy Tarreaueee5b512015-04-03 23:46:31 +02004960 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4961 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004962}
4963
4964/* This function set the method. */
4965static int hlua_http_req_set_meth(lua_State *L)
4966{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004967 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004968 size_t name_len;
4969 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004970
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004971 /* Check if a valid request is parsed */
4972 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4973 lua_pushboolean(L, 0);
4974 return 1;
4975 }
4976
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004977 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004978 return 1;
4979}
4980
4981/* This function set the method. */
4982static int hlua_http_req_set_path(lua_State *L)
4983{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004984 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004985 size_t name_len;
4986 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004987
4988 /* Check if a valid request is parsed */
4989 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4990 lua_pushboolean(L, 0);
4991 return 1;
4992 }
4993
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004994 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004995 return 1;
4996}
4997
4998/* This function set the query-string. */
4999static int hlua_http_req_set_query(lua_State *L)
5000{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005001 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005002 size_t name_len;
5003 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005004
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005005 /* Check if a valid request is parsed */
5006 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
5007 lua_pushboolean(L, 0);
5008 return 1;
5009 }
5010
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005011 /* Check length. */
5012 if (name_len > trash.size - 1) {
5013 lua_pushboolean(L, 0);
5014 return 1;
5015 }
5016
5017 /* Add the mark question as prefix. */
5018 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005019 trash.area[trash.data++] = '?';
5020 memcpy(trash.area + trash.data, name, name_len);
5021 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005022
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005023 lua_pushboolean(L,
5024 http_replace_req_line(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005025 return 1;
5026}
5027
5028/* This function set the uri. */
5029static int hlua_http_req_set_uri(lua_State *L)
5030{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005031 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005032 size_t name_len;
5033 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005034
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005035 /* Check if a valid request is parsed */
5036 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
5037 lua_pushboolean(L, 0);
5038 return 1;
5039 }
5040
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005041 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005042 return 1;
5043}
5044
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005045/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005046static int hlua_http_res_set_status(lua_State *L)
5047{
5048 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5049 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005050 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005051
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005052 /* Check if a valid response is parsed */
5053 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
5054 return 0;
5055
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005056 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005057 return 0;
5058}
5059
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005060/*
5061 *
5062 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005063 * Class TXN
5064 *
5065 *
5066 */
5067
5068/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005069 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005070 */
5071__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5072{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005073 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005074}
5075
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005076__LJMP static int hlua_set_var(lua_State *L)
5077{
5078 struct hlua_txn *htxn;
5079 const char *name;
5080 size_t len;
5081 struct sample smp;
5082
5083 MAY_LJMP(check_args(L, 3, "set_var"));
5084
5085 /* It is useles to retrieve the stream, but this function
5086 * runs only in a stream context.
5087 */
5088 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5089 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5090
5091 /* Converts the third argument in a sample. */
5092 hlua_lua2smp(L, 3, &smp);
5093
5094 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005095 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005096 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005097 return 0;
5098}
5099
Christopher Faulet85d79c92016-11-09 16:54:56 +01005100__LJMP static int hlua_unset_var(lua_State *L)
5101{
5102 struct hlua_txn *htxn;
5103 const char *name;
5104 size_t len;
5105 struct sample smp;
5106
5107 MAY_LJMP(check_args(L, 2, "unset_var"));
5108
5109 /* It is useles to retrieve the stream, but this function
5110 * runs only in a stream context.
5111 */
5112 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5113 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5114
5115 /* Unset the variable. */
5116 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5117 vars_unset_by_name(name, len, &smp);
5118 return 0;
5119}
5120
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005121__LJMP static int hlua_get_var(lua_State *L)
5122{
5123 struct hlua_txn *htxn;
5124 const char *name;
5125 size_t len;
5126 struct sample smp;
5127
5128 MAY_LJMP(check_args(L, 2, "get_var"));
5129
5130 /* It is useles to retrieve the stream, but this function
5131 * runs only in a stream context.
5132 */
5133 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5134 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5135
Willy Tarreau7560dd42016-03-10 16:28:58 +01005136 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005137 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005138 lua_pushnil(L);
5139 return 1;
5140 }
5141
5142 return hlua_smp2lua(L, &smp);
5143}
5144
Willy Tarreau59551662015-03-10 14:23:13 +01005145__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005146{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005147 struct hlua *hlua;
5148
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005149 MAY_LJMP(check_args(L, 2, "set_priv"));
5150
Willy Tarreau87b09662015-04-03 00:22:06 +02005151 /* It is useles to retrieve the stream, but this function
5152 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005153 */
5154 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005155 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005156
5157 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005158 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005159
5160 /* Get and store new value. */
5161 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5162 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5163
5164 return 0;
5165}
5166
Willy Tarreau59551662015-03-10 14:23:13 +01005167__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005168{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005169 struct hlua *hlua;
5170
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005171 MAY_LJMP(check_args(L, 1, "get_priv"));
5172
Willy Tarreau87b09662015-04-03 00:22:06 +02005173 /* It is useles to retrieve the stream, but this function
5174 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005175 */
5176 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005177 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005178
5179 /* Push configuration index in the stack. */
5180 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5181
5182 return 1;
5183}
5184
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005185/* Create stack entry containing a class TXN. This function
5186 * return 0 if the stack does not contains free slots,
5187 * otherwise it returns 1.
5188 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005189static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005190{
Willy Tarreaude491382015-04-06 11:04:28 +02005191 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005192
5193 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005194 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005195 return 0;
5196
5197 /* NOTE: The allocation never fails. The failure
5198 * throw an error, and the function never returns.
5199 * if the throw is not avalaible, the process is aborted.
5200 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005201 /* Create the object: obj[0] = userdata. */
5202 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005203 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005204 lua_rawseti(L, -2, 0);
5205
Willy Tarreaude491382015-04-06 11:04:28 +02005206 htxn->s = s;
5207 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005208 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005209 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005210
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005211 /* Create the "f" field that contains a list of fetches. */
5212 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005213 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005214 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005215 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005216
5217 /* Create the "sf" field that contains a list of stringsafe fetches. */
5218 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005219 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005220 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005221 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005222
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005223 /* Create the "c" field that contains a list of converters. */
5224 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005225 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005226 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005227 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005228
5229 /* Create the "sc" field that contains a list of stringsafe converters. */
5230 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005231 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005232 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005233 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005234
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005235 /* Create the "req" field that contains the request channel object. */
5236 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005237 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005238 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005239 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005240
5241 /* Create the "res" field that contains the response channel object. */
5242 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005243 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005244 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005245 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005246
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005247 /* Creates the HTTP object is the current proxy allows http. */
5248 lua_pushstring(L, "http");
5249 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005250 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005251 return 0;
5252 }
5253 else
5254 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005255 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005256
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005257 /* Pop a class sesison metatable and affect it to the userdata. */
5258 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5259 lua_setmetatable(L, -2);
5260
5261 return 1;
5262}
5263
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005264__LJMP static int hlua_txn_deflog(lua_State *L)
5265{
5266 const char *msg;
5267 struct hlua_txn *htxn;
5268
5269 MAY_LJMP(check_args(L, 2, "deflog"));
5270 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5271 msg = MAY_LJMP(luaL_checkstring(L, 2));
5272
5273 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5274 return 0;
5275}
5276
5277__LJMP static int hlua_txn_log(lua_State *L)
5278{
5279 int level;
5280 const char *msg;
5281 struct hlua_txn *htxn;
5282
5283 MAY_LJMP(check_args(L, 3, "log"));
5284 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5285 level = MAY_LJMP(luaL_checkinteger(L, 2));
5286 msg = MAY_LJMP(luaL_checkstring(L, 3));
5287
5288 if (level < 0 || level >= NB_LOG_LEVELS)
5289 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5290
5291 hlua_sendlog(htxn->s->be, level, msg);
5292 return 0;
5293}
5294
5295__LJMP static int hlua_txn_log_debug(lua_State *L)
5296{
5297 const char *msg;
5298 struct hlua_txn *htxn;
5299
5300 MAY_LJMP(check_args(L, 2, "Debug"));
5301 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5302 msg = MAY_LJMP(luaL_checkstring(L, 2));
5303 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5304 return 0;
5305}
5306
5307__LJMP static int hlua_txn_log_info(lua_State *L)
5308{
5309 const char *msg;
5310 struct hlua_txn *htxn;
5311
5312 MAY_LJMP(check_args(L, 2, "Info"));
5313 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5314 msg = MAY_LJMP(luaL_checkstring(L, 2));
5315 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5316 return 0;
5317}
5318
5319__LJMP static int hlua_txn_log_warning(lua_State *L)
5320{
5321 const char *msg;
5322 struct hlua_txn *htxn;
5323
5324 MAY_LJMP(check_args(L, 2, "Warning"));
5325 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5326 msg = MAY_LJMP(luaL_checkstring(L, 2));
5327 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5328 return 0;
5329}
5330
5331__LJMP static int hlua_txn_log_alert(lua_State *L)
5332{
5333 const char *msg;
5334 struct hlua_txn *htxn;
5335
5336 MAY_LJMP(check_args(L, 2, "Alert"));
5337 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5338 msg = MAY_LJMP(luaL_checkstring(L, 2));
5339 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5340 return 0;
5341}
5342
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005343__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5344{
5345 struct hlua_txn *htxn;
5346 int ll;
5347
5348 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5349 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5350 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5351
5352 if (ll < 0 || ll > 7)
5353 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5354
5355 htxn->s->logs.level = ll;
5356 return 0;
5357}
5358
5359__LJMP static int hlua_txn_set_tos(lua_State *L)
5360{
5361 struct hlua_txn *htxn;
5362 struct connection *cli_conn;
5363 int tos;
5364
5365 MAY_LJMP(check_args(L, 2, "set_tos"));
5366 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5367 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5368
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005369 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005370 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005371
5372 return 0;
5373}
5374
5375__LJMP static int hlua_txn_set_mark(lua_State *L)
5376{
5377#ifdef SO_MARK
5378 struct hlua_txn *htxn;
5379 struct connection *cli_conn;
5380 int mark;
5381
5382 MAY_LJMP(check_args(L, 2, "set_mark"));
5383 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5384 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5385
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005386 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005387 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005388#endif
5389 return 0;
5390}
5391
Patrick Hemmer268a7072018-05-11 12:52:31 -04005392__LJMP static int hlua_txn_set_priority_class(lua_State *L)
5393{
5394 struct hlua_txn *htxn;
5395
5396 MAY_LJMP(check_args(L, 2, "set_priority_class"));
5397 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5398 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
5399 return 0;
5400}
5401
5402__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
5403{
5404 struct hlua_txn *htxn;
5405
5406 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
5407 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5408 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
5409 return 0;
5410}
5411
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005412/* This function is an Lua binding that send pending data
5413 * to the client, and close the stream interface.
5414 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005415__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005416{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005417 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005418 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005419 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005420
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005421 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005422 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005423 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005424
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005425 /* If the flags NOTERM is set, we cannot terminate the http
5426 * session, so we just end the execution of the current
5427 * lua code.
5428 */
5429 if (htxn->flags & HLUA_TXN_NOTERM) {
5430 WILL_LJMP(hlua_done(L));
5431 return 0;
5432 }
5433
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005434 ic = &htxn->s->req;
5435 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005436
Willy Tarreau630ef452015-08-28 10:06:15 +02005437 if (htxn->s->txn) {
5438 /* HTTP mode, let's stay in sync with the stream */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02005439 b_del(&ic->buf, htxn->s->txn->req.sov);
Willy Tarreau630ef452015-08-28 10:06:15 +02005440 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5441 htxn->s->txn->req.sov = 0;
5442 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5443 oc->analysers = AN_RES_HTTP_XFER_BODY;
5444 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5445 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5446
Willy Tarreau630ef452015-08-28 10:06:15 +02005447 /* Note that if we want to support keep-alive, we need
5448 * to bypass the close/shutr_now calls below, but that
5449 * may only be done if the HTTP request was already
5450 * processed and the connection header is known (ie
5451 * not during TCP rules).
5452 */
5453 }
5454
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005455 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005456 channel_abort(ic);
5457 channel_auto_close(ic);
5458 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005459
5460 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005461 channel_auto_read(oc);
5462 channel_auto_close(oc);
5463 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005464
Willy Tarreau0458b082015-08-28 09:40:04 +02005465 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005466
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005467 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005468 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005469 return 0;
5470}
5471
5472__LJMP static int hlua_log(lua_State *L)
5473{
5474 int level;
5475 const char *msg;
5476
5477 MAY_LJMP(check_args(L, 2, "log"));
5478 level = MAY_LJMP(luaL_checkinteger(L, 1));
5479 msg = MAY_LJMP(luaL_checkstring(L, 2));
5480
5481 if (level < 0 || level >= NB_LOG_LEVELS)
5482 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5483
5484 hlua_sendlog(NULL, level, msg);
5485 return 0;
5486}
5487
5488__LJMP static int hlua_log_debug(lua_State *L)
5489{
5490 const char *msg;
5491
5492 MAY_LJMP(check_args(L, 1, "debug"));
5493 msg = MAY_LJMP(luaL_checkstring(L, 1));
5494 hlua_sendlog(NULL, LOG_DEBUG, msg);
5495 return 0;
5496}
5497
5498__LJMP static int hlua_log_info(lua_State *L)
5499{
5500 const char *msg;
5501
5502 MAY_LJMP(check_args(L, 1, "info"));
5503 msg = MAY_LJMP(luaL_checkstring(L, 1));
5504 hlua_sendlog(NULL, LOG_INFO, msg);
5505 return 0;
5506}
5507
5508__LJMP static int hlua_log_warning(lua_State *L)
5509{
5510 const char *msg;
5511
5512 MAY_LJMP(check_args(L, 1, "warning"));
5513 msg = MAY_LJMP(luaL_checkstring(L, 1));
5514 hlua_sendlog(NULL, LOG_WARNING, msg);
5515 return 0;
5516}
5517
5518__LJMP static int hlua_log_alert(lua_State *L)
5519{
5520 const char *msg;
5521
5522 MAY_LJMP(check_args(L, 1, "alert"));
5523 msg = MAY_LJMP(luaL_checkstring(L, 1));
5524 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005525 return 0;
5526}
5527
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005528__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005529{
5530 int wakeup_ms = lua_tointeger(L, -1);
5531 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005532 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005533 return 0;
5534}
5535
5536__LJMP static int hlua_sleep(lua_State *L)
5537{
5538 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005539 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005540
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005541 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005542
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005543 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005544 wakeup_ms = tick_add(now_ms, delay);
5545 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005546
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005547 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5548 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005549}
5550
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005551__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005552{
5553 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005554 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005555
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005556 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005557
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005558 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005559 wakeup_ms = tick_add(now_ms, delay);
5560 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005561
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005562 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5563 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005564}
5565
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005566/* This functionis an LUA binding. it permits to give back
5567 * the hand at the HAProxy scheduler. It is used when the
5568 * LUA processing consumes a lot of time.
5569 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005570__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005571{
5572 return 0;
5573}
5574
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005575__LJMP static int hlua_yield(lua_State *L)
5576{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005577 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5578 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005579}
5580
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005581/* This function change the nice of the currently executed
5582 * task. It is used set low or high priority at the current
5583 * task.
5584 */
Willy Tarreau59551662015-03-10 14:23:13 +01005585__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005586{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005587 struct hlua *hlua;
5588 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005589
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005590 MAY_LJMP(check_args(L, 1, "set_nice"));
5591 hlua = hlua_gethlua(L);
5592 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005593
5594 /* If he task is not set, I'm in a start mode. */
5595 if (!hlua || !hlua->task)
5596 return 0;
5597
5598 if (nice < -1024)
5599 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005600 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005601 nice = 1024;
5602
5603 hlua->task->nice = nice;
5604 return 0;
5605}
5606
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005607/* This function is used as a calback of a task. It is called by the
5608 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5609 * return an E_AGAIN signal, the emmiter of this signal must set a
5610 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005611 *
5612 * Task wrapper are longjmp safe because the only one Lua code
5613 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005614 */
Olivier Houchard9f6af332018-05-25 14:04:04 +02005615static struct task *hlua_process_task(struct task *task, void *context, unsigned short state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005616{
Olivier Houchard9f6af332018-05-25 14:04:04 +02005617 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005618 enum hlua_exec status;
5619
Christopher Faulet5bc99722018-04-25 10:34:45 +02005620 if (task->thread_mask == MAX_THREADS_MASK)
5621 task_set_affinity(task, tid_bit);
5622
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005623 /* If it is the first call to the task, we must initialize the
5624 * execution timeouts.
5625 */
5626 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005627 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005628
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005629 /* Execute the Lua code. */
5630 status = hlua_ctx_resume(hlua, 1);
5631
5632 switch (status) {
5633 /* finished or yield */
5634 case HLUA_E_OK:
5635 hlua_ctx_destroy(hlua);
5636 task_delete(task);
5637 task_free(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02005638 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005639 break;
5640
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005641 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01005642 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02005643 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005644 break;
5645
5646 /* finished with error. */
5647 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005648 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005649 hlua_ctx_destroy(hlua);
5650 task_delete(task);
5651 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005652 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005653 break;
5654
5655 case HLUA_E_ERR:
5656 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005657 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005658 hlua_ctx_destroy(hlua);
5659 task_delete(task);
5660 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005661 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005662 break;
5663 }
Emeric Brun253e53e2017-10-17 18:58:40 +02005664 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005665}
5666
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005667/* This function is an LUA binding that register LUA function to be
5668 * executed after the HAProxy configuration parsing and before the
5669 * HAProxy scheduler starts. This function expect only one LUA
5670 * argument that is a function. This function returns nothing, but
5671 * throws if an error is encountered.
5672 */
5673__LJMP static int hlua_register_init(lua_State *L)
5674{
5675 struct hlua_init_function *init;
5676 int ref;
5677
5678 MAY_LJMP(check_args(L, 1, "register_init"));
5679
5680 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5681
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005682 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005683 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005684 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005685
5686 init->function_ref = ref;
5687 LIST_ADDQ(&hlua_init_functions, &init->l);
5688 return 0;
5689}
5690
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005691/* This functio is an LUA binding. It permits to register a task
5692 * executed in parallel of the main HAroxy activity. The task is
5693 * created and it is set in the HAProxy scheduler. It can be called
5694 * from the "init" section, "post init" or during the runtime.
5695 *
5696 * Lua prototype:
5697 *
5698 * <none> core.register_task(<function>)
5699 */
5700static int hlua_register_task(lua_State *L)
5701{
5702 struct hlua *hlua;
5703 struct task *task;
5704 int ref;
5705
5706 MAY_LJMP(check_args(L, 1, "register_task"));
5707
5708 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5709
Willy Tarreaubafbe012017-11-24 17:34:44 +01005710 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005711 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005712 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005713
Emeric Brunc60def82017-09-27 14:59:38 +02005714 task = task_new(MAX_THREADS_MASK);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005715 task->context = hlua;
5716 task->process = hlua_process_task;
5717
5718 if (!hlua_ctx_init(hlua, task))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005719 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005720
5721 /* Restore the function in the stack. */
5722 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5723 hlua->nargs = 0;
5724
5725 /* Schedule task. */
5726 task_schedule(task, now_ms);
5727
5728 return 0;
5729}
5730
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005731/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5732 * doesn't allow "yield" functions because the HAProxy engine cannot
5733 * resume converters.
5734 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005735static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005736{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005737 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005738 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005739 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005740
Willy Tarreaube508f12016-03-10 11:47:01 +01005741 if (!stream)
5742 return 0;
5743
Willy Tarreau87b09662015-04-03 00:22:06 +02005744 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005745 * Lua context can be not initialized. This behavior
5746 * permits to save performances because a systematic
5747 * Lua initialization cause 5% performances loss.
5748 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005749 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005750 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005751 if (!stream->hlua) {
5752 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5753 return 0;
5754 }
5755 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5756 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5757 return 0;
5758 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005759 }
5760
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005761 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005762 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005763
5764 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005765 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5766 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5767 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005768 else
5769 error = "critical error";
5770 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005771 return 0;
5772 }
5773
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005774 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005775 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005776 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005777 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005778 return 0;
5779 }
5780
5781 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005782 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005783
5784 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005785 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005786 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005787 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005788 return 0;
5789 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005790 hlua_smp2lua(stream->hlua->T, smp);
5791 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005792
5793 /* push keywords in the stack. */
5794 if (arg_p) {
5795 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005796 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005797 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005798 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005799 return 0;
5800 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005801 hlua_arg2lua(stream->hlua->T, arg_p);
5802 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005803 }
5804 }
5805
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005806 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005807 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005808
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005809 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005810 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005811 }
5812
5813 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005814 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005815 /* finished. */
5816 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005817 /* If the stack is empty, the function fails. */
5818 if (lua_gettop(stream->hlua->T) <= 0)
5819 return 0;
5820
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005821 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005822 hlua_lua2smp(stream->hlua->T, -1, smp);
5823 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005824 return 1;
5825
5826 /* yield. */
5827 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005828 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005829 return 0;
5830
5831 /* finished with error. */
5832 case HLUA_E_ERRMSG:
5833 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005834 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005835 fcn->name, lua_tostring(stream->hlua->T, -1));
5836 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005837 return 0;
5838
Thierry Fournierd5b073c2018-05-21 19:42:47 +02005839 case HLUA_E_ETMOUT:
5840 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
5841 return 0;
5842
5843 case HLUA_E_NOMEM:
5844 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
5845 return 0;
5846
5847 case HLUA_E_YIELD:
5848 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
5849 return 0;
5850
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005851 case HLUA_E_ERR:
5852 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005853 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005854
5855 default:
5856 return 0;
5857 }
5858}
5859
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005860/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5861 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005862 * resume sample-fetches. This function will be called by the sample
5863 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005864 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005865static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5866 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005867{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005868 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005869 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005870 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02005871 const struct buffer msg = { };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005872
Willy Tarreaube508f12016-03-10 11:47:01 +01005873 if (!stream)
5874 return 0;
5875
Willy Tarreau87b09662015-04-03 00:22:06 +02005876 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005877 * Lua context can be not initialized. This behavior
5878 * permits to save performances because a systematic
5879 * Lua initialization cause 5% performances loss.
5880 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005881 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005882 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005883 if (!stream->hlua) {
5884 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5885 return 0;
5886 }
5887 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5888 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5889 return 0;
5890 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005891 }
5892
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005893 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005894
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005895 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005896 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005897
5898 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005899 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5900 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5901 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005902 else
5903 error = "critical error";
5904 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005905 return 0;
5906 }
5907
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005908 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005909 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005910 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005911 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005912 return 0;
5913 }
5914
5915 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005916 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005917
5918 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005919 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005920 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005921 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005922 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005923 return 0;
5924 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005925 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005926
5927 /* push keywords in the stack. */
5928 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5929 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005930 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005931 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005932 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005933 return 0;
5934 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005935 hlua_arg2lua(stream->hlua->T, arg_p);
5936 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005937 }
5938
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005939 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005940 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005941
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005942 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005943 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005944 }
5945
5946 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005947 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005948 /* finished. */
5949 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005950 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005951 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005952 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005953 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005954 /* If the stack is empty, the function fails. */
5955 if (lua_gettop(stream->hlua->T) <= 0)
5956 return 0;
5957
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005958 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005959 hlua_lua2smp(stream->hlua->T, -1, smp);
5960 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005961
5962 /* Set the end of execution flag. */
5963 smp->flags &= ~SMP_F_MAY_CHANGE;
5964 return 1;
5965
5966 /* yield. */
5967 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005968 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005969 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005970 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005971 return 0;
5972
5973 /* finished with error. */
5974 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005975 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005976 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005977 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005978 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005979 fcn->name, lua_tostring(stream->hlua->T, -1));
5980 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005981 return 0;
5982
Thierry Fournierd5b073c2018-05-21 19:42:47 +02005983 case HLUA_E_ETMOUT:
5984 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
5985 stream_int_retnclose(&stream->si[0], &msg);
5986 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
5987 return 0;
5988
5989 case HLUA_E_NOMEM:
5990 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
5991 stream_int_retnclose(&stream->si[0], &msg);
5992 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
5993 return 0;
5994
5995 case HLUA_E_YIELD:
5996 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
5997 stream_int_retnclose(&stream->si[0], &msg);
5998 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
5999 return 0;
6000
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006001 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006002 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006003 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006004 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006005 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006006
6007 default:
6008 return 0;
6009 }
6010}
6011
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006012/* This function is an LUA binding used for registering
6013 * "sample-conv" functions. It expects a converter name used
6014 * in the haproxy configuration file, and an LUA function.
6015 */
6016__LJMP static int hlua_register_converters(lua_State *L)
6017{
6018 struct sample_conv_kw_list *sck;
6019 const char *name;
6020 int ref;
6021 int len;
6022 struct hlua_function *fcn;
6023
6024 MAY_LJMP(check_args(L, 2, "register_converters"));
6025
6026 /* First argument : converter name. */
6027 name = MAY_LJMP(luaL_checkstring(L, 1));
6028
6029 /* Second argument : lua function. */
6030 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6031
6032 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006033 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006034 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006035 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006036 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006037 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006038 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006039
6040 /* Fill fcn. */
6041 fcn->name = strdup(name);
6042 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006043 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006044 fcn->function_ref = ref;
6045
6046 /* List head */
6047 sck->list.n = sck->list.p = NULL;
6048
6049 /* converter keyword. */
6050 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006051 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006052 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006053 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006054
6055 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6056 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006057 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 +01006058 sck->kw[0].val_args = NULL;
6059 sck->kw[0].in_type = SMP_T_STR;
6060 sck->kw[0].out_type = SMP_T_STR;
6061 sck->kw[0].private = fcn;
6062
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006063 /* Register this new converter */
6064 sample_register_convs(sck);
6065
6066 return 0;
6067}
6068
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006069/* This fucntion is an LUA binding used for registering
6070 * "sample-fetch" functions. It expects a converter name used
6071 * in the haproxy configuration file, and an LUA function.
6072 */
6073__LJMP static int hlua_register_fetches(lua_State *L)
6074{
6075 const char *name;
6076 int ref;
6077 int len;
6078 struct sample_fetch_kw_list *sfk;
6079 struct hlua_function *fcn;
6080
6081 MAY_LJMP(check_args(L, 2, "register_fetches"));
6082
6083 /* First argument : sample-fetch name. */
6084 name = MAY_LJMP(luaL_checkstring(L, 1));
6085
6086 /* Second argument : lua function. */
6087 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6088
6089 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006090 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006091 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006092 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006093 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006094 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006095 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006096
6097 /* Fill fcn. */
6098 fcn->name = strdup(name);
6099 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006100 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006101 fcn->function_ref = ref;
6102
6103 /* List head */
6104 sfk->list.n = sfk->list.p = NULL;
6105
6106 /* sample-fetch keyword. */
6107 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006108 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006109 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006110 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006111
6112 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6113 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006114 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 +01006115 sfk->kw[0].val_args = NULL;
6116 sfk->kw[0].out_type = SMP_T_STR;
6117 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6118 sfk->kw[0].val = 0;
6119 sfk->kw[0].private = fcn;
6120
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006121 /* Register this new fetch. */
6122 sample_register_fetches(sfk);
6123
6124 return 0;
6125}
6126
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006127/* This function is a wrapper to execute each LUA function declared
6128 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006129 * return ACT_RET_CONT if the processing is finished (with or without
6130 * error) and return ACT_RET_YIELD if the function must be called again
6131 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006132 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006133static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006134 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006135{
6136 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006137 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006138 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006139 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006140 const struct buffer msg = { };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006141
6142 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01006143 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
6144 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
6145 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
6146 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006147 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006148 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006149 return ACT_RET_CONT;
6150 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006151
Willy Tarreau87b09662015-04-03 00:22:06 +02006152 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006153 * Lua context can be not initialized. This behavior
6154 * permits to save performances because a systematic
6155 * Lua initialization cause 5% performances loss.
6156 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006157 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006158 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006159 if (!s->hlua) {
6160 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6161 rule->arg.hlua_rule->fcn.name);
6162 return ACT_RET_CONT;
6163 }
6164 if (!hlua_ctx_init(s->hlua, s->task)) {
6165 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6166 rule->arg.hlua_rule->fcn.name);
6167 return ACT_RET_CONT;
6168 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006169 }
6170
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006171 consistency_set(s, dir, &s->hlua->cons);
6172
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006173 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006174 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006175
6176 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006177 if (!SET_SAFE_LJMP(s->hlua->T)) {
6178 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6179 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006180 else
6181 error = "critical error";
6182 SEND_ERR(px, "Lua function '%s': %s.\n",
6183 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006184 return ACT_RET_CONT;
6185 }
6186
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006187 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006188 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006189 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006190 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006191 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006192 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006193 }
6194
6195 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006196 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006197
Willy Tarreau87b09662015-04-03 00:22:06 +02006198 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006199 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006200 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006201 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006202 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006203 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006204 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006205 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006206
6207 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006208 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006209 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006210 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006211 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006212 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006213 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006214 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006215 lua_pushstring(s->hlua->T, *arg);
6216 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006217 }
6218
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006219 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006220 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006221
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006222 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006223 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006224 }
6225
6226 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006227 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006228 /* finished. */
6229 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006230 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006231 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006232 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006233 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006234 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006235 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006236 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006237
6238 /* yield. */
6239 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006240 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006241 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006242 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006243 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006244 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006245 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006246 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006247 /* Some actions can be wake up when a "write" event
6248 * is detected on a response channel. This is useful
6249 * only for actions targetted on the requests.
6250 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006251 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006252 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01006253 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006254 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006255 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006256 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006257 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006258 /* We can quit the fcuntion without consistency check
6259 * because HAProxy is not able to manipulate data, it
6260 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006261 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006262
6263 /* finished with error. */
6264 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006265 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006266 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006267 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006268 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006269 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006270 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006271 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6272 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006273 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006274
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006275 case HLUA_E_ETMOUT:
6276 if (!consistency_check(s, dir, &s->hlua->cons)) {
6277 stream_int_retnclose(&s->si[0], &msg);
6278 return ACT_RET_ERR;
6279 }
6280 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
6281 return 0;
6282
6283 case HLUA_E_NOMEM:
6284 if (!consistency_check(s, dir, &s->hlua->cons)) {
6285 stream_int_retnclose(&s->si[0], &msg);
6286 return ACT_RET_ERR;
6287 }
6288 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
6289 return 0;
6290
6291 case HLUA_E_YIELD:
6292 if (!consistency_check(s, dir, &s->hlua->cons)) {
6293 stream_int_retnclose(&s->si[0], &msg);
6294 return ACT_RET_ERR;
6295 }
6296 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6297 rule->arg.hlua_rule->fcn.name);
6298 return 0;
6299
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006300 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006301 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006302 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006303 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006304 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006305 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006306 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006307 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006308
6309 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006310 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006311 }
6312}
6313
Olivier Houchard9f6af332018-05-25 14:04:04 +02006314struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006315{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006316 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006317 struct stream_interface *si = ctx->owner;
6318
6319 /* If the applet is wake up without any expected work, the sheduler
6320 * remove it from the run queue. This flag indicate that the applet
6321 * is waiting for write. If the buffer is full, the main processing
6322 * will send some data and after call the applet, otherwise it call
6323 * the applet ASAP.
6324 */
6325 si_applet_cant_put(si);
6326 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006327 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006328 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006329}
6330
6331static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6332{
6333 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006334 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006335 struct task *task;
6336 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006337 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006338
Willy Tarreaubafbe012017-11-24 17:34:44 +01006339 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006340 if (!hlua) {
6341 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6342 ctx->rule->arg.hlua_rule->fcn.name);
6343 return 0;
6344 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006345 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006346 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006347 ctx->ctx.hlua_apptcp.flags = 0;
6348
6349 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006350 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006351 if (!task) {
6352 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6353 ctx->rule->arg.hlua_rule->fcn.name);
6354 return 0;
6355 }
6356 task->nice = 0;
6357 task->context = ctx;
6358 task->process = hlua_applet_wakeup;
6359 ctx->ctx.hlua_apptcp.task = task;
6360
6361 /* In the execution wrappers linked with a stream, the
6362 * Lua context can be not initialized. This behavior
6363 * permits to save performances because a systematic
6364 * Lua initialization cause 5% performances loss.
6365 */
6366 if (!hlua_ctx_init(hlua, task)) {
6367 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6368 ctx->rule->arg.hlua_rule->fcn.name);
6369 return 0;
6370 }
6371
6372 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006373 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006374
6375 /* The following Lua calls can fail. */
6376 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006377 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6378 error = lua_tostring(hlua->T, -1);
6379 else
6380 error = "critical error";
6381 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6382 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006383 RESET_SAFE_LJMP(hlua->T);
6384 return 0;
6385 }
6386
6387 /* Check stack available size. */
6388 if (!lua_checkstack(hlua->T, 1)) {
6389 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6390 ctx->rule->arg.hlua_rule->fcn.name);
6391 RESET_SAFE_LJMP(hlua->T);
6392 return 0;
6393 }
6394
6395 /* Restore the function in the stack. */
6396 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6397
6398 /* Create and and push object stream in the stack. */
6399 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6400 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6401 ctx->rule->arg.hlua_rule->fcn.name);
6402 RESET_SAFE_LJMP(hlua->T);
6403 return 0;
6404 }
6405 hlua->nargs = 1;
6406
6407 /* push keywords in the stack. */
6408 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6409 if (!lua_checkstack(hlua->T, 1)) {
6410 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6411 ctx->rule->arg.hlua_rule->fcn.name);
6412 RESET_SAFE_LJMP(hlua->T);
6413 return 0;
6414 }
6415 lua_pushstring(hlua->T, *arg);
6416 hlua->nargs++;
6417 }
6418
6419 RESET_SAFE_LJMP(hlua->T);
6420
6421 /* Wakeup the applet ASAP. */
6422 si_applet_cant_get(si);
6423 si_applet_cant_put(si);
6424
6425 return 1;
6426}
6427
6428static void hlua_applet_tcp_fct(struct appctx *ctx)
6429{
6430 struct stream_interface *si = ctx->owner;
6431 struct stream *strm = si_strm(si);
6432 struct channel *res = si_ic(si);
6433 struct act_rule *rule = ctx->rule;
6434 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006435 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006436
6437 /* The applet execution is already done. */
6438 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
6439 return;
6440
6441 /* If the stream is disconnect or closed, ldo nothing. */
6442 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6443 return;
6444
6445 /* Execute the function. */
6446 switch (hlua_ctx_resume(hlua, 1)) {
6447 /* finished. */
6448 case HLUA_E_OK:
6449 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6450
6451 /* log time */
6452 strm->logs.tv_request = now;
6453
6454 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02006455 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006456 res->flags |= CF_READ_NULL;
6457 si_shutr(si);
6458 return;
6459
6460 /* yield. */
6461 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006462 if (hlua->wake_time != TICK_ETERNITY)
6463 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006464 return;
6465
6466 /* finished with error. */
6467 case HLUA_E_ERRMSG:
6468 /* Display log. */
6469 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6470 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6471 lua_pop(hlua->T, 1);
6472 goto error;
6473
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006474 case HLUA_E_ETMOUT:
6475 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
6476 rule->arg.hlua_rule->fcn.name);
6477 goto error;
6478
6479 case HLUA_E_NOMEM:
6480 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
6481 rule->arg.hlua_rule->fcn.name);
6482 goto error;
6483
6484 case HLUA_E_YIELD: /* unexpected */
6485 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
6486 rule->arg.hlua_rule->fcn.name);
6487 goto error;
6488
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006489 case HLUA_E_ERR:
6490 /* Display log. */
6491 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6492 rule->arg.hlua_rule->fcn.name);
6493 goto error;
6494
6495 default:
6496 goto error;
6497 }
6498
6499error:
6500
6501 /* For all other cases, just close the stream. */
6502 si_shutw(si);
6503 si_shutr(si);
6504 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6505}
6506
6507static void hlua_applet_tcp_release(struct appctx *ctx)
6508{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006509 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006510 task_free(ctx->ctx.hlua_apptcp.task);
6511 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006512 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006513 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006514}
6515
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006516/* The function returns 1 if the initialisation is complete, 0 if
6517 * an errors occurs and -1 if more data are required for initializing
6518 * the applet.
6519 */
6520static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6521{
6522 struct stream_interface *si = ctx->owner;
6523 struct channel *req = si_oc(si);
6524 struct http_msg *msg;
6525 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006526 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006527 char **arg;
6528 struct hdr_ctx hdr;
6529 struct task *task;
6530 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006531 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006532
6533 /* Wait for a full HTTP request. */
6534 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6535 if (smp.flags & SMP_F_MAY_CHANGE)
6536 return -1;
6537 return 0;
6538 }
6539 txn = strm->txn;
6540 msg = &txn->req;
6541
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006542 /* We want two things in HTTP mode :
6543 * - enforce server-close mode if we were in keep-alive, so that the
6544 * applet is released after each response ;
6545 * - enable request body transfer to the applet in order to resync
6546 * with the response body.
6547 */
6548 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6549 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006550
Willy Tarreaubafbe012017-11-24 17:34:44 +01006551 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006552 if (!hlua) {
6553 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6554 ctx->rule->arg.hlua_rule->fcn.name);
6555 return 0;
6556 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006557 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006558 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006559 ctx->ctx.hlua_apphttp.left_bytes = -1;
6560 ctx->ctx.hlua_apphttp.flags = 0;
6561
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006562 if (txn->req.flags & HTTP_MSGF_VER_11)
6563 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6564
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006565 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006566 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006567 if (!task) {
6568 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6569 ctx->rule->arg.hlua_rule->fcn.name);
6570 return 0;
6571 }
6572 task->nice = 0;
6573 task->context = ctx;
6574 task->process = hlua_applet_wakeup;
6575 ctx->ctx.hlua_apphttp.task = task;
6576
6577 /* In the execution wrappers linked with a stream, the
6578 * Lua context can be not initialized. This behavior
6579 * permits to save performances because a systematic
6580 * Lua initialization cause 5% performances loss.
6581 */
6582 if (!hlua_ctx_init(hlua, task)) {
6583 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6584 ctx->rule->arg.hlua_rule->fcn.name);
6585 return 0;
6586 }
6587
6588 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006589 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006590
6591 /* The following Lua calls can fail. */
6592 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006593 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6594 error = lua_tostring(hlua->T, -1);
6595 else
6596 error = "critical error";
6597 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6598 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006599 return 0;
6600 }
6601
6602 /* Check stack available size. */
6603 if (!lua_checkstack(hlua->T, 1)) {
6604 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6605 ctx->rule->arg.hlua_rule->fcn.name);
6606 RESET_SAFE_LJMP(hlua->T);
6607 return 0;
6608 }
6609
6610 /* Restore the function in the stack. */
6611 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6612
6613 /* Create and and push object stream in the stack. */
6614 if (!hlua_applet_http_new(hlua->T, ctx)) {
6615 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6616 ctx->rule->arg.hlua_rule->fcn.name);
6617 RESET_SAFE_LJMP(hlua->T);
6618 return 0;
6619 }
6620 hlua->nargs = 1;
6621
6622 /* Look for a 100-continue expected. */
6623 if (msg->flags & HTTP_MSGF_VER_11) {
6624 hdr.idx = 0;
Willy Tarreaua79021a2018-06-15 18:07:57 +02006625 if (http_find_header2("Expect", 6, ci_head(req), &txn->hdr_idx, &hdr) &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006626 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6627 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6628 }
6629
6630 /* push keywords in the stack. */
6631 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6632 if (!lua_checkstack(hlua->T, 1)) {
6633 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6634 ctx->rule->arg.hlua_rule->fcn.name);
6635 RESET_SAFE_LJMP(hlua->T);
6636 return 0;
6637 }
6638 lua_pushstring(hlua->T, *arg);
6639 hlua->nargs++;
6640 }
6641
6642 RESET_SAFE_LJMP(hlua->T);
6643
6644 /* Wakeup the applet when data is ready for read. */
6645 si_applet_cant_get(si);
6646
6647 return 1;
6648}
6649
6650static void hlua_applet_http_fct(struct appctx *ctx)
6651{
6652 struct stream_interface *si = ctx->owner;
6653 struct stream *strm = si_strm(si);
6654 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006655 struct act_rule *rule = ctx->rule;
6656 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006657 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Willy Tarreau206ba832018-06-14 15:27:31 +02006658 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02006659 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02006660 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02006661 size_t len2;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006662 int ret;
6663
6664 /* If the stream is disconnect or closed, ldo nothing. */
6665 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6666 return;
6667
6668 /* Set the currently running flag. */
6669 if (!HLUA_IS_RUNNING(hlua) &&
6670 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6671
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006672 /* Wait for full HTTP analysys. */
6673 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6674 si_applet_cant_get(si);
6675 return;
6676 }
6677
6678 /* Store the max amount of bytes that we can read. */
6679 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6680
6681 /* We need to flush the request header. This left the body
6682 * for the Lua.
6683 */
6684
6685 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006686 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006687 if (ret == -1)
6688 return;
6689
6690 /* No data available, ask for more data. */
6691 if (ret == 1)
6692 len2 = 0;
6693 if (ret == 0)
6694 len1 = 0;
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02006695 if (len1 + len2 < strm->txn->req.eoh + strm->txn->req.eol) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006696 si_applet_cant_get(si);
6697 return;
6698 }
6699
6700 /* skip the requests bytes. */
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02006701 co_skip(si_oc(si), strm->txn->req.eoh + strm->txn->req.eol);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006702 }
6703
6704 /* Executes The applet if it is not done. */
6705 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6706
6707 /* Execute the function. */
6708 switch (hlua_ctx_resume(hlua, 1)) {
6709 /* finished. */
6710 case HLUA_E_OK:
6711 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6712 break;
6713
6714 /* yield. */
6715 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006716 if (hlua->wake_time != TICK_ETERNITY)
6717 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006718 return;
6719
6720 /* finished with error. */
6721 case HLUA_E_ERRMSG:
6722 /* Display log. */
6723 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6724 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6725 lua_pop(hlua->T, 1);
6726 goto error;
6727
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006728 case HLUA_E_ETMOUT:
6729 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
6730 rule->arg.hlua_rule->fcn.name);
6731 goto error;
6732
6733 case HLUA_E_NOMEM:
6734 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
6735 rule->arg.hlua_rule->fcn.name);
6736 goto error;
6737
6738 case HLUA_E_YIELD: /* unexpected */
6739 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
6740 rule->arg.hlua_rule->fcn.name);
6741 goto error;
6742
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006743 case HLUA_E_ERR:
6744 /* Display log. */
6745 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6746 rule->arg.hlua_rule->fcn.name);
6747 goto error;
6748
6749 default:
6750 goto error;
6751 }
6752 }
6753
6754 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6755
6756 /* We must send the final chunk. */
6757 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6758 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6759
6760 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006761 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006762
6763 /* critical error. */
6764 if (ret == -2 || ret == -3) {
6765 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6766 rule->arg.hlua_rule->fcn.name);
6767 goto error;
6768 }
6769
6770 /* no enough space error. */
6771 if (ret == -1) {
6772 si_applet_cant_put(si);
6773 return;
6774 }
6775
6776 /* set the last chunk sent. */
6777 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6778 }
6779
6780 /* close the connection. */
6781
6782 /* status / log */
6783 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6784 strm->logs.tv_request = now;
6785
6786 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02006787 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006788 res->flags |= CF_READ_NULL;
6789 si_shutr(si);
6790
6791 return;
6792 }
6793
6794error:
6795
6796 /* If we are in HTTP mode, and we are not send any
6797 * data, return a 500 server error in best effort:
6798 * if there are no room avalaible in the buffer,
6799 * just close the connection.
6800 */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006801 ci_putblk(res, error_500, strlen(error_500));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006802 if (!(strm->flags & SF_ERR_MASK))
6803 strm->flags |= SF_ERR_RESOURCE;
6804 si_shutw(si);
6805 si_shutr(si);
6806 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6807}
6808
6809static void hlua_applet_http_release(struct appctx *ctx)
6810{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006811 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006812 task_free(ctx->ctx.hlua_apphttp.task);
6813 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006814 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006815 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006816}
6817
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006818/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6819 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006820 *
6821 * This function can fail with an abort() due to an Lua critical error.
6822 * We are in the configuration parsing process of HAProxy, this abort() is
6823 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006824 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006825static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6826 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006827{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006828 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006829 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006830
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006831 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006832 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006833 if (!rule->arg.hlua_rule) {
6834 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006835 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006836 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006837
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006838 /* Memory for arguments. */
6839 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6840 if (!rule->arg.hlua_rule->args) {
6841 memprintf(err, "out of memory error");
6842 return ACT_RET_PRS_ERR;
6843 }
6844
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006845 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006846 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006847
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006848 /* Expect some arguments */
6849 for (i = 0; i < fcn->nargs; i++) {
6850 if (*args[i+1] == '\0') {
6851 memprintf(err, "expect %d arguments", fcn->nargs);
6852 return ACT_RET_PRS_ERR;
6853 }
6854 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6855 if (!rule->arg.hlua_rule->args[i]) {
6856 memprintf(err, "out of memory error");
6857 return ACT_RET_PRS_ERR;
6858 }
6859 (*cur_arg)++;
6860 }
6861 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006862
Thierry FOURNIER42148732015-09-02 17:17:33 +02006863 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006864 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006865 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006866}
6867
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006868static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6869 struct act_rule *rule, char **err)
6870{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006871 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006872
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006873 /* HTTP applets are forbidden in tcp-request rules.
6874 * HTTP applet request requires everything initilized by
6875 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6876 * The applet will be immediately initilized, but its before
6877 * the call of this analyzer.
6878 */
6879 if (rule->from != ACT_F_HTTP_REQ) {
6880 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6881 return ACT_RET_PRS_ERR;
6882 }
6883
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006884 /* Memory for the rule. */
6885 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6886 if (!rule->arg.hlua_rule) {
6887 memprintf(err, "out of memory error");
6888 return ACT_RET_PRS_ERR;
6889 }
6890
6891 /* Reference the Lua function and store the reference. */
6892 rule->arg.hlua_rule->fcn = *fcn;
6893
6894 /* TODO: later accept arguments. */
6895 rule->arg.hlua_rule->args = NULL;
6896
6897 /* Add applet pointer in the rule. */
6898 rule->applet.obj_type = OBJ_TYPE_APPLET;
6899 rule->applet.name = fcn->name;
6900 rule->applet.init = hlua_applet_http_init;
6901 rule->applet.fct = hlua_applet_http_fct;
6902 rule->applet.release = hlua_applet_http_release;
6903 rule->applet.timeout = hlua_timeout_applet;
6904
6905 return ACT_RET_PRS_OK;
6906}
6907
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006908/* This function is an LUA binding used for registering
6909 * "sample-conv" functions. It expects a converter name used
6910 * in the haproxy configuration file, and an LUA function.
6911 */
6912__LJMP static int hlua_register_action(lua_State *L)
6913{
6914 struct action_kw_list *akl;
6915 const char *name;
6916 int ref;
6917 int len;
6918 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006919 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006920
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006921 /* Initialise the number of expected arguments at 0. */
6922 nargs = 0;
6923
6924 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6925 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006926
6927 /* First argument : converter name. */
6928 name = MAY_LJMP(luaL_checkstring(L, 1));
6929
6930 /* Second argument : environment. */
6931 if (lua_type(L, 2) != LUA_TTABLE)
6932 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6933
6934 /* Third argument : lua function. */
6935 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6936
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006937 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6938 if (lua_gettop(L) >= 4)
6939 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6940
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006941 /* browse the second argulent as an array. */
6942 lua_pushnil(L);
6943 while (lua_next(L, 2) != 0) {
6944 if (lua_type(L, -1) != LUA_TSTRING)
6945 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6946
6947 /* Check required environment. Only accepted "http" or "tcp". */
6948 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006949 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006950 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006951 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006952 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006953 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006954 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006955
6956 /* Fill fcn. */
6957 fcn->name = strdup(name);
6958 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006959 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006960 fcn->function_ref = ref;
6961
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006962 /* Set the expected number od arguments. */
6963 fcn->nargs = nargs;
6964
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006965 /* List head */
6966 akl->list.n = akl->list.p = NULL;
6967
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006968 /* action keyword. */
6969 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006970 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006971 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006972 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006973
6974 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6975
6976 akl->kw[0].match_pfx = 0;
6977 akl->kw[0].private = fcn;
6978 akl->kw[0].parse = action_register_lua;
6979
6980 /* select the action registering point. */
6981 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6982 tcp_req_cont_keywords_register(akl);
6983 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6984 tcp_res_cont_keywords_register(akl);
6985 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6986 http_req_keywords_register(akl);
6987 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6988 http_res_keywords_register(akl);
6989 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006990 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006991 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6992 "are expected.", lua_tostring(L, -1)));
6993
6994 /* pop the environment string. */
6995 lua_pop(L, 1);
6996 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006997 return ACT_RET_PRS_OK;
6998}
6999
7000static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7001 struct act_rule *rule, char **err)
7002{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007003 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007004
7005 /* Memory for the rule. */
7006 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7007 if (!rule->arg.hlua_rule) {
7008 memprintf(err, "out of memory error");
7009 return ACT_RET_PRS_ERR;
7010 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007011
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007012 /* Reference the Lua function and store the reference. */
7013 rule->arg.hlua_rule->fcn = *fcn;
7014
7015 /* TODO: later accept arguments. */
7016 rule->arg.hlua_rule->args = NULL;
7017
7018 /* Add applet pointer in the rule. */
7019 rule->applet.obj_type = OBJ_TYPE_APPLET;
7020 rule->applet.name = fcn->name;
7021 rule->applet.init = hlua_applet_tcp_init;
7022 rule->applet.fct = hlua_applet_tcp_fct;
7023 rule->applet.release = hlua_applet_tcp_release;
7024 rule->applet.timeout = hlua_timeout_applet;
7025
7026 return 0;
7027}
7028
7029/* This function is an LUA binding used for registering
7030 * "sample-conv" functions. It expects a converter name used
7031 * in the haproxy configuration file, and an LUA function.
7032 */
7033__LJMP static int hlua_register_service(lua_State *L)
7034{
7035 struct action_kw_list *akl;
7036 const char *name;
7037 const char *env;
7038 int ref;
7039 int len;
7040 struct hlua_function *fcn;
7041
7042 MAY_LJMP(check_args(L, 3, "register_service"));
7043
7044 /* First argument : converter name. */
7045 name = MAY_LJMP(luaL_checkstring(L, 1));
7046
7047 /* Second argument : environment. */
7048 env = MAY_LJMP(luaL_checkstring(L, 2));
7049
7050 /* Third argument : lua function. */
7051 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7052
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007053 /* Allocate and fill the sample fetch keyword struct. */
7054 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7055 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007056 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007057 fcn = calloc(1, sizeof(*fcn));
7058 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007059 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007060
7061 /* Fill fcn. */
7062 len = strlen("<lua.>") + strlen(name) + 1;
7063 fcn->name = calloc(1, len);
7064 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007065 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007066 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7067 fcn->function_ref = ref;
7068
7069 /* List head */
7070 akl->list.n = akl->list.p = NULL;
7071
7072 /* converter keyword. */
7073 len = strlen("lua.") + strlen(name) + 1;
7074 akl->kw[0].kw = calloc(1, len);
7075 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007076 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007077
7078 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7079
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007080 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007081 if (strcmp(env, "tcp") == 0)
7082 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007083 else if (strcmp(env, "http") == 0)
7084 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007085 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007086 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007087 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007088
7089 akl->kw[0].match_pfx = 0;
7090 akl->kw[0].private = fcn;
7091
7092 /* End of array. */
7093 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7094
7095 /* Register this new converter */
7096 service_keywords_register(akl);
7097
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007098 return 0;
7099}
7100
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007101/* This function initialises Lua cli handler. It copies the
7102 * arguments in the Lua stack and create channel IO objects.
7103 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007104static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007105{
7106 struct hlua *hlua;
7107 struct hlua_function *fcn;
7108 int i;
7109 const char *error;
7110
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007111 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007112 appctx->ctx.hlua_cli.fcn = private;
7113
Willy Tarreaubafbe012017-11-24 17:34:44 +01007114 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007115 if (!hlua) {
7116 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007117 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007118 }
7119 HLUA_INIT(hlua);
7120 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007121
7122 /* Create task used by signal to wakeup applets.
7123 * We use the same wakeup fonction than the Lua applet_tcp and
7124 * applet_http. It is absolutely compatible.
7125 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007126 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007127 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007128 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007129 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007130 }
7131 appctx->ctx.hlua_cli.task->nice = 0;
7132 appctx->ctx.hlua_cli.task->context = appctx;
7133 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7134
7135 /* Initialises the Lua context */
7136 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
7137 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007138 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007139 }
7140
7141 /* The following Lua calls can fail. */
7142 if (!SET_SAFE_LJMP(hlua->T)) {
7143 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7144 error = lua_tostring(hlua->T, -1);
7145 else
7146 error = "critical error";
7147 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7148 goto error;
7149 }
7150
7151 /* Check stack available size. */
7152 if (!lua_checkstack(hlua->T, 2)) {
7153 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7154 goto error;
7155 }
7156
7157 /* Restore the function in the stack. */
7158 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7159
7160 /* Once the arguments parsed, the CLI is like an AppletTCP,
7161 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007162 */
7163 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7164 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7165 goto error;
7166 }
7167 hlua->nargs = 1;
7168
7169 /* push keywords in the stack. */
7170 for (i = 0; *args[i]; i++) {
7171 /* Check stack available size. */
7172 if (!lua_checkstack(hlua->T, 1)) {
7173 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7174 goto error;
7175 }
7176 lua_pushstring(hlua->T, args[i]);
7177 hlua->nargs++;
7178 }
7179
7180 /* We must initialize the execution timeouts. */
7181 hlua->max_time = hlua_timeout_session;
7182
7183 /* At this point the execution is safe. */
7184 RESET_SAFE_LJMP(hlua->T);
7185
7186 /* It's ok */
7187 return 0;
7188
7189 /* It's not ok. */
7190error:
7191 RESET_SAFE_LJMP(hlua->T);
7192 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007193 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007194 return 1;
7195}
7196
7197static int hlua_cli_io_handler_fct(struct appctx *appctx)
7198{
7199 struct hlua *hlua;
7200 struct stream_interface *si;
7201 struct hlua_function *fcn;
7202
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007203 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007204 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007205 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007206
7207 /* If the stream is disconnect or closed, ldo nothing. */
7208 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7209 return 1;
7210
7211 /* Execute the function. */
7212 switch (hlua_ctx_resume(hlua, 1)) {
7213
7214 /* finished. */
7215 case HLUA_E_OK:
7216 return 1;
7217
7218 /* yield. */
7219 case HLUA_E_AGAIN:
7220 /* We want write. */
7221 if (HLUA_IS_WAKERESWR(hlua))
7222 si_applet_cant_put(si);
7223 /* Set the timeout. */
7224 if (hlua->wake_time != TICK_ETERNITY)
7225 task_schedule(hlua->task, hlua->wake_time);
7226 return 0;
7227
7228 /* finished with error. */
7229 case HLUA_E_ERRMSG:
7230 /* Display log. */
7231 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
7232 fcn->name, lua_tostring(hlua->T, -1));
7233 lua_pop(hlua->T, 1);
7234 return 1;
7235
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007236 case HLUA_E_ETMOUT:
7237 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
7238 fcn->name);
7239 return 1;
7240
7241 case HLUA_E_NOMEM:
7242 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
7243 fcn->name);
7244 return 1;
7245
7246 case HLUA_E_YIELD: /* unexpected */
7247 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
7248 fcn->name);
7249 return 1;
7250
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007251 case HLUA_E_ERR:
7252 /* Display log. */
7253 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
7254 fcn->name);
7255 return 1;
7256
7257 default:
7258 return 1;
7259 }
7260
7261 return 1;
7262}
7263
7264static void hlua_cli_io_release_fct(struct appctx *appctx)
7265{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007266 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007267 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007268}
7269
7270/* This function is an LUA binding used for registering
7271 * new keywords in the cli. It expects a list of keywords
7272 * which are the "path". It is limited to 5 keywords. A
7273 * description of the command, a function to be executed
7274 * for the parsing and a function for io handlers.
7275 */
7276__LJMP static int hlua_register_cli(lua_State *L)
7277{
7278 struct cli_kw_list *cli_kws;
7279 const char *message;
7280 int ref_io;
7281 int len;
7282 struct hlua_function *fcn;
7283 int index;
7284 int i;
7285
7286 MAY_LJMP(check_args(L, 3, "register_cli"));
7287
7288 /* First argument : an array of maximum 5 keywords. */
7289 if (!lua_istable(L, 1))
7290 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
7291
7292 /* Second argument : string with contextual message. */
7293 message = MAY_LJMP(luaL_checkstring(L, 2));
7294
7295 /* Third and fourth argument : lua function. */
7296 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
7297
7298 /* Allocate and fill the sample fetch keyword struct. */
7299 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
7300 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007301 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007302 fcn = calloc(1, sizeof(*fcn));
7303 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007304 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007305
7306 /* Fill path. */
7307 index = 0;
7308 lua_pushnil(L);
7309 while(lua_next(L, 1) != 0) {
7310 if (index >= 5)
7311 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
7312 if (lua_type(L, -1) != LUA_TSTRING)
7313 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
7314 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
7315 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007316 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007317 index++;
7318 lua_pop(L, 1);
7319 }
7320
7321 /* Copy help message. */
7322 cli_kws->kw[0].usage = strdup(message);
7323 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007324 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007325
7326 /* Fill fcn io handler. */
7327 len = strlen("<lua.cli>") + 1;
7328 for (i = 0; i < index; i++)
7329 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
7330 fcn->name = calloc(1, len);
7331 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007332 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007333 strncat((char *)fcn->name, "<lua.cli", len);
7334 for (i = 0; i < index; i++) {
7335 strncat((char *)fcn->name, ".", len);
7336 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
7337 }
7338 strncat((char *)fcn->name, ">", len);
7339 fcn->function_ref = ref_io;
7340
7341 /* Fill last entries. */
7342 cli_kws->kw[0].private = fcn;
7343 cli_kws->kw[0].parse = hlua_cli_parse_fct;
7344 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
7345 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
7346
7347 /* Register this new converter */
7348 cli_register_kw(cli_kws);
7349
7350 return 0;
7351}
7352
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007353static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7354 struct proxy *defpx, const char *file, int line,
7355 char **err, unsigned int *timeout)
7356{
7357 const char *error;
7358
7359 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
7360 if (error && *error != '\0') {
7361 memprintf(err, "%s: invalid timeout", args[0]);
7362 return -1;
7363 }
7364 return 0;
7365}
7366
7367static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7368 struct proxy *defpx, const char *file, int line,
7369 char **err)
7370{
7371 return hlua_read_timeout(args, section_type, curpx, defpx,
7372 file, line, err, &hlua_timeout_session);
7373}
7374
7375static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7376 struct proxy *defpx, const char *file, int line,
7377 char **err)
7378{
7379 return hlua_read_timeout(args, section_type, curpx, defpx,
7380 file, line, err, &hlua_timeout_task);
7381}
7382
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007383static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7384 struct proxy *defpx, const char *file, int line,
7385 char **err)
7386{
7387 return hlua_read_timeout(args, section_type, curpx, defpx,
7388 file, line, err, &hlua_timeout_applet);
7389}
7390
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007391static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7392 struct proxy *defpx, const char *file, int line,
7393 char **err)
7394{
7395 char *error;
7396
7397 hlua_nb_instruction = strtoll(args[1], &error, 10);
7398 if (*error != '\0') {
7399 memprintf(err, "%s: invalid number", args[0]);
7400 return -1;
7401 }
7402 return 0;
7403}
7404
Willy Tarreau32f61e22015-03-18 17:54:59 +01007405static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7406 struct proxy *defpx, const char *file, int line,
7407 char **err)
7408{
7409 char *error;
7410
7411 if (*(args[1]) == 0) {
7412 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7413 return -1;
7414 }
7415 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7416 if (*error != '\0') {
7417 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7418 return -1;
7419 }
7420 return 0;
7421}
7422
7423
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007424/* This function is called by the main configuration key "lua-load". It loads and
7425 * execute an lua file during the parsing of the HAProxy configuration file. It is
7426 * the main lua entry point.
7427 *
7428 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7429 * occured, otherwise it returns 0.
7430 *
7431 * In some error case, LUA set an error message in top of the stack. This function
7432 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007433 *
7434 * This function can fail with an abort() due to an Lua critical error.
7435 * We are in the configuration parsing process of HAProxy, this abort() is
7436 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007437 */
7438static int hlua_load(char **args, int section_type, struct proxy *curpx,
7439 struct proxy *defpx, const char *file, int line,
7440 char **err)
7441{
7442 int error;
7443
7444 /* Just load and compile the file. */
7445 error = luaL_loadfile(gL.T, args[1]);
7446 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007447 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007448 lua_pop(gL.T, 1);
7449 return -1;
7450 }
7451
7452 /* If no syntax error where detected, execute the code. */
7453 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7454 switch (error) {
7455 case LUA_OK:
7456 break;
7457 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007458 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007459 lua_pop(gL.T, 1);
7460 return -1;
7461 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007462 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007463 return -1;
7464 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007465 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007466 lua_pop(gL.T, 1);
7467 return -1;
7468 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007469 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007470 lua_pop(gL.T, 1);
7471 return -1;
7472 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007473 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007474 lua_pop(gL.T, 1);
7475 return -1;
7476 }
7477
7478 return 0;
7479}
7480
7481/* configuration keywords declaration */
7482static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007483 { CFG_GLOBAL, "lua-load", hlua_load },
7484 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7485 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007486 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007487 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007488 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007489 { 0, NULL, NULL },
7490}};
7491
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007492/* This function can fail with an abort() due to an Lua critical error.
7493 * We are in the initialisation process of HAProxy, this abort() is
7494 * tolerated.
7495 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007496int hlua_post_init()
7497{
7498 struct hlua_init_function *init;
7499 const char *msg;
7500 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007501 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007502
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007503 /* Call post initialisation function in safe environement. */
7504 if (!SET_SAFE_LJMP(gL.T)) {
7505 if (lua_type(gL.T, -1) == LUA_TSTRING)
7506 error = lua_tostring(gL.T, -1);
7507 else
7508 error = "critical error";
7509 fprintf(stderr, "Lua post-init: %s.\n", error);
7510 exit(1);
7511 }
7512 hlua_fcn_post_init(gL.T);
7513 RESET_SAFE_LJMP(gL.T);
7514
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007515 list_for_each_entry(init, &hlua_init_functions, l) {
7516 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7517 ret = hlua_ctx_resume(&gL, 0);
7518 switch (ret) {
7519 case HLUA_E_OK:
7520 lua_pop(gL.T, -1);
7521 return 1;
7522 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007523 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007524 return 0;
7525 case HLUA_E_ERRMSG:
7526 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01007527 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007528 return 0;
7529 case HLUA_E_ERR:
7530 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007531 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007532 return 0;
7533 }
7534 }
7535 return 1;
7536}
7537
Willy Tarreau32f61e22015-03-18 17:54:59 +01007538/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7539 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7540 * is the previously allocated size or the kind of object in case of a new
7541 * allocation. <nsize> is the requested new size.
7542 */
7543static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7544{
7545 struct hlua_mem_allocator *zone = ud;
7546
7547 if (nsize == 0) {
7548 /* it's a free */
7549 if (ptr)
7550 zone->allocated -= osize;
7551 free(ptr);
7552 return NULL;
7553 }
7554
7555 if (!ptr) {
7556 /* it's a new allocation */
7557 if (zone->limit && zone->allocated + nsize > zone->limit)
7558 return NULL;
7559
7560 ptr = malloc(nsize);
7561 if (ptr)
7562 zone->allocated += nsize;
7563 return ptr;
7564 }
7565
7566 /* it's a realloc */
7567 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7568 return NULL;
7569
7570 ptr = realloc(ptr, nsize);
7571 if (ptr)
7572 zone->allocated += nsize - osize;
7573 return ptr;
7574}
7575
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007576/* Ithis function can fail with an abort() due to an Lua critical error.
7577 * We are in the initialisation process of HAProxy, this abort() is
7578 * tolerated.
7579 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007580void hlua_init(void)
7581{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007582 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007583 int idx;
7584 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007585 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007586 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007587 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007588#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007589 struct srv_kw *kw;
7590 int tmp_error;
7591 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007592 char *args[] = { /* SSL client configuration. */
7593 "ssl",
7594 "verify",
7595 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007596 NULL
7597 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007598#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007599
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007600 HA_SPIN_INIT(&hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02007601
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007602 /* Initialise struct hlua and com signals pool */
Willy Tarreaubafbe012017-11-24 17:34:44 +01007603 pool_head_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007604
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007605 /* Register configuration keywords. */
7606 cfg_register_keywords(&cfg_kws);
7607
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007608 /* Init main lua stack. */
7609 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007610 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007611 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007612 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007613 hlua_sethlua(&gL);
7614 gL.Tref = LUA_REFNIL;
7615 gL.task = NULL;
7616
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007617 /* From this point, until the end of the initialisation fucntion,
7618 * the Lua function can fail with an abort. We are in the initialisation
7619 * process of HAProxy, this abort() is tolerated.
7620 */
7621
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007622 /* Initialise lua. */
7623 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007624
Thierry Fournier75933d42016-01-21 09:30:18 +01007625 /* Set safe environment for the initialisation. */
7626 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007627 if (lua_type(gL.T, -1) == LUA_TSTRING)
7628 error_msg = lua_tostring(gL.T, -1);
7629 else
7630 error_msg = "critical error";
7631 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007632 exit(1);
7633 }
7634
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007635 /*
7636 *
7637 * Create "core" object.
7638 *
7639 */
7640
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007641 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007642 lua_newtable(gL.T);
7643
7644 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007645 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007646 hlua_class_const_int(gL.T, log_levels[i], i);
7647
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007648 /* Register special functions. */
7649 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007650 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007651 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007652 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007653 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007654 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007655 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007656 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007657 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007658 hlua_class_function(gL.T, "sleep", hlua_sleep);
7659 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007660 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7661 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7662 hlua_class_function(gL.T, "set_map", hlua_set_map);
7663 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007664 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007665 hlua_class_function(gL.T, "log", hlua_log);
7666 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7667 hlua_class_function(gL.T, "Info", hlua_log_info);
7668 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7669 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007670 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007671 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007672
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007673 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007674
7675 /*
7676 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007677 * Register class Map
7678 *
7679 */
7680
7681 /* This table entry is the object "Map" base. */
7682 lua_newtable(gL.T);
7683
7684 /* register pattern types. */
7685 for (i=0; i<PAT_MATCH_NUM; i++)
7686 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007687 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007688 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
7689 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007690 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007691
7692 /* register constructor. */
7693 hlua_class_function(gL.T, "new", hlua_map_new);
7694
7695 /* Create and fill the metatable. */
7696 lua_newtable(gL.T);
7697
7698 /* Create and fille the __index entry. */
7699 lua_pushstring(gL.T, "__index");
7700 lua_newtable(gL.T);
7701
7702 /* Register . */
7703 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7704 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7705
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007706 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007707
Thierry Fournier45e78d72016-02-19 18:34:46 +01007708 /* Register previous table in the registry with reference and named entry.
7709 * The function hlua_register_metatable() pops the stack, so we
7710 * previously create a copy of the table.
7711 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007712 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007713 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007714
7715 /* Assign the metatable to the mai Map object. */
7716 lua_setmetatable(gL.T, -2);
7717
7718 /* Set a name to the table. */
7719 lua_setglobal(gL.T, "Map");
7720
7721 /*
7722 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007723 * Register class Channel
7724 *
7725 */
7726
7727 /* Create and fill the metatable. */
7728 lua_newtable(gL.T);
7729
7730 /* Create and fille the __index entry. */
7731 lua_pushstring(gL.T, "__index");
7732 lua_newtable(gL.T);
7733
7734 /* Register . */
7735 hlua_class_function(gL.T, "get", hlua_channel_get);
7736 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7737 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7738 hlua_class_function(gL.T, "set", hlua_channel_set);
7739 hlua_class_function(gL.T, "append", hlua_channel_append);
7740 hlua_class_function(gL.T, "send", hlua_channel_send);
7741 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7742 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7743 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007744 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007745
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007746 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007747
7748 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007749 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007750
7751 /*
7752 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007753 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007754 *
7755 */
7756
7757 /* Create and fill the metatable. */
7758 lua_newtable(gL.T);
7759
7760 /* Create and fille the __index entry. */
7761 lua_pushstring(gL.T, "__index");
7762 lua_newtable(gL.T);
7763
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007764 /* Browse existing fetches and create the associated
7765 * object method.
7766 */
7767 sf = NULL;
7768 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7769
7770 /* Dont register the keywork if the arguments check function are
7771 * not safe during the runtime.
7772 */
7773 if ((sf->val_args != NULL) &&
7774 (sf->val_args != val_payload_lv) &&
7775 (sf->val_args != val_hdr))
7776 continue;
7777
7778 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7779 * by an underscore.
7780 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007781 strncpy(trash.area, sf->kw, trash.size);
7782 trash.area[trash.size - 1] = '\0';
7783 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007784 if (*p == '.' || *p == '-' || *p == '+')
7785 *p = '_';
7786
7787 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007788 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007789 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007790 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007791 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007792 }
7793
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007794 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007795
7796 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007797 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007798
7799 /*
7800 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007801 * Register class Converters
7802 *
7803 */
7804
7805 /* Create and fill the metatable. */
7806 lua_newtable(gL.T);
7807
7808 /* Create and fill the __index entry. */
7809 lua_pushstring(gL.T, "__index");
7810 lua_newtable(gL.T);
7811
7812 /* Browse existing converters and create the associated
7813 * object method.
7814 */
7815 sc = NULL;
7816 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7817 /* Dont register the keywork if the arguments check function are
7818 * not safe during the runtime.
7819 */
7820 if (sc->val_args != NULL)
7821 continue;
7822
7823 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7824 * by an underscore.
7825 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007826 strncpy(trash.area, sc->kw, trash.size);
7827 trash.area[trash.size - 1] = '\0';
7828 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007829 if (*p == '.' || *p == '-' || *p == '+')
7830 *p = '_';
7831
7832 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007833 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007834 lua_pushlightuserdata(gL.T, sc);
7835 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007836 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007837 }
7838
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007839 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007840
7841 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007842 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007843
7844 /*
7845 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007846 * Register class HTTP
7847 *
7848 */
7849
7850 /* Create and fill the metatable. */
7851 lua_newtable(gL.T);
7852
7853 /* Create and fille the __index entry. */
7854 lua_pushstring(gL.T, "__index");
7855 lua_newtable(gL.T);
7856
7857 /* Register Lua functions. */
7858 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7859 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7860 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7861 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7862 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7863 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7864 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7865 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7866 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7867 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7868
7869 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7870 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7871 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7872 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7873 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7874 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007875 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007876
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007877 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007878
7879 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007880 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007881
7882 /*
7883 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007884 * Register class AppletTCP
7885 *
7886 */
7887
7888 /* Create and fill the metatable. */
7889 lua_newtable(gL.T);
7890
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007891 /* Create and fille the __index entry. */
7892 lua_pushstring(gL.T, "__index");
7893 lua_newtable(gL.T);
7894
7895 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007896 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7897 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7898 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7899 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7900 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007901 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7902 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7903 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007904
7905 lua_settable(gL.T, -3);
7906
7907 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007908 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007909
7910 /*
7911 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007912 * Register class AppletHTTP
7913 *
7914 */
7915
7916 /* Create and fill the metatable. */
7917 lua_newtable(gL.T);
7918
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007919 /* Create and fille the __index entry. */
7920 lua_pushstring(gL.T, "__index");
7921 lua_newtable(gL.T);
7922
7923 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007924 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7925 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007926 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7927 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7928 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007929 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7930 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7931 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7932 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7933 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7934 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7935
7936 lua_settable(gL.T, -3);
7937
7938 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007939 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007940
7941 /*
7942 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007943 * Register class TXN
7944 *
7945 */
7946
7947 /* Create and fill the metatable. */
7948 lua_newtable(gL.T);
7949
7950 /* Create and fille the __index entry. */
7951 lua_pushstring(gL.T, "__index");
7952 lua_newtable(gL.T);
7953
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007954 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04007955 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7956 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
7957 hlua_class_function(gL.T, "set_var", hlua_set_var);
7958 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
7959 hlua_class_function(gL.T, "get_var", hlua_get_var);
7960 hlua_class_function(gL.T, "done", hlua_txn_done);
7961 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
7962 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7963 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
7964 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
7965 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
7966 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7967 hlua_class_function(gL.T, "log", hlua_txn_log);
7968 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7969 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7970 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7971 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007972
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007973 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007974
7975 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007976 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007977
7978 /*
7979 *
7980 * Register class Socket
7981 *
7982 */
7983
7984 /* Create and fill the metatable. */
7985 lua_newtable(gL.T);
7986
7987 /* Create and fille the __index entry. */
7988 lua_pushstring(gL.T, "__index");
7989 lua_newtable(gL.T);
7990
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007991#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007992 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007993#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007994 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7995 hlua_class_function(gL.T, "send", hlua_socket_send);
7996 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7997 hlua_class_function(gL.T, "close", hlua_socket_close);
7998 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7999 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8000 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8001 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8002
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008003 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008004
8005 /* Register the garbage collector entry. */
8006 lua_pushstring(gL.T, "__gc");
8007 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008008 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008009
8010 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008011 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008012
8013 /* Proxy and server configuration initialisation. */
8014 memset(&socket_proxy, 0, sizeof(socket_proxy));
8015 init_new_proxy(&socket_proxy);
8016 socket_proxy.parent = NULL;
8017 socket_proxy.last_change = now.tv_sec;
8018 socket_proxy.id = "LUA-SOCKET";
8019 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8020 socket_proxy.maxconn = 0;
8021 socket_proxy.accept = NULL;
8022 socket_proxy.options2 |= PR_O2_INDEPSTR;
8023 socket_proxy.srv = NULL;
8024 socket_proxy.conn_retries = 0;
8025 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8026
8027 /* Init TCP server: unchanged parameters */
8028 memset(&socket_tcp, 0, sizeof(socket_tcp));
8029 socket_tcp.next = NULL;
8030 socket_tcp.proxy = &socket_proxy;
8031 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8032 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008033 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008034 socket_tcp.priv_conns = NULL;
8035 socket_tcp.idle_conns = NULL;
8036 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008037 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008038 socket_tcp.last_change = 0;
8039 socket_tcp.id = "LUA-TCP-CONN";
8040 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8041 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8042 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
8043
8044 /* XXX: Copy default parameter from default server,
8045 * but the default server is not initialized.
8046 */
8047 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
8048 socket_tcp.minconn = socket_proxy.defsrv.minconn;
8049 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
8050 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
8051 socket_tcp.onerror = socket_proxy.defsrv.onerror;
8052 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8053 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
8054 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8055 socket_tcp.uweight = socket_proxy.defsrv.iweight;
8056 socket_tcp.iweight = socket_proxy.defsrv.iweight;
8057
8058 socket_tcp.check.status = HCHK_STATUS_INI;
8059 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
8060 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
8061 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
8062 socket_tcp.check.server = &socket_tcp;
8063
8064 socket_tcp.agent.status = HCHK_STATUS_INI;
8065 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
8066 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
8067 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
8068 socket_tcp.agent.server = &socket_tcp;
8069
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008070 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008071
8072#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008073 /* Init TCP server: unchanged parameters */
8074 memset(&socket_ssl, 0, sizeof(socket_ssl));
8075 socket_ssl.next = NULL;
8076 socket_ssl.proxy = &socket_proxy;
8077 socket_ssl.obj_type = OBJ_TYPE_SERVER;
8078 LIST_INIT(&socket_ssl.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008079 socket_ssl.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008080 socket_tcp.priv_conns = NULL;
8081 socket_tcp.idle_conns = NULL;
8082 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008083 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008084 socket_ssl.last_change = 0;
8085 socket_ssl.id = "LUA-SSL-CONN";
8086 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8087 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8088 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8089
8090 /* XXX: Copy default parameter from default server,
8091 * but the default server is not initialized.
8092 */
8093 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8094 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8095 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8096 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8097 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8098 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8099 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8100 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8101 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8102 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8103
8104 socket_ssl.check.status = HCHK_STATUS_INI;
8105 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8106 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8107 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8108 socket_ssl.check.server = &socket_ssl;
8109
8110 socket_ssl.agent.status = HCHK_STATUS_INI;
8111 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8112 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8113 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8114 socket_ssl.agent.server = &socket_ssl;
8115
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008116 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008117 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008118
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008119 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008120 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8121 /*
8122 *
8123 * If the keyword is not known, we can search in the registered
8124 * server keywords. This is usefull to configure special SSL
8125 * features like client certificates and ssl_verify.
8126 *
8127 */
8128 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8129 if (tmp_error != 0) {
8130 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8131 abort(); /* This must be never arrives because the command line
8132 not editable by the user. */
8133 }
8134 idx += kw->skip;
8135 }
8136 }
8137
8138 /* Initialize SSL server. */
Willy Tarreaucbe6da52018-05-18 17:08:28 +02008139 if (socket_ssl.xprt->prepare_srv) {
8140 int saved_used_backed = global.ssl_used_backend;
8141 // don't affect maxconn automatic computation
Willy Tarreau17d45382016-12-22 21:16:08 +01008142 socket_ssl.xprt->prepare_srv(&socket_ssl);
Willy Tarreaucbe6da52018-05-18 17:08:28 +02008143 global.ssl_used_backend = saved_used_backed;
8144 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008145#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008146
8147 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008148}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008149
8150__attribute__((constructor))
8151static void __hlua_init(void)
8152{
8153 char *ptr = NULL;
8154 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8155 hap_register_build_opts(ptr, 1);
8156}