blob: 32199c9640f72ea625e56f59e90556f9df411b1e [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>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010047#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010048#include <proto/payload.h>
49#include <proto/proto_http.h>
50#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010051#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020052#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020053#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010054#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010055#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010056#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020057#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010058
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010059/* Lua uses longjmp to perform yield or throwing errors. This
60 * macro is used only for identifying the function that can
61 * not return because a longjmp is executed.
62 * __LJMP marks a prototype of hlua file that can use longjmp.
63 * WILL_LJMP() marks an lua function that will use longjmp.
64 * MAY_LJMP() marks an lua function that may use longjmp.
65 */
66#define __LJMP
67#define WILL_LJMP(func) func
68#define MAY_LJMP(func) func
69
Thierry FOURNIERbabae282015-09-17 11:36:37 +020070/* This couple of function executes securely some Lua calls outside of
71 * the lua runtime environment. Each Lua call can return a longjmp
72 * if it encounter a memory error.
73 *
74 * Lua documentation extract:
75 *
76 * If an error happens outside any protected environment, Lua calls
77 * a panic function (see lua_atpanic) and then calls abort, thus
78 * exiting the host application. Your panic function can avoid this
79 * exit by never returning (e.g., doing a long jump to your own
80 * recovery point outside Lua).
81 *
82 * The panic function runs as if it were a message handler (see
83 * §2.3); in particular, the error message is at the top of the
84 * stack. However, there is no guarantee about stack space. To push
85 * anything on the stack, the panic function must first check the
86 * available space (see §4.2).
87 *
88 * We must check all the Lua entry point. This includes:
89 * - The include/proto/hlua.h exported functions
90 * - the task wrapper function
91 * - The action wrapper function
92 * - The converters wrapper function
93 * - The sample-fetch wrapper functions
94 *
95 * It is tolerated that the initilisation function returns an abort.
96 * Before each Lua abort, an error message is writed on stderr.
97 *
98 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
99 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
100 * because they must be exists in the program stack when the longjmp
101 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200102 *
103 * Note that the Lua processing is not really thread safe. It provides
104 * heavy system which consists to add our own lock function in the Lua
105 * code and recompile the library. This system will probably not accepted
106 * by maintainers of various distribs.
107 *
108 * Our main excution point of the Lua is the function lua_resume(). A
109 * quick looking on the Lua sources displays a lua_lock() a the start
110 * of function and a lua_unlock() at the end of the function. So I
111 * conclude that the Lua thread safe mode just perform a mutex around
112 * all execution. So I prefer to do this in the HAProxy code, it will be
113 * easier for distro maintainers.
114 *
115 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
116 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
117 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200118 */
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100119__decl_hathreads(HA_SPINLOCK_T hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200120THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200121static int hlua_panic_safe(lua_State *L) { return 0; }
122static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
123
124#define SET_SAFE_LJMP(__L) \
125 ({ \
126 int ret; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100127 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200128 if (setjmp(safe_ljmp_env) != 0) { \
129 lua_atpanic(__L, hlua_panic_safe); \
130 ret = 0; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100131 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200132 } else { \
133 lua_atpanic(__L, hlua_panic_ljmp); \
134 ret = 1; \
135 } \
136 ret; \
137 })
138
139/* If we are the last function catching Lua errors, we
140 * must reset the panic function.
141 */
142#define RESET_SAFE_LJMP(__L) \
143 do { \
144 lua_atpanic(__L, hlua_panic_safe); \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100145 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200146 } while(0)
147
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200148/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200149#define APPLET_DONE 0x01 /* applet processing is done. */
150#define APPLET_100C 0x02 /* 100 continue expected. */
151#define APPLET_HDR_SENT 0x04 /* Response header sent. */
152#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
153#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100154#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200155
156#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200157
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100158/* The main Lua execution context. */
159struct hlua gL;
160
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100161/* This is the memory pool containing struct lua for applets
162 * (including cli).
163 */
Willy Tarreaubafbe012017-11-24 17:34:44 +0100164struct pool_head *pool_head_hlua;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100165
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100166/* Used for Socket connection. */
167static struct proxy socket_proxy;
168static struct server socket_tcp;
169#ifdef USE_OPENSSL
170static struct server socket_ssl;
171#endif
172
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100173/* List head of the function called at the initialisation time. */
174struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
175
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100176/* The following variables contains the reference of the different
177 * Lua classes. These references are useful for identify metadata
178 * associated with an object.
179 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100180static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100181static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100182static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100183static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100184static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100185static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200186static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200187static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200188static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100189
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100190/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200191 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100192 * short timeout. Lua linked with tasks doesn't have a timeout
193 * because a task may remain alive during all the haproxy execution.
194 */
195static unsigned int hlua_timeout_session = 4000; /* session timeout. */
196static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200197static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100198
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100199/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
200 * it is used for preventing infinite loops.
201 *
202 * I test the scheer with an infinite loop containing one incrementation
203 * and one test. I run this loop between 10 seconds, I raise a ceil of
204 * 710M loops from one interrupt each 9000 instructions, so I fix the value
205 * to one interrupt each 10 000 instructions.
206 *
207 * configured | Number of
208 * instructions | loops executed
209 * between two | in milions
210 * forced yields |
211 * ---------------+---------------
212 * 10 | 160
213 * 500 | 670
214 * 1000 | 680
215 * 5000 | 700
216 * 7000 | 700
217 * 8000 | 700
218 * 9000 | 710 <- ceil
219 * 10000 | 710
220 * 100000 | 710
221 * 1000000 | 710
222 *
223 */
224static unsigned int hlua_nb_instruction = 10000;
225
Willy Tarreau32f61e22015-03-18 17:54:59 +0100226/* Descriptor for the memory allocation state. If limit is not null, it will
227 * be enforced on any memory allocation.
228 */
229struct hlua_mem_allocator {
230 size_t allocated;
231 size_t limit;
232};
233
234static struct hlua_mem_allocator hlua_global_allocator;
235
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200236static const char error_500[] =
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200237 "HTTP/1.0 500 Internal Server Error\r\n"
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200238 "Cache-Control: no-cache\r\n"
239 "Connection: close\r\n"
240 "Content-Type: text/html\r\n"
241 "\r\n"
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200242 "<html><body><h1>500 Internal Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200243
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100244/* These functions converts types between HAProxy internal args or
245 * sample and LUA types. Another function permits to check if the
246 * LUA stack contains arguments according with an required ARG_T
247 * format.
248 */
249static int hlua_arg2lua(lua_State *L, const struct arg *arg);
250static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100251__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100252 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100253static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100254static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100255static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
256
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200257__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
258
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200259#define SEND_ERR(__be, __fmt, __args...) \
260 do { \
261 send_log(__be, LOG_ERR, __fmt, ## __args); \
262 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100263 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200264 } while (0)
265
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100266/* Used to check an Lua function type in the stack. It creates and
267 * returns a reference of the function. This function throws an
268 * error if the rgument is not a "function".
269 */
270__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
271{
272 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100273 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100274 WILL_LJMP(luaL_argerror(L, argno, msg));
275 }
276 lua_pushvalue(L, argno);
277 return luaL_ref(L, LUA_REGISTRYINDEX);
278}
279
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200280/* Return the string that is of the top of the stack. */
281const char *hlua_get_top_error_string(lua_State *L)
282{
283 if (lua_gettop(L) < 1)
284 return "unknown error";
285 if (lua_type(L, -1) != LUA_TSTRING)
286 return "unknown error";
287 return lua_tostring(L, -1);
288}
289
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100290/* This function check the number of arguments available in the
291 * stack. If the number of arguments available is not the same
292 * then <nb> an error is throwed.
293 */
294__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
295{
296 if (lua_gettop(L) == nb)
297 return;
298 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
299}
300
Mark Lakes22154b42018-01-29 14:38:40 -0800301/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100302 * and the line number where the error is encountered.
303 */
304static int hlua_pusherror(lua_State *L, const char *fmt, ...)
305{
306 va_list argp;
307 va_start(argp, fmt);
308 luaL_where(L, 1);
309 lua_pushvfstring(L, fmt, argp);
310 va_end(argp);
311 lua_concat(L, 2);
312 return 1;
313}
314
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100315/* This functions is used with sample fetch and converters. It
316 * converts the HAProxy configuration argument in a lua stack
317 * values.
318 *
319 * It takes an array of "arg", and each entry of the array is
320 * converted and pushed in the LUA stack.
321 */
322static int hlua_arg2lua(lua_State *L, const struct arg *arg)
323{
324 switch (arg->type) {
325 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100326 case ARGT_TIME:
327 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100328 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100329 break;
330
331 case ARGT_STR:
332 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
333 break;
334
335 case ARGT_IPV4:
336 case ARGT_IPV6:
337 case ARGT_MSK4:
338 case ARGT_MSK6:
339 case ARGT_FE:
340 case ARGT_BE:
341 case ARGT_TAB:
342 case ARGT_SRV:
343 case ARGT_USR:
344 case ARGT_MAP:
345 default:
346 lua_pushnil(L);
347 break;
348 }
349 return 1;
350}
351
352/* This function take one entrie in an LUA stack at the index "ud",
353 * and try to convert it in an HAProxy argument entry. This is useful
354 * with sample fetch wrappers. The input arguments are gived to the
355 * lua wrapper and converted as arg list by thi function.
356 */
357static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
358{
359 switch (lua_type(L, ud)) {
360
361 case LUA_TNUMBER:
362 case LUA_TBOOLEAN:
363 arg->type = ARGT_SINT;
364 arg->data.sint = lua_tointeger(L, ud);
365 break;
366
367 case LUA_TSTRING:
368 arg->type = ARGT_STR;
369 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
370 break;
371
372 case LUA_TUSERDATA:
373 case LUA_TNIL:
374 case LUA_TTABLE:
375 case LUA_TFUNCTION:
376 case LUA_TTHREAD:
377 case LUA_TLIGHTUSERDATA:
378 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200379 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100380 break;
381 }
382 return 1;
383}
384
385/* the following functions are used to convert a struct sample
386 * in Lua type. This useful to convert the return of the
387 * fetchs or converters.
388 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100389static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100390{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200391 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100392 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100393 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200394 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100395 break;
396
397 case SMP_T_BIN:
398 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200399 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100400 break;
401
402 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200403 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100404 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
405 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
406 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
407 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
408 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
409 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
410 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
411 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
412 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200413 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100414 break;
415 default:
416 lua_pushnil(L);
417 break;
418 }
419 break;
420
421 case SMP_T_IPV4:
422 case SMP_T_IPV6:
423 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200424 if (sample_casts[smp->data.type][SMP_T_STR] &&
425 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200426 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100427 else
428 lua_pushnil(L);
429 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100430 default:
431 lua_pushnil(L);
432 break;
433 }
434 return 1;
435}
436
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100437/* the following functions are used to convert a struct sample
438 * in Lua strings. This is useful to convert the return of the
439 * fetchs or converters.
440 */
441static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
442{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200443 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100444
445 case SMP_T_BIN:
446 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200447 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100448 break;
449
450 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200451 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100452 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
453 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
454 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
455 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
456 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
457 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
458 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
459 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
460 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200461 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100462 break;
463 default:
464 lua_pushstring(L, "");
465 break;
466 }
467 break;
468
469 case SMP_T_SINT:
470 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100471 case SMP_T_IPV4:
472 case SMP_T_IPV6:
473 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200474 if (sample_casts[smp->data.type][SMP_T_STR] &&
475 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200476 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100477 else
478 lua_pushstring(L, "");
479 break;
480 default:
481 lua_pushstring(L, "");
482 break;
483 }
484 return 1;
485}
486
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100487/* the following functions are used to convert an Lua type in a
488 * struct sample. This is useful to provide data from a converter
489 * to the LUA code.
490 */
491static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
492{
493 switch (lua_type(L, ud)) {
494
495 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200496 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200497 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100498 break;
499
500
501 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200502 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200503 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100504 break;
505
506 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200507 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100508 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200509 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100510 break;
511
512 case LUA_TUSERDATA:
513 case LUA_TNIL:
514 case LUA_TTABLE:
515 case LUA_TFUNCTION:
516 case LUA_TTHREAD:
517 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200518 case LUA_TNONE:
519 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200520 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200521 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100522 break;
523 }
524 return 1;
525}
526
527/* This function check the "argp" builded by another conversion function
528 * is in accord with the expected argp defined by the "mask". The fucntion
529 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100530 *
531 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
532 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100533 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100534__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100535 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100536{
537 int min_arg;
538 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100539 struct proxy *px;
540 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100541
542 idx = 0;
543 min_arg = ARGM(mask);
544 mask >>= ARGM_BITS;
545
546 while (1) {
547
548 /* Check oversize. */
549 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100550 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100551 }
552
553 /* Check for mandatory arguments. */
554 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100555 if (idx < min_arg) {
556
557 /* If miss other argument than the first one, we return an error. */
558 if (idx > 0)
559 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
560
561 /* If first argument have a certain type, some default values
562 * may be used. See the function smp_resolve_args().
563 */
564 switch (mask & ARGT_MASK) {
565
566 case ARGT_FE:
567 if (!(p->cap & PR_CAP_FE))
568 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
569 argp[idx].data.prx = p;
570 argp[idx].type = ARGT_FE;
571 argp[idx+1].type = ARGT_STOP;
572 break;
573
574 case ARGT_BE:
575 if (!(p->cap & PR_CAP_BE))
576 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
577 argp[idx].data.prx = p;
578 argp[idx].type = ARGT_BE;
579 argp[idx+1].type = ARGT_STOP;
580 break;
581
582 case ARGT_TAB:
583 argp[idx].data.prx = p;
584 argp[idx].type = ARGT_TAB;
585 argp[idx+1].type = ARGT_STOP;
586 break;
587
588 default:
589 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
590 break;
591 }
592 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100593 return 0;
594 }
595
596 /* Check for exceed the number of requiered argument. */
597 if ((mask & ARGT_MASK) == ARGT_STOP &&
598 argp[idx].type != ARGT_STOP) {
599 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
600 }
601
602 if ((mask & ARGT_MASK) == ARGT_STOP &&
603 argp[idx].type == ARGT_STOP) {
604 return 0;
605 }
606
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100607 /* Convert some argument types. */
608 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100609 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100610 if (argp[idx].type != ARGT_SINT)
611 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
612 argp[idx].type = ARGT_SINT;
613 break;
614
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100615 case ARGT_TIME:
616 if (argp[idx].type != ARGT_SINT)
617 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200618 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100619 break;
620
621 case ARGT_SIZE:
622 if (argp[idx].type != ARGT_SINT)
623 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200624 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100625 break;
626
627 case ARGT_FE:
628 if (argp[idx].type != ARGT_STR)
629 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
630 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
631 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200632 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100633 if (!argp[idx].data.prx)
634 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
635 argp[idx].type = ARGT_FE;
636 break;
637
638 case ARGT_BE:
639 if (argp[idx].type != ARGT_STR)
640 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
641 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
642 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200643 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100644 if (!argp[idx].data.prx)
645 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
646 argp[idx].type = ARGT_BE;
647 break;
648
649 case ARGT_TAB:
650 if (argp[idx].type != ARGT_STR)
651 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
652 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
653 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200654 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100655 if (!argp[idx].data.prx)
656 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
657 argp[idx].type = ARGT_TAB;
658 break;
659
660 case ARGT_SRV:
661 if (argp[idx].type != ARGT_STR)
662 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
663 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
664 trash.str[argp[idx].data.str.len] = 0;
665 sname = strrchr(trash.str, '/');
666 if (sname) {
667 *sname++ = '\0';
668 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200669 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100670 if (!px)
671 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
672 }
673 else {
674 sname = trash.str;
675 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100676 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100677 argp[idx].data.srv = findserver(px, sname);
678 if (!argp[idx].data.srv)
679 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
680 argp[idx].type = ARGT_SRV;
681 break;
682
683 case ARGT_IPV4:
684 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
685 trash.str[argp[idx].data.str.len] = 0;
686 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
687 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
688 argp[idx].type = ARGT_IPV4;
689 break;
690
691 case ARGT_MSK4:
692 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
693 trash.str[argp[idx].data.str.len] = 0;
694 if (!str2mask(trash.str, &argp[idx].data.ipv4))
695 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
696 argp[idx].type = ARGT_MSK4;
697 break;
698
699 case ARGT_IPV6:
700 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
701 trash.str[argp[idx].data.str.len] = 0;
702 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
703 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
704 argp[idx].type = ARGT_IPV6;
705 break;
706
707 case ARGT_MSK6:
Tim Duesterhusb814da62018-01-25 16:24:50 +0100708 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
709 trash.str[argp[idx].data.str.len] = 0;
710 if (!str2mask6(trash.str, &argp[idx].data.ipv6))
711 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 mask"));
712 argp[idx].type = ARGT_MSK6;
713 break;
714
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100715 case ARGT_MAP:
716 case ARGT_REG:
717 case ARGT_USR:
718 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100719 break;
720 }
721
722 /* Check for type of argument. */
723 if ((mask & ARGT_MASK) != argp[idx].type) {
724 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
725 arg_type_names[(mask & ARGT_MASK)],
726 arg_type_names[argp[idx].type & ARGT_MASK]);
727 WILL_LJMP(luaL_argerror(L, first + idx, msg));
728 }
729
730 /* Next argument. */
731 mask >>= ARGT_BITS;
732 idx++;
733 }
734}
735
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100736/*
737 * The following functions are used to make correspondance between the the
738 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100739 *
740 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100741 * - hlua_sethlua : create the association between hlua context and lua_state.
742 */
743static inline struct hlua *hlua_gethlua(lua_State *L)
744{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100745 struct hlua **hlua = lua_getextraspace(L);
746 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100747}
748static inline void hlua_sethlua(struct hlua *hlua)
749{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100750 struct hlua **hlua_store = lua_getextraspace(hlua->T);
751 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100752}
753
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100754/* This function is used to send logs. It try to send on screen (stderr)
755 * and on the default syslog server.
756 */
757static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
758{
759 struct tm tm;
760 char *p;
761
762 /* Cleanup the log message. */
763 p = trash.str;
764 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200765 if (p >= trash.str + trash.size - 1) {
766 /* Break the message if exceed the buffer size. */
767 *(p-4) = ' ';
768 *(p-3) = '.';
769 *(p-2) = '.';
770 *(p-1) = '.';
771 break;
772 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100773 if (isprint(*msg))
774 *p = *msg;
775 else
776 *p = '.';
777 }
778 *p = '\0';
779
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200780 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100781 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200782 get_localtime(date.tv_sec, &tm);
783 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100784 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
785 (int)getpid(), trash.str);
786 fflush(stderr);
787 }
788}
789
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100790/* This function just ensure that the yield will be always
791 * returned with a timeout and permit to set some flags
792 */
793__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100794 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100795{
796 struct hlua *hlua = hlua_gethlua(L);
797
798 /* Set the wake timeout. If timeout is required, we set
799 * the expiration time.
800 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200801 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100802
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100803 hlua->flags |= flags;
804
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100805 /* Process the yield. */
806 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
807}
808
Willy Tarreau87b09662015-04-03 00:22:06 +0200809/* This function initialises the Lua environment stored in the stream.
810 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100811 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200812 *
813 * This function is particular. it initialises a new Lua thread. If the
814 * initialisation fails (example: out of memory error), the lua function
815 * throws an error (longjmp).
816 *
817 * This function manipulates two Lua stack: the main and the thread. Only
818 * the main stack can fail. The thread is not manipulated. This function
819 * MUST NOT manipulate the created thread stack state, because is not
820 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100821 */
822int hlua_ctx_init(struct hlua *lua, struct task *task)
823{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200824 if (!SET_SAFE_LJMP(gL.T)) {
825 lua->Tref = LUA_REFNIL;
826 return 0;
827 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100828 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100829 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100830 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100831 lua->T = lua_newthread(gL.T);
832 if (!lua->T) {
833 lua->Tref = LUA_REFNIL;
Thierry FOURNIER0a976202017-07-12 11:18:00 +0200834 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100835 return 0;
836 }
837 hlua_sethlua(lua);
838 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
839 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200840 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100841 return 1;
842}
843
Willy Tarreau87b09662015-04-03 00:22:06 +0200844/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100845 * is destroyed. The destroy also the memory context. The struct "lua"
846 * is not freed.
847 */
848void hlua_ctx_destroy(struct hlua *lua)
849{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100850 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100851 return;
852
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100853 if (!lua->T)
854 goto end;
855
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100856 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +0200857 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100858
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200859 if (!SET_SAFE_LJMP(lua->T))
860 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100861 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200862 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200863
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200864 if (!SET_SAFE_LJMP(gL.T))
865 return;
866 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
867 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200868 /* Forces a garbage collecting process. If the Lua program is finished
869 * without error, we run the GC on the thread pointer. Its freed all
870 * the unused memory.
871 * If the thread is finnish with an error or is currently yielded,
872 * it seems that the GC applied on the thread doesn't clean anything,
873 * so e run the GC on the main thread.
874 * NOTE: maybe this action locks all the Lua threads untiml the en of
875 * the garbage collection.
876 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200877 if (lua->flags & HLUA_MUST_GC) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200878 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200879 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200880 lua_gc(gL.T, LUA_GCCOLLECT, 0);
881 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200882 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200883
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200884 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100885
886end:
Willy Tarreaubafbe012017-11-24 17:34:44 +0100887 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100888}
889
890/* This function is used to restore the Lua context when a coroutine
891 * fails. This function copy the common memory between old coroutine
892 * and the new coroutine. The old coroutine is destroyed, and its
893 * replaced by the new coroutine.
894 * If the flag "keep_msg" is set, the last entry of the old is assumed
895 * as string error message and it is copied in the new stack.
896 */
897static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
898{
899 lua_State *T;
900 int new_ref;
901
902 /* Renew the main LUA stack doesn't have sense. */
903 if (lua == &gL)
904 return 0;
905
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100906 /* New Lua coroutine. */
907 T = lua_newthread(gL.T);
908 if (!T)
909 return 0;
910
911 /* Copy last error message. */
912 if (keep_msg)
913 lua_xmove(lua->T, T, 1);
914
915 /* Copy data between the coroutines. */
916 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
917 lua_xmove(lua->T, T, 1);
918 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
919
920 /* Destroy old data. */
921 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
922
923 /* The thread is garbage collected by Lua. */
924 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
925
926 /* Fill the struct with the new coroutine values. */
927 lua->Mref = new_ref;
928 lua->T = T;
929 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
930
931 /* Set context. */
932 hlua_sethlua(lua);
933
934 return 1;
935}
936
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100937void hlua_hook(lua_State *L, lua_Debug *ar)
938{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100939 struct hlua *hlua = hlua_gethlua(L);
940
941 /* Lua cannot yield when its returning from a function,
942 * so, we can fix the interrupt hook to 1 instruction,
943 * expecting that the function is finnished.
944 */
945 if (lua_gethookmask(L) & LUA_MASKRET) {
946 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
947 return;
948 }
949
950 /* restore the interrupt condition. */
951 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
952
953 /* If we interrupt the Lua processing in yieldable state, we yield.
954 * If the state is not yieldable, trying yield causes an error.
955 */
956 if (lua_isyieldable(L))
957 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
958
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100959 /* If we cannot yield, update the clock and check the timeout. */
960 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200961 hlua->run_time += now_ms - hlua->start_time;
962 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100963 lua_pushfstring(L, "execution timeout");
964 WILL_LJMP(lua_error(L));
965 }
966
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200967 /* Update the start time. */
968 hlua->start_time = now_ms;
969
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100970 /* Try to interrupt the process at the end of the current
971 * unyieldable function.
972 */
973 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100974}
975
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100976/* This function start or resumes the Lua stack execution. If the flag
977 * "yield_allowed" if no set and the LUA stack execution returns a yield
978 * The function return an error.
979 *
980 * The function can returns 4 values:
981 * - HLUA_E_OK : The execution is terminated without any errors.
982 * - HLUA_E_AGAIN : The execution must continue at the next associated
983 * task wakeup.
984 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
985 * the top of the stack.
986 * - HLUA_E_ERR : An error has occured without error message.
987 *
988 * If an error occured, the stack is renewed and it is ready to run new
989 * LUA code.
990 */
991static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
992{
993 int ret;
994 const char *msg;
995
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200996 /* Initialise run time counter. */
997 if (!HLUA_IS_RUNNING(lua))
998 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100999
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001000 /* Lock the whole Lua execution. This lock must be before the
1001 * label "resume_execution".
1002 */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001003 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001004
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001005resume_execution:
1006
1007 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1008 * instructions. it is used for preventing infinite loops.
1009 */
1010 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1011
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001012 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001013 HLUA_SET_RUN(lua);
1014 HLUA_CLR_CTRLYIELD(lua);
1015 HLUA_CLR_WAKERESWR(lua);
1016 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001017
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001018 /* Update the start time. */
1019 lua->start_time = now_ms;
1020
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001021 /* Call the function. */
1022 ret = lua_resume(lua->T, gL.T, lua->nargs);
1023 switch (ret) {
1024
1025 case LUA_OK:
1026 ret = HLUA_E_OK;
1027 break;
1028
1029 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001030 /* Check if the execution timeout is expired. It it is the case, we
1031 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001032 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001033 tv_update_date(0, 1);
1034 lua->run_time += now_ms - lua->start_time;
1035 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001036 lua_settop(lua->T, 0); /* Empty the stack. */
1037 if (!lua_checkstack(lua->T, 1)) {
1038 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001039 break;
1040 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001041 lua_pushfstring(lua->T, "execution timeout");
1042 ret = HLUA_E_ERRMSG;
1043 break;
1044 }
1045 /* Process the forced yield. if the general yield is not allowed or
1046 * if no task were associated this the current Lua execution
1047 * coroutine, we resume the execution. Else we want to return in the
1048 * scheduler and we want to be waked up again, to continue the
1049 * current Lua execution. So we schedule our own task.
1050 */
1051 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001052 if (!yield_allowed || !lua->task)
1053 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001054 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001055 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001056 if (!yield_allowed) {
1057 lua_settop(lua->T, 0); /* Empty the stack. */
1058 if (!lua_checkstack(lua->T, 1)) {
1059 ret = HLUA_E_ERR;
1060 break;
1061 }
1062 lua_pushfstring(lua->T, "yield not allowed");
1063 ret = HLUA_E_ERRMSG;
1064 break;
1065 }
1066 ret = HLUA_E_AGAIN;
1067 break;
1068
1069 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001070
1071 /* Special exit case. The traditionnal exit is returned as an error
1072 * because the errors ares the only one mean to return immediately
1073 * from and lua execution.
1074 */
1075 if (lua->flags & HLUA_EXIT) {
1076 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001077 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001078 break;
1079 }
1080
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001081 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001082 if (!lua_checkstack(lua->T, 1)) {
1083 ret = HLUA_E_ERR;
1084 break;
1085 }
1086 msg = lua_tostring(lua->T, -1);
1087 lua_settop(lua->T, 0); /* Empty the stack. */
1088 lua_pop(lua->T, 1);
1089 if (msg)
1090 lua_pushfstring(lua->T, "runtime error: %s", msg);
1091 else
1092 lua_pushfstring(lua->T, "unknown runtime error");
1093 ret = HLUA_E_ERRMSG;
1094 break;
1095
1096 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001097 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001098 lua_settop(lua->T, 0); /* Empty the stack. */
1099 if (!lua_checkstack(lua->T, 1)) {
1100 ret = HLUA_E_ERR;
1101 break;
1102 }
1103 lua_pushfstring(lua->T, "out of memory error");
1104 ret = HLUA_E_ERRMSG;
1105 break;
1106
1107 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001108 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001109 if (!lua_checkstack(lua->T, 1)) {
1110 ret = HLUA_E_ERR;
1111 break;
1112 }
1113 msg = lua_tostring(lua->T, -1);
1114 lua_settop(lua->T, 0); /* Empty the stack. */
1115 lua_pop(lua->T, 1);
1116 if (msg)
1117 lua_pushfstring(lua->T, "message handler error: %s", msg);
1118 else
1119 lua_pushfstring(lua->T, "message handler error");
1120 ret = HLUA_E_ERRMSG;
1121 break;
1122
1123 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001124 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001125 lua_settop(lua->T, 0); /* Empty the stack. */
1126 if (!lua_checkstack(lua->T, 1)) {
1127 ret = HLUA_E_ERR;
1128 break;
1129 }
1130 lua_pushfstring(lua->T, "unknonwn error");
1131 ret = HLUA_E_ERRMSG;
1132 break;
1133 }
1134
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001135 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001136 if (lua->flags & HLUA_MUST_GC &&
1137 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001138 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1139
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001140 switch (ret) {
1141 case HLUA_E_AGAIN:
1142 break;
1143
1144 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001145 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001146 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001147 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001148 break;
1149
1150 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001151 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001152 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001153 hlua_ctx_renew(lua, 0);
1154 break;
1155
1156 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001157 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001158 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001159 break;
1160 }
1161
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001162 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001163 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001164
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001165 return ret;
1166}
1167
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001168/* This function exit the current code. */
1169__LJMP static int hlua_done(lua_State *L)
1170{
1171 struct hlua *hlua = hlua_gethlua(L);
1172
1173 hlua->flags |= HLUA_EXIT;
1174 WILL_LJMP(lua_error(L));
1175
1176 return 0;
1177}
1178
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001179/* This function is an LUA binding. It provides a function
1180 * for deleting ACL from a referenced ACL file.
1181 */
1182__LJMP static int hlua_del_acl(lua_State *L)
1183{
1184 const char *name;
1185 const char *key;
1186 struct pat_ref *ref;
1187
1188 MAY_LJMP(check_args(L, 2, "del_acl"));
1189
1190 name = MAY_LJMP(luaL_checkstring(L, 1));
1191 key = MAY_LJMP(luaL_checkstring(L, 2));
1192
1193 ref = pat_ref_lookup(name);
1194 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001195 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001196
1197 pat_ref_delete(ref, key);
1198 return 0;
1199}
1200
1201/* This function is an LUA binding. It provides a function
1202 * for deleting map entry from a referenced map file.
1203 */
1204static int hlua_del_map(lua_State *L)
1205{
1206 const char *name;
1207 const char *key;
1208 struct pat_ref *ref;
1209
1210 MAY_LJMP(check_args(L, 2, "del_map"));
1211
1212 name = MAY_LJMP(luaL_checkstring(L, 1));
1213 key = MAY_LJMP(luaL_checkstring(L, 2));
1214
1215 ref = pat_ref_lookup(name);
1216 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001217 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001218
1219 pat_ref_delete(ref, key);
1220 return 0;
1221}
1222
1223/* This function is an LUA binding. It provides a function
1224 * for adding ACL pattern from a referenced ACL file.
1225 */
1226static int hlua_add_acl(lua_State *L)
1227{
1228 const char *name;
1229 const char *key;
1230 struct pat_ref *ref;
1231
1232 MAY_LJMP(check_args(L, 2, "add_acl"));
1233
1234 name = MAY_LJMP(luaL_checkstring(L, 1));
1235 key = MAY_LJMP(luaL_checkstring(L, 2));
1236
1237 ref = pat_ref_lookup(name);
1238 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001239 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001240
1241 if (pat_ref_find_elt(ref, key) == NULL)
1242 pat_ref_add(ref, key, NULL, NULL);
1243 return 0;
1244}
1245
1246/* This function is an LUA binding. It provides a function
1247 * for setting map pattern and sample from a referenced map
1248 * file.
1249 */
1250static int hlua_set_map(lua_State *L)
1251{
1252 const char *name;
1253 const char *key;
1254 const char *value;
1255 struct pat_ref *ref;
1256
1257 MAY_LJMP(check_args(L, 3, "set_map"));
1258
1259 name = MAY_LJMP(luaL_checkstring(L, 1));
1260 key = MAY_LJMP(luaL_checkstring(L, 2));
1261 value = MAY_LJMP(luaL_checkstring(L, 3));
1262
1263 ref = pat_ref_lookup(name);
1264 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001265 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001266
1267 if (pat_ref_find_elt(ref, key) != NULL)
1268 pat_ref_set(ref, key, value, NULL);
1269 else
1270 pat_ref_add(ref, key, value, NULL);
1271 return 0;
1272}
1273
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001274/* A class is a lot of memory that contain data. This data can be a table,
1275 * an integer or user data. This data is associated with a metatable. This
1276 * metatable have an original version registred in the global context with
1277 * the name of the object (_G[<name>] = <metable> ).
1278 *
1279 * A metable is a table that modify the standard behavior of a standard
1280 * access to the associated data. The entries of this new metatable are
1281 * defined as is:
1282 *
1283 * http://lua-users.org/wiki/MetatableEvents
1284 *
1285 * __index
1286 *
1287 * we access an absent field in a table, the result is nil. This is
1288 * true, but it is not the whole truth. Actually, such access triggers
1289 * the interpreter to look for an __index metamethod: If there is no
1290 * such method, as usually happens, then the access results in nil;
1291 * otherwise, the metamethod will provide the result.
1292 *
1293 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1294 * the key does not appear in the table, but the metatable has an __index
1295 * property:
1296 *
1297 * - if the value is a function, the function is called, passing in the
1298 * table and the key; the return value of that function is returned as
1299 * the result.
1300 *
1301 * - if the value is another table, the value of the key in that table is
1302 * asked for and returned (and if it doesn't exist in that table, but that
1303 * table's metatable has an __index property, then it continues on up)
1304 *
1305 * - Use "rawget(myTable,key)" to skip this metamethod.
1306 *
1307 * http://www.lua.org/pil/13.4.1.html
1308 *
1309 * __newindex
1310 *
1311 * Like __index, but control property assignment.
1312 *
1313 * __mode - Control weak references. A string value with one or both
1314 * of the characters 'k' and 'v' which specifies that the the
1315 * keys and/or values in the table are weak references.
1316 *
1317 * __call - Treat a table like a function. When a table is followed by
1318 * parenthesis such as "myTable( 'foo' )" and the metatable has
1319 * a __call key pointing to a function, that function is invoked
1320 * (passing any specified arguments) and the return value is
1321 * returned.
1322 *
1323 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1324 * called, if the metatable for myTable has a __metatable
1325 * key, the value of that key is returned instead of the
1326 * actual metatable.
1327 *
1328 * __tostring - Control string representation. When the builtin
1329 * "tostring( myTable )" function is called, if the metatable
1330 * for myTable has a __tostring property set to a function,
1331 * that function is invoked (passing myTable to it) and the
1332 * return value is used as the string representation.
1333 *
1334 * __len - Control table length. When the table length is requested using
1335 * the length operator ( '#' ), if the metatable for myTable has
1336 * a __len key pointing to a function, that function is invoked
1337 * (passing myTable to it) and the return value used as the value
1338 * of "#myTable".
1339 *
1340 * __gc - Userdata finalizer code. When userdata is set to be garbage
1341 * collected, if the metatable has a __gc field pointing to a
1342 * function, that function is first invoked, passing the userdata
1343 * to it. The __gc metamethod is not called for tables.
1344 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1345 *
1346 * Special metamethods for redefining standard operators:
1347 * http://www.lua.org/pil/13.1.html
1348 *
1349 * __add "+"
1350 * __sub "-"
1351 * __mul "*"
1352 * __div "/"
1353 * __unm "!"
1354 * __pow "^"
1355 * __concat ".."
1356 *
1357 * Special methods for redfining standar relations
1358 * http://www.lua.org/pil/13.2.html
1359 *
1360 * __eq "=="
1361 * __lt "<"
1362 * __le "<="
1363 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001364
1365/*
1366 *
1367 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001368 * Class Map
1369 *
1370 *
1371 */
1372
1373/* Returns a struct hlua_map if the stack entry "ud" is
1374 * a class session, otherwise it throws an error.
1375 */
1376__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1377{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001378 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001379}
1380
1381/* This function is the map constructor. It don't need
1382 * the class Map object. It creates and return a new Map
1383 * object. It must be called only during "body" or "init"
1384 * context because it process some filesystem accesses.
1385 */
1386__LJMP static int hlua_map_new(struct lua_State *L)
1387{
1388 const char *fn;
1389 int match = PAT_MATCH_STR;
1390 struct sample_conv conv;
1391 const char *file = "";
1392 int line = 0;
1393 lua_Debug ar;
1394 char *err = NULL;
1395 struct arg args[2];
1396
1397 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1398 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1399
1400 fn = MAY_LJMP(luaL_checkstring(L, 1));
1401
1402 if (lua_gettop(L) >= 2) {
1403 match = MAY_LJMP(luaL_checkinteger(L, 2));
1404 if (match < 0 || match >= PAT_MATCH_NUM)
1405 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1406 }
1407
1408 /* Get Lua filename and line number. */
1409 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1410 lua_getinfo(L, "Sl", &ar); /* get info about it */
1411 if (ar.currentline > 0) { /* is there info? */
1412 file = ar.short_src;
1413 line = ar.currentline;
1414 }
1415 }
1416
1417 /* fill fake sample_conv struct. */
1418 conv.kw = ""; /* unused. */
1419 conv.process = NULL; /* unused. */
1420 conv.arg_mask = 0; /* unused. */
1421 conv.val_args = NULL; /* unused. */
1422 conv.out_type = SMP_T_STR;
1423 conv.private = (void *)(long)match;
1424 switch (match) {
1425 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1426 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1427 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1428 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1429 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1430 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1431 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001432 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001433 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1434 default:
1435 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1436 }
1437
1438 /* fill fake args. */
1439 args[0].type = ARGT_STR;
1440 args[0].data.str.str = (char *)fn;
1441 args[1].type = ARGT_STOP;
1442
1443 /* load the map. */
1444 if (!sample_load_map(args, &conv, file, line, &err)) {
1445 /* error case: we cant use luaL_error because we must
1446 * free the err variable.
1447 */
1448 luaL_where(L, 1);
1449 lua_pushfstring(L, "'new': %s.", err);
1450 lua_concat(L, 2);
1451 free(err);
1452 WILL_LJMP(lua_error(L));
1453 }
1454
1455 /* create the lua object. */
1456 lua_newtable(L);
1457 lua_pushlightuserdata(L, args[0].data.map);
1458 lua_rawseti(L, -2, 0);
1459
1460 /* Pop a class Map metatable and affect it to the userdata. */
1461 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1462 lua_setmetatable(L, -2);
1463
1464
1465 return 1;
1466}
1467
1468__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1469{
1470 struct map_descriptor *desc;
1471 struct pattern *pat;
1472 struct sample smp;
1473
1474 MAY_LJMP(check_args(L, 2, "lookup"));
1475 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001476 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001477 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001478 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001479 }
1480 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001481 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001482 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001483 smp.data.u.str.str = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.len));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001484 }
1485
1486 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001487 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001488 if (str)
1489 lua_pushstring(L, "");
1490 else
1491 lua_pushnil(L);
1492 return 1;
1493 }
1494
1495 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001496 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001497 return 1;
1498}
1499
1500__LJMP static int hlua_map_lookup(struct lua_State *L)
1501{
1502 return _hlua_map_lookup(L, 0);
1503}
1504
1505__LJMP static int hlua_map_slookup(struct lua_State *L)
1506{
1507 return _hlua_map_lookup(L, 1);
1508}
1509
1510/*
1511 *
1512 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001513 * Class Socket
1514 *
1515 *
1516 */
1517
1518__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1519{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001520 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001521}
1522
1523/* This function is the handler called for each I/O on the established
1524 * connection. It is used for notify space avalaible to send or data
1525 * received.
1526 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001527static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001528{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001529 struct stream_interface *si = appctx->owner;
Olivier Houchard9aaf7782017-09-13 18:30:23 +02001530 struct connection *c = cs_conn(objt_cs(si_opposite(si)->end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001531
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001532 if (appctx->ctx.hlua_cosocket.die) {
1533 si_shutw(si);
1534 si_shutr(si);
1535 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001536 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1537 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001538 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1539 }
1540
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001541 /* If the connection object is not avalaible, close all the
1542 * streams and wakeup everithing waiting for.
1543 */
1544 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001545 si_shutw(si);
1546 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001547 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001548 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1549 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001550 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001551 }
1552
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001553 /* If we cant write, wakeup the pending write signals. */
1554 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001555 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001556
1557 /* If we cant read, wakeup the pending read signals. */
1558 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001559 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001560
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001561 /* if the connection is not estabkished, inform the stream that we want
1562 * to be notified whenever the connection completes.
1563 */
1564 if (!(c->flags & CO_FL_CONNECTED)) {
1565 si_applet_cant_get(si);
1566 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001567 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001568 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001569
1570 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001571 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001572
1573 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001574 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001575 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001576
1577 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001578 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001579 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001580}
1581
Willy Tarreau87b09662015-04-03 00:22:06 +02001582/* This function is called when the "struct stream" is destroyed.
1583 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001584 * Wake all the pending signals.
1585 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001586static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001587{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001588 struct xref *peer;
1589
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001590 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001591 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1592 if (peer)
1593 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001594
1595 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001596 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1597 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001598}
1599
1600/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001601 * uses this object. If the stream does not exists, just quit.
1602 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001603 * pending signal can rest in the read and write lists. destroy
1604 * it.
1605 */
1606__LJMP static int hlua_socket_gc(lua_State *L)
1607{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001608 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001609 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001610 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001611
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001612 MAY_LJMP(check_args(L, 1, "__gc"));
1613
1614 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001615 peer = xref_get_peer_and_lock(&socket->xref);
1616 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001617 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001618 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001619
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001620 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001621 appctx->ctx.hlua_cosocket.die = 1;
1622 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001623
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001624 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001625 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001626 return 0;
1627}
1628
1629/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001630 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001631 */
1632__LJMP static int hlua_socket_close(lua_State *L)
1633{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001634 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001635 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001636 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001637
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001638 MAY_LJMP(check_args(L, 1, "close"));
1639
1640 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001641
1642 /* Check if we run on the same thread than the xreator thread.
1643 * We cannot access to the socket if the thread is different.
1644 */
1645 if (socket->tid != tid)
1646 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1647
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001648 peer = xref_get_peer_and_lock(&socket->xref);
1649 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001650 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001651 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001652
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001653 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001654 appctx->ctx.hlua_cosocket.die = 1;
1655 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001656
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001657 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001658 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001659 return 0;
1660}
1661
1662/* This Lua function assumes that the stack contain three parameters.
1663 * 1 - USERDATA containing a struct socket
1664 * 2 - INTEGER with values of the macro defined below
1665 * If the integer is -1, we must read at most one line.
1666 * If the integer is -2, we ust read all the data until the
1667 * end of the stream.
1668 * If the integer is positive value, we must read a number of
1669 * bytes corresponding to this value.
1670 */
1671#define HLSR_READ_LINE (-1)
1672#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001673__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001674{
1675 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1676 int wanted = lua_tointeger(L, 2);
1677 struct hlua *hlua = hlua_gethlua(L);
1678 struct appctx *appctx;
1679 int len;
1680 int nblk;
1681 char *blk1;
1682 int len1;
1683 char *blk2;
1684 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001685 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001686 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001687 struct stream_interface *si;
1688 struct stream *s;
1689 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001690
1691 /* Check if this lua stack is schedulable. */
1692 if (!hlua || !hlua->task)
1693 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1694 "'frontend', 'backend' or 'task'"));
1695
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001696 /* Check if we run on the same thread than the xreator thread.
1697 * We cannot access to the socket if the thread is different.
1698 */
1699 if (socket->tid != tid)
1700 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1701
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001702 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001703 peer = xref_get_peer_and_lock(&socket->xref);
1704 if (!peer)
1705 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001706 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1707 si = appctx->owner;
1708 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001709
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001710 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001711 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001712 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001713 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001714 if (nblk < 0) /* Connection close. */
1715 goto connection_closed;
1716 if (nblk == 0) /* No data avalaible. */
1717 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001718
1719 /* remove final \r\n. */
1720 if (nblk == 1) {
1721 if (blk1[len1-1] == '\n') {
1722 len1--;
1723 skip_at_end++;
1724 if (blk1[len1-1] == '\r') {
1725 len1--;
1726 skip_at_end++;
1727 }
1728 }
1729 }
1730 else {
1731 if (blk2[len2-1] == '\n') {
1732 len2--;
1733 skip_at_end++;
1734 if (blk2[len2-1] == '\r') {
1735 len2--;
1736 skip_at_end++;
1737 }
1738 }
1739 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001740 }
1741
1742 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001743 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001744 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001745 if (nblk < 0) /* Connection close. */
1746 goto connection_closed;
1747 if (nblk == 0) /* No data avalaible. */
1748 goto connection_empty;
1749 }
1750
1751 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001752 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001753 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001754 if (nblk < 0) /* Connection close. */
1755 goto connection_closed;
1756 if (nblk == 0) /* No data avalaible. */
1757 goto connection_empty;
1758
1759 if (len1 > wanted) {
1760 nblk = 1;
1761 len1 = wanted;
1762 } if (nblk == 2 && len1 + len2 > wanted)
1763 len2 = wanted - len1;
1764 }
1765
1766 len = len1;
1767
1768 luaL_addlstring(&socket->b, blk1, len1);
1769 if (nblk == 2) {
1770 len += len2;
1771 luaL_addlstring(&socket->b, blk2, len2);
1772 }
1773
1774 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001775 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001776
1777 /* Don't wait anything. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001778 stream_int_notify(&s->si[0]);
1779 stream_int_update_applet(&s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001780
1781 /* If the pattern reclaim to read all the data
1782 * in the connection, got out.
1783 */
1784 if (wanted == HLSR_READ_ALL)
1785 goto connection_empty;
1786 else if (wanted >= 0 && len < wanted)
1787 goto connection_empty;
1788
1789 /* Return result. */
1790 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001791 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001792 return 1;
1793
1794connection_closed:
1795
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001796 xref_unlock(&socket->xref, peer);
1797
1798no_peer:
1799
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001800 /* If the buffer containds data. */
1801 if (socket->b.n > 0) {
1802 luaL_pushresult(&socket->b);
1803 return 1;
1804 }
1805 lua_pushnil(L);
1806 lua_pushstring(L, "connection closed.");
1807 return 2;
1808
1809connection_empty:
1810
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001811 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001812 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1813 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001814 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001815 }
1816 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001817 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001818 return 0;
1819}
1820
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001821/* This Lua function gets two parameters. The first one can be string
1822 * or a number. If the string is "*l", the user requires one line. If
1823 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001824 * If the value is a number, the user require a number of bytes equal
1825 * to the value. The default value is "*l" (a line).
1826 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001827 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001828 * integer takes this values:
1829 * -1 : read a line
1830 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001831 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001832 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001833 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001834 * concatenated with the read data.
1835 */
1836__LJMP static int hlua_socket_receive(struct lua_State *L)
1837{
1838 int wanted = HLSR_READ_LINE;
1839 const char *pattern;
1840 int type;
1841 char *error;
1842 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001843 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001844
1845 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1846 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1847
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001848 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001849
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001850 /* Check if we run on the same thread than the xreator thread.
1851 * We cannot access to the socket if the thread is different.
1852 */
1853 if (socket->tid != tid)
1854 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1855
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001856 /* check for pattern. */
1857 if (lua_gettop(L) >= 2) {
1858 type = lua_type(L, 2);
1859 if (type == LUA_TSTRING) {
1860 pattern = lua_tostring(L, 2);
1861 if (strcmp(pattern, "*a") == 0)
1862 wanted = HLSR_READ_ALL;
1863 else if (strcmp(pattern, "*l") == 0)
1864 wanted = HLSR_READ_LINE;
1865 else {
1866 wanted = strtoll(pattern, &error, 10);
1867 if (*error != '\0')
1868 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1869 }
1870 }
1871 else if (type == LUA_TNUMBER) {
1872 wanted = lua_tointeger(L, 2);
1873 if (wanted < 0)
1874 WILL_LJMP(luaL_error(L, "Unsupported size."));
1875 }
1876 }
1877
1878 /* Set pattern. */
1879 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01001880
1881 /* Check if we would replace the top by itself. */
1882 if (lua_gettop(L) != 2)
1883 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001884
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001885 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001886 luaL_buffinit(L, &socket->b);
1887
1888 /* Check prefix. */
1889 if (lua_gettop(L) >= 3) {
1890 if (lua_type(L, 3) != LUA_TSTRING)
1891 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1892 pattern = lua_tolstring(L, 3, &len);
1893 luaL_addlstring(&socket->b, pattern, len);
1894 }
1895
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001896 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001897}
1898
1899/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08001900 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001901 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001902static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001903{
1904 struct hlua_socket *socket;
1905 struct hlua *hlua = hlua_gethlua(L);
1906 struct appctx *appctx;
1907 size_t buf_len;
1908 const char *buf;
1909 int len;
1910 int send_len;
1911 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001912 struct xref *peer;
1913 struct stream_interface *si;
1914 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001915
1916 /* Check if this lua stack is schedulable. */
1917 if (!hlua || !hlua->task)
1918 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1919 "'frontend', 'backend' or 'task'"));
1920
1921 /* Get object */
1922 socket = MAY_LJMP(hlua_checksocket(L, 1));
1923 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001924 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001925
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001926 /* Check if we run on the same thread than the xreator thread.
1927 * We cannot access to the socket if the thread is different.
1928 */
1929 if (socket->tid != tid)
1930 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1931
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001932 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001933 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001934 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001935 lua_pushinteger(L, -1);
1936 return 1;
1937 }
1938 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1939 si = appctx->owner;
1940 s = si_strm(si);
1941
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001942 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001943 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001944 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001945 lua_pushinteger(L, -1);
1946 return 1;
1947 }
1948
1949 /* Update the input buffer data. */
1950 buf += sent;
1951 send_len = buf_len - sent;
1952
1953 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001954 if (sent >= buf_len) {
1955 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001956 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001957 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001958
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001959 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1960 * the request buffer if its not required.
1961 */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001962 if (s->req.buf->size == 0) {
Christopher Faulet33834b12016-12-19 09:29:06 +01001963 appctx = hlua->task->context;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001964 if (!channel_alloc_buffer(&s->req, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01001965 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001966 }
1967
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001968 /* Check for avalaible space. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001969 len = buffer_total_space(s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01001970 if (len <= 0) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001971 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001972 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
1973 xref_unlock(&socket->xref, peer);
Christopher Faulet33834b12016-12-19 09:29:06 +01001974 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001975 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001976 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01001977 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001978
1979 /* send data */
1980 if (len < send_len)
1981 send_len = len;
Willy Tarreau06d80a92017-10-19 14:32:15 +02001982 len = ci_putblk(&s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001983
1984 /* "Not enough space" (-1), "Buffer too little to contain
1985 * the data" (-2) are not expected because the available length
1986 * is tested.
1987 * Other unknown error are also not expected.
1988 */
1989 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001990 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001991 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001992
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001993 MAY_LJMP(hlua_socket_close(L));
1994 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001995 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001996 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001997 return 1;
1998 }
1999
2000 /* update buffers. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002001 stream_int_notify(&s->si[0]);
2002 stream_int_update_applet(&s->si[0]);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002003
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002004 s->req.rex = TICK_ETERNITY;
2005 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002006
2007 /* Update length sent. */
2008 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002009 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002010
2011 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002012 if (sent + len >= buf_len) {
2013 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002014 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002015 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002016
2017hlua_socket_write_yield_return:
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002018 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002019 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002020 return 0;
2021}
2022
2023/* This function initiate the send of data. It just check the input
2024 * parameters and push an integer in the Lua stack that contain the
2025 * amount of data writed in the buffer. This is used by the function
2026 * "hlua_socket_write_yield" that can yield.
2027 *
2028 * The Lua function gets between 3 and 4 parameters. The first one is
2029 * the associated object. The second is a string buffer. The third is
2030 * a facultative integer that represents where is the buffer position
2031 * of the start of the data that can send. The first byte is the
2032 * position "1". The default value is "1". The fourth argument is a
2033 * facultative integer that represents where is the buffer position
2034 * of the end of the data that can send. The default is the last byte.
2035 */
2036static int hlua_socket_send(struct lua_State *L)
2037{
2038 int i;
2039 int j;
2040 const char *buf;
2041 size_t buf_len;
2042
2043 /* Check number of arguments. */
2044 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2045 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2046
2047 /* Get the string. */
2048 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2049
2050 /* Get and check j. */
2051 if (lua_gettop(L) == 4) {
2052 j = MAY_LJMP(luaL_checkinteger(L, 4));
2053 if (j < 0)
2054 j = buf_len + j + 1;
2055 if (j > buf_len)
2056 j = buf_len + 1;
2057 lua_pop(L, 1);
2058 }
2059 else
2060 j = buf_len;
2061
2062 /* Get and check i. */
2063 if (lua_gettop(L) == 3) {
2064 i = MAY_LJMP(luaL_checkinteger(L, 3));
2065 if (i < 0)
2066 i = buf_len + i + 1;
2067 if (i > buf_len)
2068 i = buf_len + 1;
2069 lua_pop(L, 1);
2070 } else
2071 i = 1;
2072
2073 /* Check bth i and j. */
2074 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002075 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002076 return 1;
2077 }
2078 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002079 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002080 return 1;
2081 }
2082 if (i == 0)
2083 i = 1;
2084 if (j == 0)
2085 j = 1;
2086
2087 /* Pop the string. */
2088 lua_pop(L, 1);
2089
2090 /* Update the buffer length. */
2091 buf += i - 1;
2092 buf_len = j - i + 1;
2093 lua_pushlstring(L, buf, buf_len);
2094
2095 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002096 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002097
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002098 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002099}
2100
Willy Tarreau22b0a682015-06-17 19:43:49 +02002101#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002102__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2103{
2104 static char buffer[SOCKET_INFO_MAX_LEN];
2105 int ret;
2106 int len;
2107 char *p;
2108
2109 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2110 if (ret <= 0) {
2111 lua_pushnil(L);
2112 return 1;
2113 }
2114
2115 if (ret == AF_UNIX) {
2116 lua_pushstring(L, buffer+1);
2117 return 1;
2118 }
2119 else if (ret == AF_INET6) {
2120 buffer[0] = '[';
2121 len = strlen(buffer);
2122 buffer[len] = ']';
2123 len++;
2124 buffer[len] = ':';
2125 len++;
2126 p = buffer;
2127 }
2128 else if (ret == AF_INET) {
2129 p = buffer + 1;
2130 len = strlen(p);
2131 p[len] = ':';
2132 len++;
2133 }
2134 else {
2135 lua_pushnil(L);
2136 return 1;
2137 }
2138
2139 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2140 lua_pushnil(L);
2141 return 1;
2142 }
2143
2144 lua_pushstring(L, p);
2145 return 1;
2146}
2147
2148/* Returns information about the peer of the connection. */
2149__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2150{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002151 struct hlua_socket *socket;
2152 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002153 struct xref *peer;
2154 struct appctx *appctx;
2155 struct stream_interface *si;
2156 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002157 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002158
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002159 MAY_LJMP(check_args(L, 1, "getpeername"));
2160
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002161 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002162
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002163 /* Check if we run on the same thread than the xreator thread.
2164 * We cannot access to the socket if the thread is different.
2165 */
2166 if (socket->tid != tid)
2167 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2168
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002169 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002170 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002171 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002172 lua_pushnil(L);
2173 return 1;
2174 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002175 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2176 si = appctx->owner;
2177 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002178
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002179 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002180 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002181 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002182 lua_pushnil(L);
2183 return 1;
2184 }
2185
Willy Tarreaua71f6422016-11-16 17:00:14 +01002186 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002187 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002188 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002189 lua_pushnil(L);
2190 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002191 }
2192
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002193 ret = MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2194 xref_unlock(&socket->xref, peer);
2195 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002196}
2197
2198/* Returns information about my connection side. */
2199static int hlua_socket_getsockname(struct lua_State *L)
2200{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002201 struct hlua_socket *socket;
2202 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002203 struct appctx *appctx;
2204 struct xref *peer;
2205 struct stream_interface *si;
2206 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002207 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002208
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002209 MAY_LJMP(check_args(L, 1, "getsockname"));
2210
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002211 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002212
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002213 /* Check if we run on the same thread than the xreator thread.
2214 * We cannot access to the socket if the thread is different.
2215 */
2216 if (socket->tid != tid)
2217 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2218
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002219 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002220 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002221 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002222 lua_pushnil(L);
2223 return 1;
2224 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002225 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2226 si = appctx->owner;
2227 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002228
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002229 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002230 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002231 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002232 lua_pushnil(L);
2233 return 1;
2234 }
2235
Willy Tarreaua71f6422016-11-16 17:00:14 +01002236 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002237 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002238 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002239 lua_pushnil(L);
2240 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002241 }
2242
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002243 ret = hlua_socket_info(L, &conn->addr.from);
2244 xref_unlock(&socket->xref, peer);
2245 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002246}
2247
2248/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002249static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002250 .obj_type = OBJ_TYPE_APPLET,
2251 .name = "<LUA_TCP>",
2252 .fct = hlua_socket_handler,
2253 .release = hlua_socket_release,
2254};
2255
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002256__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002257{
2258 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2259 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002260 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002261 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002262 struct stream_interface *si;
2263 struct stream *s;
2264
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002265 /* Check if we run on the same thread than the xreator thread.
2266 * We cannot access to the socket if the thread is different.
2267 */
2268 if (socket->tid != tid)
2269 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2270
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002271 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002272 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002273 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002274 lua_pushnil(L);
2275 lua_pushstring(L, "Can't connect");
2276 return 2;
2277 }
2278 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2279 si = appctx->owner;
2280 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002281
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002282 /* Check if we run on the same thread than the xreator thread.
2283 * We cannot access to the socket if the thread is different.
2284 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002285 if (socket->tid != tid) {
2286 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002287 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002288 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002289
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002290 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002291 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002292 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002293 lua_pushnil(L);
2294 lua_pushstring(L, "Can't connect");
2295 return 2;
2296 }
2297
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002298 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002299
2300 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002301 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002302 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002303 lua_pushinteger(L, 1);
2304 return 1;
2305 }
2306
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002307 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2308 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002309 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002310 }
2311 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002312 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313 return 0;
2314}
2315
2316/* This function fail or initite the connection. */
2317__LJMP static int hlua_socket_connect(struct lua_State *L)
2318{
2319 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002320 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321 const char *ip;
2322 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002323 struct hlua *hlua;
2324 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002325 int low, high;
2326 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002327 struct xref *peer;
2328 struct stream_interface *si;
2329 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002330
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002331 if (lua_gettop(L) < 2)
2332 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002333
2334 /* Get args. */
2335 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002336
2337 /* Check if we run on the same thread than the xreator thread.
2338 * We cannot access to the socket if the thread is different.
2339 */
2340 if (socket->tid != tid)
2341 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2342
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002343 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002344 if (lua_gettop(L) >= 3) {
2345 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002346 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002347
Tim Duesterhus6edab862018-01-06 19:04:45 +01002348 /* Force the ip to end with a colon, to support IPv6 addresses
2349 * that are not enclosed within square brackets.
2350 */
2351 if (port > 0) {
2352 luaL_buffinit(L, &b);
2353 luaL_addstring(&b, ip);
2354 luaL_addchar(&b, ':');
2355 luaL_pushresult(&b);
2356 ip = lua_tolstring(L, lua_gettop(L), NULL);
2357 }
2358 }
2359
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002360 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002361 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002362 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002363 lua_pushnil(L);
2364 return 1;
2365 }
2366 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2367 si = appctx->owner;
2368 s = si_strm(si);
2369
2370 /* Initialise connection. */
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002371 conn = cs_conn(si_alloc_cs(&s->si[1], NULL));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002372 if (!conn) {
2373 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002374 WILL_LJMP(luaL_error(L, "connect: internal error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002375 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002376
Willy Tarreau3adac082015-09-26 17:51:09 +02002377 /* needed for the connection not to be closed */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002378 conn->target = s->target;
Willy Tarreau3adac082015-09-26 17:51:09 +02002379
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002380 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002381 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002382 if (!addr) {
2383 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002384 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002385 }
2386 if (low != high) {
2387 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002388 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002389 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002390 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002391
2392 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002393 if (low == 0) {
2394 if (conn->addr.to.ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002395 if (port == -1) {
2396 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002397 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002398 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002399 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2400 } else if (conn->addr.to.ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002401 if (port == -1) {
2402 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002403 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002404 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002405 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2406 }
2407 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002408
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002409 hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002410 appctx = objt_appctx(s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002411
2412 /* inform the stream that we want to be notified whenever the
2413 * connection completes.
2414 */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002415 si_applet_cant_get(&s->si[0]);
2416 si_applet_cant_put(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002417 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002418
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002419 hlua->flags |= HLUA_MUST_GC;
2420
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002421 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2422 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002423 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002424 }
2425 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002426 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002427
2428 return 0;
2429}
2430
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002431#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002432__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2433{
2434 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002435 struct xref *peer;
2436 struct appctx *appctx;
2437 struct stream_interface *si;
2438 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002439
2440 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2441 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002442
2443 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002444 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002445 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002446 lua_pushnil(L);
2447 return 1;
2448 }
2449 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2450 si = appctx->owner;
2451 s = si_strm(si);
2452
2453 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002454 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002455 return MAY_LJMP(hlua_socket_connect(L));
2456}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002457#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002458
2459__LJMP static int hlua_socket_setoption(struct lua_State *L)
2460{
2461 return 0;
2462}
2463
2464__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2465{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002466 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002467 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002468 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002469 struct xref *peer;
2470 struct appctx *appctx;
2471 struct stream_interface *si;
2472 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002473
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002474 MAY_LJMP(check_args(L, 2, "settimeout"));
2475
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002476 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002477
2478 /* round up for inputs that are fractions and convert to millis */
2479 dtmout = (0.5 + MAY_LJMP(luaL_checknumber(L, 2))) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002480
Thierry Fournier17a921b2018-03-08 09:59:02 +01002481 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002482 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002483 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2484
Mark Lakes56cc1252018-03-27 09:48:06 +02002485 if (dtmout > INT_MAX) /* overflow check */
2486 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d", INT_MAX));
2487
2488 tmout = MS_TO_TICKS((int)dtmout);
2489
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002490 /* Check if we run on the same thread than the xreator thread.
2491 * We cannot access to the socket if the thread is different.
2492 */
2493 if (socket->tid != tid)
2494 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2495
Mark Lakes56cc1252018-03-27 09:48:06 +02002496 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002497 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002498 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002499 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2500 WILL_LJMP(lua_error(L));
2501 return 0;
2502 }
2503 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2504 si = appctx->owner;
2505 s = si_strm(si);
2506
2507 s->req.rto = tmout;
2508 s->req.wto = tmout;
2509 s->res.rto = tmout;
2510 s->res.wto = tmout;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002511 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002512
Thierry Fourniere9636f12018-03-08 09:54:32 +01002513 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002514 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002515}
2516
2517__LJMP static int hlua_socket_new(lua_State *L)
2518{
2519 struct hlua_socket *socket;
2520 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002521 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002522 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002523
2524 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002525 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002526 hlua_pusherror(L, "socket: full stack");
2527 goto out_fail_conf;
2528 }
2529
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002530 /* Create the object: obj[0] = userdata. */
2531 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002532 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002533 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002534 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002535 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002536
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002537 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002538 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002539 hlua_pusherror(L, "socket: uninitialized pools.");
2540 goto out_fail_conf;
2541 }
2542
Willy Tarreau87b09662015-04-03 00:22:06 +02002543 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002544 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2545 lua_setmetatable(L, -2);
2546
Willy Tarreaud420a972015-04-06 00:39:18 +02002547 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002548 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002549 if (!appctx) {
2550 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002551 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002552 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002553
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002554 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002555 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002556 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2557 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002558
Willy Tarreaud420a972015-04-06 00:39:18 +02002559 /* Now create a session, task and stream for this applet */
2560 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2561 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002562 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002563 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002564 }
2565
Willy Tarreau87787ac2017-08-28 16:22:54 +02002566 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002567 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002568 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002569 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002570 }
2571
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002572 /* Initialise cross reference between stream and Lua socket object. */
2573 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002574
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002575 /* Configure "right" stream interface. this "si" is used to connect
2576 * and retrieve data from the server. The connection is initialized
2577 * with the "struct server".
2578 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002579 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002580
2581 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002582 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2583 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002584
Willy Tarreau87787ac2017-08-28 16:22:54 +02002585 task_wakeup(strm->task, TASK_WOKEN_INIT);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002586 /* Return yield waiting for connection. */
2587 return 1;
2588
Willy Tarreaud420a972015-04-06 00:39:18 +02002589 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002590 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002591 out_fail_sess:
2592 appctx_free(appctx);
2593 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002594 WILL_LJMP(lua_error(L));
2595 return 0;
2596}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002597
2598/*
2599 *
2600 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002601 * Class Channel
2602 *
2603 *
2604 */
2605
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002606/* The state between the channel data and the HTTP parser state can be
2607 * unconsistent, so reset the parser and call it again. Warning, this
2608 * action not revalidate the request and not send a 400 if the modified
2609 * resuest is not valid.
2610 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002611 * This function never fails. The direction is set using dir, which equals
2612 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002613 */
2614static void hlua_resynchonize_proto(struct stream *stream, int dir)
2615{
2616 /* Protocol HTTP. */
2617 if (stream->be->mode == PR_MODE_HTTP) {
2618
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002619 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002620 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002621 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002622 http_txn_reset_res(stream->txn);
2623
2624 if (stream->txn->hdr_idx.v)
2625 hdr_idx_init(&stream->txn->hdr_idx);
2626
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002627 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002628 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002629 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002630 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2631 }
2632}
2633
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002634/* This function is called before the Lua execution. It stores
2635 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002636 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002637static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002638{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002639 c->mode = stream->be->mode;
2640 switch (c->mode) {
2641 case PR_MODE_HTTP:
2642 c->data.http.dir = opt & SMP_OPT_DIR;
2643 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2644 c->data.http.state = stream->txn->req.msg_state;
2645 else
2646 c->data.http.state = stream->txn->rsp.msg_state;
2647 break;
2648 default:
2649 break;
2650 }
2651}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002652
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002653/* This function is called after the Lua execution. it
2654 * returns true if the parser state is consistent, otherwise,
2655 * it return false.
2656 *
2657 * In HTTP mode, the parser state must be in the same state
2658 * or greater when we exit the function. Even if we do a
2659 * control yield. This prevent to break the HTTP message
2660 * from the Lua code.
2661 */
2662static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2663{
2664 if (c->mode != stream->be->mode)
2665 return 0;
2666
2667 switch (c->mode) {
2668 case PR_MODE_HTTP:
2669 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002670 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002671 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2672 return stream->txn->req.msg_state >= c->data.http.state;
2673 else
2674 return stream->txn->rsp.msg_state >= c->data.http.state;
2675 default:
2676 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002677 }
2678 return 1;
2679}
2680
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002681/* Returns the struct hlua_channel join to the class channel in the
2682 * stack entry "ud" or throws an argument error.
2683 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002684__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002685{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002686 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002687}
2688
Willy Tarreau47860ed2015-03-10 14:07:50 +01002689/* Pushes the channel onto the top of the stack. If the stask does not have a
2690 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002691 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002692static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002693{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002694 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002695 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002696 return 0;
2697
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002698 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002699 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002700 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002701
2702 /* Pop a class sesison metatable and affect it to the userdata. */
2703 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2704 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002705 return 1;
2706}
2707
2708/* Duplicate all the data present in the input channel and put it
2709 * in a string LUA variables. Returns -1 and push a nil value in
2710 * the stack if the channel is closed and all the data are consumed,
2711 * returns 0 if no data are available, otherwise it returns the length
2712 * of the builded string.
2713 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002714static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002715{
2716 char *blk1;
2717 char *blk2;
2718 int len1;
2719 int len2;
2720 int ret;
2721 luaL_Buffer b;
2722
Willy Tarreau06d80a92017-10-19 14:32:15 +02002723 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002724 if (unlikely(ret == 0))
2725 return 0;
2726
2727 if (unlikely(ret < 0)) {
2728 lua_pushnil(L);
2729 return -1;
2730 }
2731
2732 luaL_buffinit(L, &b);
2733 luaL_addlstring(&b, blk1, len1);
2734 if (unlikely(ret == 2))
2735 luaL_addlstring(&b, blk2, len2);
2736 luaL_pushresult(&b);
2737
2738 if (unlikely(ret == 2))
2739 return len1 + len2;
2740 return len1;
2741}
2742
2743/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2744 * a yield. This function keep the data in the buffer.
2745 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002746__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002747{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002748 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002749
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002750 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2751
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002752 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002753 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002754 return 1;
2755}
2756
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002757/* Check arguments for the function "hlua_channel_dup_yield". */
2758__LJMP static int hlua_channel_dup(lua_State *L)
2759{
2760 MAY_LJMP(check_args(L, 1, "dup"));
2761 MAY_LJMP(hlua_checkchannel(L, 1));
2762 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2763}
2764
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002765/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2766 * a yield. This function consumes the data in the buffer. It returns
2767 * a string containing the data or a nil pointer if no data are available
2768 * and the channel is closed.
2769 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002770__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002771{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002772 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002773 int ret;
2774
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002775 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002776
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002777 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002778 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002779 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002780
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002781 if (unlikely(ret == -1))
2782 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002783
Willy Tarreau47860ed2015-03-10 14:07:50 +01002784 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002785 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002786 return 1;
2787}
2788
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002789/* Check arguments for the fucntion "hlua_channel_get_yield". */
2790__LJMP static int hlua_channel_get(lua_State *L)
2791{
2792 MAY_LJMP(check_args(L, 1, "get"));
2793 MAY_LJMP(hlua_checkchannel(L, 1));
2794 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2795}
2796
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002797/* This functions consumes and returns one line. If the channel is closed,
2798 * and the last data does not contains a final '\n', the data are returned
2799 * without the final '\n'. When no more data are avalaible, it returns nil
2800 * value.
2801 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002802__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002803{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002804 char *blk1;
2805 char *blk2;
2806 int len1;
2807 int len2;
2808 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002809 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002810 int ret;
2811 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002812
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002813 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2814
Willy Tarreau06d80a92017-10-19 14:32:15 +02002815 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002816 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002817 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002818
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002819 if (ret == -1) {
2820 lua_pushnil(L);
2821 return 1;
2822 }
2823
2824 luaL_buffinit(L, &b);
2825 luaL_addlstring(&b, blk1, len1);
2826 len = len1;
2827 if (unlikely(ret == 2)) {
2828 luaL_addlstring(&b, blk2, len2);
2829 len += len2;
2830 }
2831 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002832 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002833 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002834 return 1;
2835}
2836
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002837/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2838__LJMP static int hlua_channel_getline(lua_State *L)
2839{
2840 MAY_LJMP(check_args(L, 1, "getline"));
2841 MAY_LJMP(hlua_checkchannel(L, 1));
2842 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2843}
2844
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002845/* This function takes a string as input, and append it at the
2846 * input side of channel. If the data is too big, but a space
2847 * is probably available after sending some data, the function
2848 * yield. If the data is bigger than the buffer, or if the
2849 * channel is closed, it returns -1. otherwise, it returns the
2850 * amount of data writed.
2851 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002852__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002853{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002854 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002855 size_t len;
2856 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2857 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2858 int ret;
2859 int max;
2860
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002861 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2862 * the request buffer if its not required.
2863 */
2864 if (chn->buf->size == 0) {
2865 si_applet_cant_put(chn_prod(chn));
2866 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2867 }
2868
Willy Tarreau47860ed2015-03-10 14:07:50 +01002869 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002870 if (max > len - l)
2871 max = len - l;
2872
Willy Tarreau06d80a92017-10-19 14:32:15 +02002873 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002874 if (ret == -2 || ret == -3) {
2875 lua_pushinteger(L, -1);
2876 return 1;
2877 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002878 if (ret == -1) {
2879 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002880 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002881 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002882 l += ret;
2883 lua_pop(L, 1);
2884 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002885 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002886
Willy Tarreau47860ed2015-03-10 14:07:50 +01002887 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2888 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002889 /* There are no space avalaible, and the output buffer is empty.
2890 * in this case, we cannot add more data, so we cannot yield,
2891 * we return the amount of copyied data.
2892 */
2893 return 1;
2894 }
2895 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002896 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002897 return 1;
2898}
2899
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002900/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002901 * of the writed string, or -1 if the channel is closed or if the
2902 * buffer size is too little for the data.
2903 */
2904__LJMP static int hlua_channel_append(lua_State *L)
2905{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002906 size_t len;
2907
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002908 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002909 MAY_LJMP(hlua_checkchannel(L, 1));
2910 MAY_LJMP(luaL_checklstring(L, 2, &len));
2911 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002912 lua_pushinteger(L, 0);
2913
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002914 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002915}
2916
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002917/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002918 * his process by cleaning the buffer. The result is a replacement
2919 * of the current data. It returns the length of the writed string,
2920 * or -1 if the channel is closed or if the buffer size is too
2921 * little for the data.
2922 */
2923__LJMP static int hlua_channel_set(lua_State *L)
2924{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002925 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002926
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002927 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002928 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002929 lua_pushinteger(L, 0);
2930
Willy Tarreau47860ed2015-03-10 14:07:50 +01002931 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002932
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002933 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002934}
2935
2936/* Append data in the output side of the buffer. This data is immediatly
2937 * sent. The fcuntion returns the ammount of data writed. If the buffer
2938 * cannot contains the data, the function yield. The function returns -1
2939 * if the channel is closed.
2940 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002941__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002942{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002943 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002944 size_t len;
2945 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2946 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2947 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002948 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002949
Willy Tarreau47860ed2015-03-10 14:07:50 +01002950 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002951 lua_pushinteger(L, -1);
2952 return 1;
2953 }
2954
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002955 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2956 * the request buffer if its not required.
2957 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002958 if (chn->buf->size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002959 si_applet_cant_put(chn_prod(chn));
2960 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002961 }
2962
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002963 /* the writed data will be immediatly sent, so we can check
2964 * the avalaible space without taking in account the reserve.
2965 * The reserve is guaranted for the processing of incoming
2966 * data, because the buffer will be flushed.
2967 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002968 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002969
2970 /* If there are no space avalaible, and the output buffer is empty.
2971 * in this case, we cannot add more data, so we cannot yield,
2972 * we return the amount of copyied data.
2973 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002974 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002975 return 1;
2976
2977 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002978 if (max > len - l)
2979 max = len - l;
2980
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002981 /* The buffer avalaible size may be not contiguous. This test
2982 * detects a non contiguous buffer and realign it.
2983 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002984 if (bi_space_for_replace(chn->buf) < max)
2985 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002986
2987 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002988 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002989
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002990 /* buffer replace considers that the input part is filled.
2991 * so, I must forward these new data in the output part.
2992 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002993 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002994
2995 l += max;
2996 lua_pop(L, 1);
2997 lua_pushinteger(L, l);
2998
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002999 /* If there are no space avalaible, and the output buffer is empty.
3000 * in this case, we cannot add more data, so we cannot yield,
3001 * we return the amount of copyied data.
3002 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003003 max = chn->buf->size - buffer_len(chn->buf);
3004 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003005 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003006
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003007 if (l < len) {
3008 /* If we are waiting for space in the response buffer, we
3009 * must set the flag WAKERESWR. This flag required the task
3010 * wake up if any activity is detected on the response buffer.
3011 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003012 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003013 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003014 else
3015 HLUA_SET_WAKEREQWR(hlua);
3016 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003017 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003018
3019 return 1;
3020}
3021
3022/* Just a wraper of "_hlua_channel_send". This wrapper permits
3023 * yield the LUA process, and resume it without checking the
3024 * input arguments.
3025 */
3026__LJMP static int hlua_channel_send(lua_State *L)
3027{
3028 MAY_LJMP(check_args(L, 2, "send"));
3029 lua_pushinteger(L, 0);
3030
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003031 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003032}
3033
3034/* This function forward and amount of butes. The data pass from
3035 * the input side of the buffer to the output side, and can be
3036 * forwarded. This function never fails.
3037 *
3038 * The Lua function takes an amount of bytes to be forwarded in
3039 * imput. It returns the number of bytes forwarded.
3040 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003041__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003042{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003043 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003044 int len;
3045 int l;
3046 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003047 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003048
3049 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3050 len = MAY_LJMP(luaL_checkinteger(L, 2));
3051 l = MAY_LJMP(luaL_checkinteger(L, -1));
3052
3053 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01003054 if (max > chn->buf->i)
3055 max = chn->buf->i;
3056 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003057 l += max;
3058
3059 lua_pop(L, 1);
3060 lua_pushinteger(L, l);
3061
3062 /* Check if it miss bytes to forward. */
3063 if (l < len) {
3064 /* The the input channel or the output channel are closed, we
3065 * must return the amount of data forwarded.
3066 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003067 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003068 return 1;
3069
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003070 /* If we are waiting for space data in the response buffer, we
3071 * must set the flag WAKERESWR. This flag required the task
3072 * wake up if any activity is detected on the response buffer.
3073 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003074 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003075 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003076 else
3077 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003078
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003079 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01003080 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003081 }
3082
3083 return 1;
3084}
3085
3086/* Just check the input and prepare the stack for the previous
3087 * function "hlua_channel_forward_yield"
3088 */
3089__LJMP static int hlua_channel_forward(lua_State *L)
3090{
3091 MAY_LJMP(check_args(L, 2, "forward"));
3092 MAY_LJMP(hlua_checkchannel(L, 1));
3093 MAY_LJMP(luaL_checkinteger(L, 2));
3094
3095 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003096 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003097}
3098
3099/* Just returns the number of bytes available in the input
3100 * side of the buffer. This function never fails.
3101 */
3102__LJMP static int hlua_channel_get_in_len(lua_State *L)
3103{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003104 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003105
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003106 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003107 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01003108 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003109 return 1;
3110}
3111
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003112/* Returns true if the channel is full. */
3113__LJMP static int hlua_channel_is_full(lua_State *L)
3114{
3115 struct channel *chn;
3116 int rem;
3117
3118 MAY_LJMP(check_args(L, 1, "is_full"));
3119 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3120
3121 rem = chn->buf->size;
3122 rem -= chn->buf->o; /* Output size */
3123 rem -= chn->buf->i; /* Input size */
3124 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
3125
3126 lua_pushboolean(L, rem <= 0);
3127 return 1;
3128}
3129
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003130/* Just returns the number of bytes available in the output
3131 * side of the buffer. This function never fails.
3132 */
3133__LJMP static int hlua_channel_get_out_len(lua_State *L)
3134{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003135 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003136
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003137 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003138 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01003139 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003140 return 1;
3141}
3142
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003143/*
3144 *
3145 *
3146 * Class Fetches
3147 *
3148 *
3149 */
3150
3151/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003152 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003153 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003154__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003155{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003156 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003157}
3158
3159/* This function creates and push in the stack a fetch object according
3160 * with a current TXN.
3161 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003162static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003163{
Willy Tarreau7073c472015-04-06 11:15:40 +02003164 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003165
3166 /* Check stack size. */
3167 if (!lua_checkstack(L, 3))
3168 return 0;
3169
3170 /* Create the object: obj[0] = userdata.
3171 * Note that the base of the Fetches object is the
3172 * transaction object.
3173 */
3174 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003175 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003176 lua_rawseti(L, -2, 0);
3177
Willy Tarreau7073c472015-04-06 11:15:40 +02003178 hsmp->s = txn->s;
3179 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003180 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003181 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003182
3183 /* Pop a class sesison metatable and affect it to the userdata. */
3184 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3185 lua_setmetatable(L, -2);
3186
3187 return 1;
3188}
3189
3190/* This function is an LUA binding. It is called with each sample-fetch.
3191 * It uses closure argument to store the associated sample-fetch. It
3192 * returns only one argument or throws an error. An error is thrown
3193 * only if an error is encountered during the argument parsing. If
3194 * the "sample-fetch" function fails, nil is returned.
3195 */
3196__LJMP static int hlua_run_sample_fetch(lua_State *L)
3197{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003198 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003199 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003200 struct arg args[ARGM_NBARGS + 1];
3201 int i;
3202 struct sample smp;
3203
3204 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003205 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003206
3207 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003208 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003209
Thierry FOURNIERca988662015-12-20 18:43:03 +01003210 /* Check execution authorization. */
3211 if (f->use & SMP_USE_HTTP_ANY &&
3212 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3213 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3214 "is not available in Lua services", f->kw);
3215 WILL_LJMP(lua_error(L));
3216 }
3217
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003218 /* Get extra arguments. */
3219 for (i = 0; i < lua_gettop(L) - 1; i++) {
3220 if (i >= ARGM_NBARGS)
3221 break;
3222 hlua_lua2arg(L, i + 2, &args[i]);
3223 }
3224 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003225 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003226
3227 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003228 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003229
3230 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003231 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003232 lua_pushfstring(L, "error in arguments");
3233 WILL_LJMP(lua_error(L));
3234 }
3235
3236 /* Initialise the sample. */
3237 memset(&smp, 0, sizeof(smp));
3238
3239 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003240 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003241 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003242 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003243 lua_pushstring(L, "");
3244 else
3245 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003246 return 1;
3247 }
3248
3249 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003250 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003251 hlua_smp2lua_str(L, &smp);
3252 else
3253 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003254 return 1;
3255}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003256
3257/*
3258 *
3259 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003260 * Class Converters
3261 *
3262 *
3263 */
3264
3265/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003266 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003267 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003268__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003269{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003270 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003271}
3272
3273/* This function creates and push in the stack a Converters object
3274 * according with a current TXN.
3275 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003276static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003277{
Willy Tarreau7073c472015-04-06 11:15:40 +02003278 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003279
3280 /* Check stack size. */
3281 if (!lua_checkstack(L, 3))
3282 return 0;
3283
3284 /* Create the object: obj[0] = userdata.
3285 * Note that the base of the Converters object is the
3286 * same than the TXN object.
3287 */
3288 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003289 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003290 lua_rawseti(L, -2, 0);
3291
Willy Tarreau7073c472015-04-06 11:15:40 +02003292 hsmp->s = txn->s;
3293 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003294 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003295 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003296
Willy Tarreau87b09662015-04-03 00:22:06 +02003297 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003298 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3299 lua_setmetatable(L, -2);
3300
3301 return 1;
3302}
3303
3304/* This function is an LUA binding. It is called with each converter.
3305 * It uses closure argument to store the associated converter. It
3306 * returns only one argument or throws an error. An error is thrown
3307 * only if an error is encountered during the argument parsing. If
3308 * the converter function function fails, nil is returned.
3309 */
3310__LJMP static int hlua_run_sample_conv(lua_State *L)
3311{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003312 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003313 struct sample_conv *conv;
3314 struct arg args[ARGM_NBARGS + 1];
3315 int i;
3316 struct sample smp;
3317
3318 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003319 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003320
3321 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003322 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003323
3324 /* Get extra arguments. */
3325 for (i = 0; i < lua_gettop(L) - 2; i++) {
3326 if (i >= ARGM_NBARGS)
3327 break;
3328 hlua_lua2arg(L, i + 3, &args[i]);
3329 }
3330 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003331 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003332
3333 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003334 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003335
3336 /* Run the special args checker. */
3337 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3338 hlua_pusherror(L, "error in arguments");
3339 WILL_LJMP(lua_error(L));
3340 }
3341
3342 /* Initialise the sample. */
3343 if (!hlua_lua2smp(L, 2, &smp)) {
3344 hlua_pusherror(L, "error in the input argument");
3345 WILL_LJMP(lua_error(L));
3346 }
3347
Willy Tarreau1777ea62016-03-10 16:15:46 +01003348 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3349
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003350 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003351 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003352 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003353 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003354 WILL_LJMP(lua_error(L));
3355 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003356 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3357 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003358 hlua_pusherror(L, "error during the input argument casting");
3359 WILL_LJMP(lua_error(L));
3360 }
3361
3362 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003363 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003364 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003365 lua_pushstring(L, "");
3366 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003367 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003368 return 1;
3369 }
3370
3371 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003372 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003373 hlua_smp2lua_str(L, &smp);
3374 else
3375 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003376 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003377}
3378
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003379/*
3380 *
3381 *
3382 * Class AppletTCP
3383 *
3384 *
3385 */
3386
3387/* Returns a struct hlua_txn if the stack entry "ud" is
3388 * a class stream, otherwise it throws an error.
3389 */
3390__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3391{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003392 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003393}
3394
3395/* This function creates and push in the stack an Applet object
3396 * according with a current TXN.
3397 */
3398static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3399{
3400 struct hlua_appctx *appctx;
3401 struct stream_interface *si = ctx->owner;
3402 struct stream *s = si_strm(si);
3403 struct proxy *p = s->be;
3404
3405 /* Check stack size. */
3406 if (!lua_checkstack(L, 3))
3407 return 0;
3408
3409 /* Create the object: obj[0] = userdata.
3410 * Note that the base of the Converters object is the
3411 * same than the TXN object.
3412 */
3413 lua_newtable(L);
3414 appctx = lua_newuserdata(L, sizeof(*appctx));
3415 lua_rawseti(L, -2, 0);
3416 appctx->appctx = ctx;
3417 appctx->htxn.s = s;
3418 appctx->htxn.p = p;
3419
3420 /* Create the "f" field that contains a list of fetches. */
3421 lua_pushstring(L, "f");
3422 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3423 return 0;
3424 lua_settable(L, -3);
3425
3426 /* Create the "sf" field that contains a list of stringsafe fetches. */
3427 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003428 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003429 return 0;
3430 lua_settable(L, -3);
3431
3432 /* Create the "c" field that contains a list of converters. */
3433 lua_pushstring(L, "c");
3434 if (!hlua_converters_new(L, &appctx->htxn, 0))
3435 return 0;
3436 lua_settable(L, -3);
3437
3438 /* Create the "sc" field that contains a list of stringsafe converters. */
3439 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003440 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003441 return 0;
3442 lua_settable(L, -3);
3443
3444 /* Pop a class stream metatable and affect it to the table. */
3445 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3446 lua_setmetatable(L, -2);
3447
3448 return 1;
3449}
3450
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003451__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3452{
3453 struct hlua_appctx *appctx;
3454 struct stream *s;
3455 const char *name;
3456 size_t len;
3457 struct sample smp;
3458
3459 MAY_LJMP(check_args(L, 3, "set_var"));
3460
3461 /* It is useles to retrieve the stream, but this function
3462 * runs only in a stream context.
3463 */
3464 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3465 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3466 s = appctx->htxn.s;
3467
3468 /* Converts the third argument in a sample. */
3469 hlua_lua2smp(L, 3, &smp);
3470
3471 /* Store the sample in a variable. */
3472 smp_set_owner(&smp, s->be, s->sess, s, 0);
3473 vars_set_by_name(name, len, &smp);
3474 return 0;
3475}
3476
3477__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3478{
3479 struct hlua_appctx *appctx;
3480 struct stream *s;
3481 const char *name;
3482 size_t len;
3483 struct sample smp;
3484
3485 MAY_LJMP(check_args(L, 2, "unset_var"));
3486
3487 /* It is useles to retrieve the stream, but this function
3488 * runs only in a stream context.
3489 */
3490 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3491 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3492 s = appctx->htxn.s;
3493
3494 /* Unset the variable. */
3495 smp_set_owner(&smp, s->be, s->sess, s, 0);
3496 vars_unset_by_name(name, len, &smp);
3497 return 0;
3498}
3499
3500__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3501{
3502 struct hlua_appctx *appctx;
3503 struct stream *s;
3504 const char *name;
3505 size_t len;
3506 struct sample smp;
3507
3508 MAY_LJMP(check_args(L, 2, "get_var"));
3509
3510 /* It is useles to retrieve the stream, but this function
3511 * runs only in a stream context.
3512 */
3513 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3514 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3515 s = appctx->htxn.s;
3516
3517 smp_set_owner(&smp, s->be, s->sess, s, 0);
3518 if (!vars_get_by_name(name, len, &smp)) {
3519 lua_pushnil(L);
3520 return 1;
3521 }
3522
3523 return hlua_smp2lua(L, &smp);
3524}
3525
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003526__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3527{
3528 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3529 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003530 struct hlua *hlua;
3531
3532 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003533 if (!s->hlua)
3534 return 0;
3535 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003536
3537 MAY_LJMP(check_args(L, 2, "set_priv"));
3538
3539 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003540 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003541
3542 /* Get and store new value. */
3543 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3544 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3545
3546 return 0;
3547}
3548
3549__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3550{
3551 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3552 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003553 struct hlua *hlua;
3554
3555 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003556 if (!s->hlua) {
3557 lua_pushnil(L);
3558 return 1;
3559 }
3560 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003561
3562 /* Push configuration index in the stack. */
3563 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3564
3565 return 1;
3566}
3567
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003568/* If expected data not yet available, it returns a yield. This function
3569 * consumes the data in the buffer. It returns a string containing the
3570 * data. This string can be empty.
3571 */
3572__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3573{
3574 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3575 struct stream_interface *si = appctx->appctx->owner;
3576 int ret;
3577 char *blk1;
3578 int len1;
3579 char *blk2;
3580 int len2;
3581
3582 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003583 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003584
3585 /* Data not yet avalaible. return yield. */
3586 if (ret == 0) {
3587 si_applet_cant_get(si);
3588 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3589 }
3590
3591 /* End of data: commit the total strings and return. */
3592 if (ret < 0) {
3593 luaL_pushresult(&appctx->b);
3594 return 1;
3595 }
3596
3597 /* Ensure that the block 2 length is usable. */
3598 if (ret == 1)
3599 len2 = 0;
3600
3601 /* dont check the max length read and dont check. */
3602 luaL_addlstring(&appctx->b, blk1, len1);
3603 luaL_addlstring(&appctx->b, blk2, len2);
3604
3605 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003606 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003607 luaL_pushresult(&appctx->b);
3608 return 1;
3609}
3610
3611/* Check arguments for the fucntion "hlua_channel_get_yield". */
3612__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3613{
3614 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3615
3616 /* Initialise the string catenation. */
3617 luaL_buffinit(L, &appctx->b);
3618
3619 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3620}
3621
3622/* If expected data not yet available, it returns a yield. This function
3623 * consumes the data in the buffer. It returns a string containing the
3624 * data. This string can be empty.
3625 */
3626__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3627{
3628 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3629 struct stream_interface *si = appctx->appctx->owner;
3630 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3631 int ret;
3632 char *blk1;
3633 int len1;
3634 char *blk2;
3635 int len2;
3636
3637 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003638 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003639
3640 /* Data not yet avalaible. return yield. */
3641 if (ret == 0) {
3642 si_applet_cant_get(si);
3643 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3644 }
3645
3646 /* End of data: commit the total strings and return. */
3647 if (ret < 0) {
3648 luaL_pushresult(&appctx->b);
3649 return 1;
3650 }
3651
3652 /* Ensure that the block 2 length is usable. */
3653 if (ret == 1)
3654 len2 = 0;
3655
3656 if (len == -1) {
3657
3658 /* If len == -1, catenate all the data avalaile and
3659 * yield because we want to get all the data until
3660 * the end of data stream.
3661 */
3662 luaL_addlstring(&appctx->b, blk1, len1);
3663 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003664 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003665 si_applet_cant_get(si);
3666 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3667
3668 } else {
3669
3670 /* Copy the fisrt block caping to the length required. */
3671 if (len1 > len)
3672 len1 = len;
3673 luaL_addlstring(&appctx->b, blk1, len1);
3674 len -= len1;
3675
3676 /* Copy the second block. */
3677 if (len2 > len)
3678 len2 = len;
3679 luaL_addlstring(&appctx->b, blk2, len2);
3680 len -= len2;
3681
3682 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003683 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003684
3685 /* If we are no other data avalaible, yield waiting for new data. */
3686 if (len > 0) {
3687 lua_pushinteger(L, len);
3688 lua_replace(L, 2);
3689 si_applet_cant_get(si);
3690 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3691 }
3692
3693 /* return the result. */
3694 luaL_pushresult(&appctx->b);
3695 return 1;
3696 }
3697
3698 /* we never executes this */
3699 hlua_pusherror(L, "Lua: internal error");
3700 WILL_LJMP(lua_error(L));
3701 return 0;
3702}
3703
3704/* Check arguments for the fucntion "hlua_channel_get_yield". */
3705__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3706{
3707 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3708 int len = -1;
3709
3710 if (lua_gettop(L) > 2)
3711 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3712 if (lua_gettop(L) >= 2) {
3713 len = MAY_LJMP(luaL_checkinteger(L, 2));
3714 lua_pop(L, 1);
3715 }
3716
3717 /* Confirm or set the required length */
3718 lua_pushinteger(L, len);
3719
3720 /* Initialise the string catenation. */
3721 luaL_buffinit(L, &appctx->b);
3722
3723 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3724}
3725
3726/* Append data in the output side of the buffer. This data is immediatly
3727 * sent. The fcuntion returns the ammount of data writed. If the buffer
3728 * cannot contains the data, the function yield. The function returns -1
3729 * if the channel is closed.
3730 */
3731__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3732{
3733 size_t len;
3734 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3735 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3736 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3737 struct stream_interface *si = appctx->appctx->owner;
3738 struct channel *chn = si_ic(si);
3739 int max;
3740
3741 /* Get the max amount of data which can write as input in the channel. */
3742 max = channel_recv_max(chn);
3743 if (max > (len - l))
3744 max = len - l;
3745
3746 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003747 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003748
3749 /* update counters. */
3750 l += max;
3751 lua_pop(L, 1);
3752 lua_pushinteger(L, l);
3753
3754 /* If some data is not send, declares the situation to the
3755 * applet, and returns a yield.
3756 */
3757 if (l < len) {
3758 si_applet_cant_put(si);
3759 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3760 }
3761
3762 return 1;
3763}
3764
3765/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3766 * yield the LUA process, and resume it without checking the
3767 * input arguments.
3768 */
3769__LJMP static int hlua_applet_tcp_send(lua_State *L)
3770{
3771 MAY_LJMP(check_args(L, 2, "send"));
3772 lua_pushinteger(L, 0);
3773
3774 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3775}
3776
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003777/*
3778 *
3779 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003780 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003781 *
3782 *
3783 */
3784
3785/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003786 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003787 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003788__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003789{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003790 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003791}
3792
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003793/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003794 * according with a current TXN.
3795 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003796static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003797{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003798 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003799 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003800 struct stream_interface *si = ctx->owner;
3801 struct stream *s = si_strm(si);
3802 struct proxy *px = s->be;
3803 struct http_txn *txn = s->txn;
3804 const char *path;
3805 const char *end;
3806 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003807
3808 /* Check stack size. */
3809 if (!lua_checkstack(L, 3))
3810 return 0;
3811
3812 /* Create the object: obj[0] = userdata.
3813 * Note that the base of the Converters object is the
3814 * same than the TXN object.
3815 */
3816 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003817 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003818 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003819 appctx->appctx = ctx;
3820 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003821 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003822 appctx->htxn.s = s;
3823 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003824
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003825 /* Create the "f" field that contains a list of fetches. */
3826 lua_pushstring(L, "f");
3827 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3828 return 0;
3829 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003830
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003831 /* Create the "sf" field that contains a list of stringsafe fetches. */
3832 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003833 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003834 return 0;
3835 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003836
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003837 /* Create the "c" field that contains a list of converters. */
3838 lua_pushstring(L, "c");
3839 if (!hlua_converters_new(L, &appctx->htxn, 0))
3840 return 0;
3841 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003842
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003843 /* Create the "sc" field that contains a list of stringsafe converters. */
3844 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003845 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003846 return 0;
3847 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003848
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003849 /* Stores the request method. */
3850 lua_pushstring(L, "method");
3851 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3852 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003853
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003854 /* Stores the http version. */
3855 lua_pushstring(L, "version");
3856 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3857 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003858
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003859 /* creates an array of headers. hlua_http_get_headers() crates and push
3860 * the array on the top of the stack.
3861 */
3862 lua_pushstring(L, "headers");
3863 htxn.s = s;
3864 htxn.p = px;
3865 htxn.dir = SMP_OPT_DIR_REQ;
3866 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3867 return 0;
3868 lua_settable(L, -3);
3869
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003870 /* Get path and qs */
3871 path = http_get_path(txn);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003872 if (path) {
3873 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3874 p = path;
3875 while (p < end && *p != '?')
3876 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003877
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003878 /* Stores the request path. */
3879 lua_pushstring(L, "path");
3880 lua_pushlstring(L, path, p - path);
3881 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003882
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003883 /* Stores the query string. */
3884 lua_pushstring(L, "qs");
3885 if (*p == '?')
3886 p++;
3887 lua_pushlstring(L, p, end - p);
3888 lua_settable(L, -3);
3889 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003890
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003891 /* Stores the request path. */
3892 lua_pushstring(L, "length");
3893 lua_pushinteger(L, txn->req.body_len);
3894 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003895
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003896 /* Create an array of HTTP request headers. */
3897 lua_pushstring(L, "headers");
3898 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3899 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003900
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003901 /* Create an empty array of HTTP request headers. */
3902 lua_pushstring(L, "response");
3903 lua_newtable(L);
3904 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003905
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003906 /* Pop a class stream metatable and affect it to the table. */
3907 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3908 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003909
3910 return 1;
3911}
3912
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003913__LJMP static int hlua_applet_http_set_var(lua_State *L)
3914{
3915 struct hlua_appctx *appctx;
3916 struct stream *s;
3917 const char *name;
3918 size_t len;
3919 struct sample smp;
3920
3921 MAY_LJMP(check_args(L, 3, "set_var"));
3922
3923 /* It is useles to retrieve the stream, but this function
3924 * runs only in a stream context.
3925 */
3926 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3927 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3928 s = appctx->htxn.s;
3929
3930 /* Converts the third argument in a sample. */
3931 hlua_lua2smp(L, 3, &smp);
3932
3933 /* Store the sample in a variable. */
3934 smp_set_owner(&smp, s->be, s->sess, s, 0);
3935 vars_set_by_name(name, len, &smp);
3936 return 0;
3937}
3938
3939__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3940{
3941 struct hlua_appctx *appctx;
3942 struct stream *s;
3943 const char *name;
3944 size_t len;
3945 struct sample smp;
3946
3947 MAY_LJMP(check_args(L, 2, "unset_var"));
3948
3949 /* It is useles to retrieve the stream, but this function
3950 * runs only in a stream context.
3951 */
3952 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3953 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3954 s = appctx->htxn.s;
3955
3956 /* Unset the variable. */
3957 smp_set_owner(&smp, s->be, s->sess, s, 0);
3958 vars_unset_by_name(name, len, &smp);
3959 return 0;
3960}
3961
3962__LJMP static int hlua_applet_http_get_var(lua_State *L)
3963{
3964 struct hlua_appctx *appctx;
3965 struct stream *s;
3966 const char *name;
3967 size_t len;
3968 struct sample smp;
3969
3970 MAY_LJMP(check_args(L, 2, "get_var"));
3971
3972 /* It is useles to retrieve the stream, but this function
3973 * runs only in a stream context.
3974 */
3975 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3976 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3977 s = appctx->htxn.s;
3978
3979 smp_set_owner(&smp, s->be, s->sess, s, 0);
3980 if (!vars_get_by_name(name, len, &smp)) {
3981 lua_pushnil(L);
3982 return 1;
3983 }
3984
3985 return hlua_smp2lua(L, &smp);
3986}
3987
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003988__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3989{
3990 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3991 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003992 struct hlua *hlua;
3993
3994 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003995 if (!s->hlua)
3996 return 0;
3997 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003998
3999 MAY_LJMP(check_args(L, 2, "set_priv"));
4000
4001 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004002 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004003
4004 /* Get and store new value. */
4005 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4006 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4007
4008 return 0;
4009}
4010
4011__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4012{
4013 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4014 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004015 struct hlua *hlua;
4016
4017 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004018 if (!s->hlua) {
4019 lua_pushnil(L);
4020 return 1;
4021 }
4022 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004023
4024 /* Push configuration index in the stack. */
4025 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4026
4027 return 1;
4028}
4029
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004030/* If expected data not yet available, it returns a yield. This function
4031 * consumes the data in the buffer. It returns a string containing the
4032 * data. This string can be empty.
4033 */
4034__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004035{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004036 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4037 struct stream_interface *si = appctx->appctx->owner;
4038 struct channel *chn = si_ic(si);
4039 int ret;
4040 char *blk1;
4041 int len1;
4042 char *blk2;
4043 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004044
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004045 /* Maybe we cant send a 100-continue ? */
4046 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau06d80a92017-10-19 14:32:15 +02004047 ret = ci_putblk(chn, HTTP_100C, strlen(HTTP_100C));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004048 /* if ret == -2 or -3 the channel closed or the message si too
4049 * big for the buffers. We cant send anything. So, we ignoring
4050 * the error, considers that the 100-continue is sent, and try
4051 * to receive.
4052 * If ret is -1, we dont have room in the buffer, so we yield.
4053 */
4054 if (ret == -1) {
4055 si_applet_cant_put(si);
4056 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4057 }
4058 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4059 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004060
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004061 /* Check for the end of the data. */
4062 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4063 luaL_pushresult(&appctx->b);
4064 return 1;
4065 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004066
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004067 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004068 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004069
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004070 /* Data not yet avalaible. return yield. */
4071 if (ret == 0) {
4072 si_applet_cant_get(si);
4073 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4074 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004075
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004076 /* End of data: commit the total strings and return. */
4077 if (ret < 0) {
4078 luaL_pushresult(&appctx->b);
4079 return 1;
4080 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004081
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004082 /* Ensure that the block 2 length is usable. */
4083 if (ret == 1)
4084 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004085
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004086 /* Copy the fisrt block caping to the length required. */
4087 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4088 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4089 luaL_addlstring(&appctx->b, blk1, len1);
4090 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004091
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004092 /* Copy the second block. */
4093 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4094 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4095 luaL_addlstring(&appctx->b, blk2, len2);
4096 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004097
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004098 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004099 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004100 luaL_pushresult(&appctx->b);
4101 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004102}
4103
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004104/* Check arguments for the fucntion "hlua_channel_get_yield". */
4105__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004106{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004107 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004108
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004109 /* Initialise the string catenation. */
4110 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004111
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004112 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004113}
4114
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004115/* If expected data not yet available, it returns a yield. This function
4116 * consumes the data in the buffer. It returns a string containing the
4117 * data. This string can be empty.
4118 */
4119__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004120{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004121 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4122 struct stream_interface *si = appctx->appctx->owner;
4123 int len = MAY_LJMP(luaL_checkinteger(L, 2));
4124 struct channel *chn = si_ic(si);
4125 int ret;
4126 char *blk1;
4127 int len1;
4128 char *blk2;
4129 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004130
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004131 /* Maybe we cant send a 100-continue ? */
4132 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau06d80a92017-10-19 14:32:15 +02004133 ret = ci_putblk(chn, HTTP_100C, strlen(HTTP_100C));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004134 /* if ret == -2 or -3 the channel closed or the message si too
4135 * big for the buffers. We cant send anything. So, we ignoring
4136 * the error, considers that the 100-continue is sent, and try
4137 * to receive.
4138 * If ret is -1, we dont have room in the buffer, so we yield.
4139 */
4140 if (ret == -1) {
4141 si_applet_cant_put(si);
4142 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4143 }
4144 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4145 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004146
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004147 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004148 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004149
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004150 /* Data not yet avalaible. return yield. */
4151 if (ret == 0) {
4152 si_applet_cant_get(si);
4153 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4154 }
4155
4156 /* End of data: commit the total strings and return. */
4157 if (ret < 0) {
4158 luaL_pushresult(&appctx->b);
4159 return 1;
4160 }
4161
4162 /* Ensure that the block 2 length is usable. */
4163 if (ret == 1)
4164 len2 = 0;
4165
4166 /* Copy the fisrt block caping to the length required. */
4167 if (len1 > len)
4168 len1 = len;
4169 luaL_addlstring(&appctx->b, blk1, len1);
4170 len -= len1;
4171
4172 /* Copy the second block. */
4173 if (len2 > len)
4174 len2 = len;
4175 luaL_addlstring(&appctx->b, blk2, len2);
4176 len -= len2;
4177
4178 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004179 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004180 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4181 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4182
4183 /* If we are no other data avalaible, yield waiting for new data. */
4184 if (len > 0) {
4185 lua_pushinteger(L, len);
4186 lua_replace(L, 2);
4187 si_applet_cant_get(si);
4188 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4189 }
4190
4191 /* return the result. */
4192 luaL_pushresult(&appctx->b);
4193 return 1;
4194}
4195
4196/* Check arguments for the fucntion "hlua_channel_get_yield". */
4197__LJMP static int hlua_applet_http_recv(lua_State *L)
4198{
4199 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4200 int len = -1;
4201
4202 /* Check arguments. */
4203 if (lua_gettop(L) > 2)
4204 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4205 if (lua_gettop(L) >= 2) {
4206 len = MAY_LJMP(luaL_checkinteger(L, 2));
4207 lua_pop(L, 1);
4208 }
4209
4210 /* Check the required length */
4211 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4212 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4213 lua_pushinteger(L, len);
4214
4215 /* Initialise the string catenation. */
4216 luaL_buffinit(L, &appctx->b);
4217
4218 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4219}
4220
4221/* Append data in the output side of the buffer. This data is immediatly
4222 * sent. The fcuntion returns the ammount of data writed. If the buffer
4223 * cannot contains the data, the function yield. The function returns -1
4224 * if the channel is closed.
4225 */
4226__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4227{
4228 size_t len;
4229 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4230 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4231 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4232 struct stream_interface *si = appctx->appctx->owner;
4233 struct channel *chn = si_ic(si);
4234 int max;
4235
4236 /* Get the max amount of data which can write as input in the channel. */
4237 max = channel_recv_max(chn);
4238 if (max > (len - l))
4239 max = len - l;
4240
4241 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004242 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004243
4244 /* update counters. */
4245 l += max;
4246 lua_pop(L, 1);
4247 lua_pushinteger(L, l);
4248
4249 /* If some data is not send, declares the situation to the
4250 * applet, and returns a yield.
4251 */
4252 if (l < len) {
4253 si_applet_cant_put(si);
4254 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
4255 }
4256
4257 return 1;
4258}
4259
4260/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4261 * yield the LUA process, and resume it without checking the
4262 * input arguments.
4263 */
4264__LJMP static int hlua_applet_http_send(lua_State *L)
4265{
4266 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4267 size_t len;
4268 char hex[10];
4269
4270 MAY_LJMP(luaL_checklstring(L, 2, &len));
4271
4272 /* If transfer encoding chunked is selected, we surround the data
4273 * by chunk data.
4274 */
4275 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4276 snprintf(hex, 9, "%x", (unsigned int)len);
4277 lua_pushfstring(L, "%s\r\n", hex);
4278 lua_insert(L, 2); /* swap the last 2 entries. */
4279 lua_pushstring(L, "\r\n");
4280 lua_concat(L, 3);
4281 }
4282
4283 /* This interger is used for followinf the amount of data sent. */
4284 lua_pushinteger(L, 0);
4285
4286 /* We want to send some data. Headers must be sent. */
4287 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4288 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4289 WILL_LJMP(lua_error(L));
4290 }
4291
4292 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4293}
4294
4295__LJMP static int hlua_applet_http_addheader(lua_State *L)
4296{
4297 const char *name;
4298 int ret;
4299
4300 MAY_LJMP(hlua_checkapplet_http(L, 1));
4301 name = MAY_LJMP(luaL_checkstring(L, 2));
4302 MAY_LJMP(luaL_checkstring(L, 3));
4303
4304 /* Push in the stack the "response" entry. */
4305 ret = lua_getfield(L, 1, "response");
4306 if (ret != LUA_TTABLE) {
4307 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4308 "is expected as an array. %s found", lua_typename(L, ret));
4309 WILL_LJMP(lua_error(L));
4310 }
4311
4312 /* check if the header is already registered if it is not
4313 * the case, register it.
4314 */
4315 ret = lua_getfield(L, -1, name);
4316 if (ret == LUA_TNIL) {
4317
4318 /* Entry not found. */
4319 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4320
4321 /* Insert the new header name in the array in the top of the stack.
4322 * It left the new array in the top of the stack.
4323 */
4324 lua_newtable(L);
4325 lua_pushvalue(L, 2);
4326 lua_pushvalue(L, -2);
4327 lua_settable(L, -4);
4328
4329 } else if (ret != LUA_TTABLE) {
4330
4331 /* corruption error. */
4332 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4333 "is expected as an array. %s found", name, lua_typename(L, ret));
4334 WILL_LJMP(lua_error(L));
4335 }
4336
4337 /* Now the top od thestack is an array of values. We push
4338 * the header value as new entry.
4339 */
4340 lua_pushvalue(L, 3);
4341 ret = lua_rawlen(L, -2);
4342 lua_rawseti(L, -2, ret + 1);
4343 lua_pushboolean(L, 1);
4344 return 1;
4345}
4346
4347__LJMP static int hlua_applet_http_status(lua_State *L)
4348{
4349 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4350 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004351 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004352
4353 if (status < 100 || status > 599) {
4354 lua_pushboolean(L, 0);
4355 return 1;
4356 }
4357
4358 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004359 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004360 lua_pushboolean(L, 1);
4361 return 1;
4362}
4363
4364/* We will build the status line and the headers of the HTTP response.
4365 * We will try send at once if its not possible, we give back the hand
4366 * waiting for more room.
4367 */
4368__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4369{
4370 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4371 struct stream_interface *si = appctx->appctx->owner;
4372 struct channel *chn = si_ic(si);
4373 int ret;
4374 size_t len;
4375 const char *msg;
4376
4377 /* Get the message as the first argument on the stack. */
4378 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4379
4380 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004381 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004382
4383 /* if ret == -2 or -3 the channel closed or the message si too
4384 * big for the buffers.
4385 */
4386 if (ret == -2 || ret == -3) {
4387 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4388 WILL_LJMP(lua_error(L));
4389 }
4390
4391 /* If ret is -1, we dont have room in the buffer, so we yield. */
4392 if (ret == -1) {
4393 si_applet_cant_put(si);
4394 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4395 }
4396
4397 /* Headers sent, set the flag. */
4398 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4399 return 0;
4400}
4401
4402__LJMP static int hlua_applet_http_start_response(lua_State *L)
4403{
4404 struct chunk *tmp = get_trash_chunk();
4405 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004406 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02004407 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004408 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02004409 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004410 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004411 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004412 int hdr_chunked = 0;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004413 const char *reason = appctx->appctx->ctx.hlua_apphttp.reason;
4414
4415 if (reason == NULL)
4416 reason = get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004417
4418 /* Use the same http version than the request. */
4419 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004420 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004421 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004422 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004423
4424 /* Get the array associated to the field "response" in the object AppletHTTP. */
4425 lua_pushvalue(L, 0);
4426 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4427 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4428 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4429 WILL_LJMP(lua_error(L));
4430 }
4431
4432 /* Browse the list of headers. */
4433 lua_pushnil(L);
4434 while(lua_next(L, -2) != 0) {
4435
4436 /* We expect a string as -2. */
4437 if (lua_type(L, -2) != LUA_TSTRING) {
4438 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4439 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4440 lua_typename(L, lua_type(L, -2)));
4441 WILL_LJMP(lua_error(L));
4442 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004443 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004444
4445 /* We expect an array as -1. */
4446 if (lua_type(L, -1) != LUA_TTABLE) {
4447 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4448 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4449 name,
4450 lua_typename(L, lua_type(L, -1)));
4451 WILL_LJMP(lua_error(L));
4452 }
4453
4454 /* Browse the table who is on the top of the stack. */
4455 lua_pushnil(L);
4456 while(lua_next(L, -2) != 0) {
4457
4458 /* We expect a number as -2. */
4459 if (lua_type(L, -2) != LUA_TNUMBER) {
4460 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4461 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4462 name,
4463 lua_typename(L, lua_type(L, -2)));
4464 WILL_LJMP(lua_error(L));
4465 }
4466 id = lua_tointeger(L, -2);
4467
4468 /* We expect a string as -2. */
4469 if (lua_type(L, -1) != LUA_TSTRING) {
4470 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4471 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4472 name, id,
4473 lua_typename(L, lua_type(L, -1)));
4474 WILL_LJMP(lua_error(L));
4475 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004476 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004477
4478 /* Catenate a new header. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004479 if (tmp->len + name_len + 2 + value_len + 2 < tmp->size) {
4480 memcpy(tmp->str + tmp->len, name, name_len);
4481 tmp->len += name_len;
4482 tmp->str[tmp->len++] = ':';
4483 tmp->str[tmp->len++] = ' ';
4484
4485 memcpy(tmp->str + tmp->len, value, value_len);
4486 tmp->len += value_len;
4487 tmp->str[tmp->len++] = '\r';
4488 tmp->str[tmp->len++] = '\n';
4489 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004490
4491 /* Protocol checks. */
4492
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004493 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004494 * is done without control. If it contains a bad value,
4495 * the content-length remains negative so that we can
4496 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004497 */
Willy Tarreaua3294632017-08-23 11:24:47 +02004498 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004499 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004500
4501 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004502 if (name_len == 17 && value_len == 7 &&
4503 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004504 strcasecmp("chunked", value) == 0)
4505 hdr_chunked = 1;
4506
4507 /* Remove the array from the stack, and get next element with a remaining string. */
4508 lua_pop(L, 1);
4509 }
4510
4511 /* Remove the array from the stack, and get next element with a remaining string. */
4512 lua_pop(L, 1);
4513 }
4514
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004515 /* If we dont have a content-length set, and the HTTP version is 1.1
4516 * and the status code implies the presence of a message body, we must
4517 * announce a transfer encoding chunked. This is required by haproxy
4518 * for the keepalive compliance. If the applet annouces a transfer-encoding
4519 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004520 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004521 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004522 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
4523 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4524 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4525 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004526 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4527 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4528 }
4529
4530 /* Finalize headers. */
4531 chunk_appendf(tmp, "\r\n");
4532
4533 /* Remove the last entry and the array of headers */
4534 lua_pop(L, 2);
4535
4536 /* Push the headers block. */
4537 lua_pushlstring(L, tmp->str, tmp->len);
4538
4539 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4540}
4541
4542/*
4543 *
4544 *
4545 * Class HTTP
4546 *
4547 *
4548 */
4549
4550/* Returns a struct hlua_txn if the stack entry "ud" is
4551 * a class stream, otherwise it throws an error.
4552 */
4553__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4554{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004555 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004556}
4557
4558/* This function creates and push in the stack a HTTP object
4559 * according with a current TXN.
4560 */
4561static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4562{
4563 struct hlua_txn *htxn;
4564
4565 /* Check stack size. */
4566 if (!lua_checkstack(L, 3))
4567 return 0;
4568
4569 /* Create the object: obj[0] = userdata.
4570 * Note that the base of the Converters object is the
4571 * same than the TXN object.
4572 */
4573 lua_newtable(L);
4574 htxn = lua_newuserdata(L, sizeof(*htxn));
4575 lua_rawseti(L, -2, 0);
4576
4577 htxn->s = txn->s;
4578 htxn->p = txn->p;
4579
4580 /* Pop a class stream metatable and affect it to the table. */
4581 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4582 lua_setmetatable(L, -2);
4583
4584 return 1;
4585}
4586
4587/* This function creates ans returns an array of HTTP headers.
4588 * This function does not fails. It is used as wrapper with the
4589 * 2 following functions.
4590 */
4591__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4592{
4593 const char *cur_ptr, *cur_next, *p;
4594 int old_idx, cur_idx;
4595 struct hdr_idx_elem *cur_hdr;
4596 const char *hn, *hv;
4597 int hnl, hvl;
4598 int type;
4599 const char *in;
4600 char *out;
4601 int len;
4602
4603 /* Create the table. */
4604 lua_newtable(L);
4605
4606 if (!htxn->s->txn)
4607 return 1;
4608
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004609 /* Check if a valid response is parsed */
4610 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4611 return 1;
4612
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004613 /* Build array of headers. */
4614 old_idx = 0;
4615 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4616
4617 while (1) {
4618 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4619 if (!cur_idx)
4620 break;
4621 old_idx = cur_idx;
4622
4623 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4624 cur_ptr = cur_next;
4625 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4626
4627 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4628 * and the next header starts at cur_next. We'll check
4629 * this header in the list as well as against the default
4630 * rule.
4631 */
4632
4633 /* look for ': *'. */
4634 hn = cur_ptr;
4635 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4636 if (p >= cur_ptr+cur_hdr->len)
4637 continue;
4638 hnl = p - hn;
4639 p++;
4640 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4641 p++;
4642 if (p >= cur_ptr+cur_hdr->len)
4643 continue;
4644 hv = p;
4645 hvl = cur_ptr+cur_hdr->len-p;
4646
4647 /* Lowercase the key. Don't check the size of trash, it have
4648 * the size of one buffer and the input data contains in one
4649 * buffer.
4650 */
4651 out = trash.str;
4652 for (in=hn; in<hn+hnl; in++, out++)
4653 *out = tolower(*in);
4654 *out = '\0';
4655
4656 /* Check for existing entry:
4657 * assume that the table is on the top of the stack, and
4658 * push the key in the stack, the function lua_gettable()
4659 * perform the lookup.
4660 */
4661 lua_pushlstring(L, trash.str, hnl);
4662 lua_gettable(L, -2);
4663 type = lua_type(L, -1);
4664
4665 switch (type) {
4666 case LUA_TNIL:
4667 /* Table not found, create it. */
4668 lua_pop(L, 1); /* remove the nil value. */
4669 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4670 lua_newtable(L); /* create and push empty table. */
4671 lua_pushlstring(L, hv, hvl); /* push header value. */
4672 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4673 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4674 break;
4675
4676 case LUA_TTABLE:
4677 /* Entry found: push the value in the table. */
4678 len = lua_rawlen(L, -1);
4679 lua_pushlstring(L, hv, hvl); /* push header value. */
4680 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4681 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4682 break;
4683
4684 default:
4685 /* Other cases are errors. */
4686 hlua_pusherror(L, "internal error during the parsing of headers.");
4687 WILL_LJMP(lua_error(L));
4688 }
4689 }
4690
4691 return 1;
4692}
4693
4694__LJMP static int hlua_http_req_get_headers(lua_State *L)
4695{
4696 struct hlua_txn *htxn;
4697
4698 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4699 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4700
4701 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4702}
4703
4704__LJMP static int hlua_http_res_get_headers(lua_State *L)
4705{
4706 struct hlua_txn *htxn;
4707
4708 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4709 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4710
4711 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4712}
4713
4714/* This function replace full header, or just a value in
4715 * the request or in the response. It is a wrapper fir the
4716 * 4 following functions.
4717 */
4718__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4719 struct http_msg *msg, int action)
4720{
4721 size_t name_len;
4722 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4723 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4724 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4725 struct my_regex re;
4726
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004727 /* Check if a valid response is parsed */
4728 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4729 return 0;
4730
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004731 if (!regex_comp(reg, &re, 1, 1, NULL))
4732 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4733
4734 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4735 regex_free(&re);
4736 return 0;
4737}
4738
4739__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4740{
4741 struct hlua_txn *htxn;
4742
4743 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4744 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4745
4746 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4747}
4748
4749__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4750{
4751 struct hlua_txn *htxn;
4752
4753 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4754 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4755
4756 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4757}
4758
4759__LJMP static int hlua_http_req_rep_val(lua_State *L)
4760{
4761 struct hlua_txn *htxn;
4762
4763 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4764 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4765
4766 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4767}
4768
4769__LJMP static int hlua_http_res_rep_val(lua_State *L)
4770{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004771 struct hlua_txn *htxn;
4772
4773 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4774 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4775
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004776 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004777}
4778
4779/* This function deletes all the occurences of an header.
4780 * It is a wrapper for the 2 following functions.
4781 */
4782__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4783{
4784 size_t len;
4785 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4786 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004787 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004788
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004789 /* Check if a valid response is parsed */
4790 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4791 return 0;
4792
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004793 ctx.idx = 0;
4794 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4795 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4796 return 0;
4797}
4798
4799__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4800{
4801 struct hlua_txn *htxn;
4802
4803 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4804 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4805
Willy Tarreaueee5b512015-04-03 23:46:31 +02004806 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004807}
4808
4809__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4810{
4811 struct hlua_txn *htxn;
4812
4813 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4814 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4815
Willy Tarreaueee5b512015-04-03 23:46:31 +02004816 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004817}
4818
4819/* This function adds an header. It is a wrapper used by
4820 * the 2 following functions.
4821 */
4822__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4823{
4824 size_t name_len;
4825 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4826 size_t value_len;
4827 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4828 char *p;
4829
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004830 /* Check if a valid message is parsed */
4831 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4832 return 0;
4833
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004834 /* Check length. */
4835 trash.len = value_len + name_len + 2;
4836 if (trash.len > trash.size)
4837 return 0;
4838
4839 /* Creates the header string. */
4840 p = trash.str;
4841 memcpy(p, name, name_len);
4842 p += name_len;
4843 *p = ':';
4844 p++;
4845 *p = ' ';
4846 p++;
4847 memcpy(p, value, value_len);
4848
Willy Tarreaueee5b512015-04-03 23:46:31 +02004849 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004850 trash.str, trash.len) != 0);
4851
4852 return 0;
4853}
4854
4855__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4856{
4857 struct hlua_txn *htxn;
4858
4859 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4860 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4861
Willy Tarreaueee5b512015-04-03 23:46:31 +02004862 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004863}
4864
4865__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4866{
4867 struct hlua_txn *htxn;
4868
4869 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4870 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4871
Willy Tarreaueee5b512015-04-03 23:46:31 +02004872 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004873}
4874
4875static int hlua_http_req_set_hdr(lua_State *L)
4876{
4877 struct hlua_txn *htxn;
4878
4879 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4880 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4881
Willy Tarreaueee5b512015-04-03 23:46:31 +02004882 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4883 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004884}
4885
4886static int hlua_http_res_set_hdr(lua_State *L)
4887{
4888 struct hlua_txn *htxn;
4889
4890 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4891 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4892
Willy Tarreaueee5b512015-04-03 23:46:31 +02004893 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4894 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004895}
4896
4897/* This function set the method. */
4898static int hlua_http_req_set_meth(lua_State *L)
4899{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004900 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004901 size_t name_len;
4902 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004903
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004904 /* Check if a valid request is parsed */
4905 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4906 lua_pushboolean(L, 0);
4907 return 1;
4908 }
4909
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004910 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004911 return 1;
4912}
4913
4914/* This function set the method. */
4915static int hlua_http_req_set_path(lua_State *L)
4916{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004917 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004918 size_t name_len;
4919 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004920
4921 /* Check if a valid request is parsed */
4922 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4923 lua_pushboolean(L, 0);
4924 return 1;
4925 }
4926
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004927 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004928 return 1;
4929}
4930
4931/* This function set the query-string. */
4932static int hlua_http_req_set_query(lua_State *L)
4933{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004934 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004935 size_t name_len;
4936 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004937
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004938 /* Check if a valid request is parsed */
4939 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4940 lua_pushboolean(L, 0);
4941 return 1;
4942 }
4943
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004944 /* Check length. */
4945 if (name_len > trash.size - 1) {
4946 lua_pushboolean(L, 0);
4947 return 1;
4948 }
4949
4950 /* Add the mark question as prefix. */
4951 chunk_reset(&trash);
4952 trash.str[trash.len++] = '?';
4953 memcpy(trash.str + trash.len, name, name_len);
4954 trash.len += name_len;
4955
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004956 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004957 return 1;
4958}
4959
4960/* This function set the uri. */
4961static int hlua_http_req_set_uri(lua_State *L)
4962{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004963 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004964 size_t name_len;
4965 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004966
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004967 /* Check if a valid request is parsed */
4968 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4969 lua_pushboolean(L, 0);
4970 return 1;
4971 }
4972
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004973 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004974 return 1;
4975}
4976
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004977/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004978static int hlua_http_res_set_status(lua_State *L)
4979{
4980 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4981 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004982 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004983
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004984 /* Check if a valid response is parsed */
4985 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4986 return 0;
4987
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004988 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004989 return 0;
4990}
4991
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004992/*
4993 *
4994 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004995 * Class TXN
4996 *
4997 *
4998 */
4999
5000/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005001 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005002 */
5003__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5004{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005005 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005006}
5007
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005008__LJMP static int hlua_set_var(lua_State *L)
5009{
5010 struct hlua_txn *htxn;
5011 const char *name;
5012 size_t len;
5013 struct sample smp;
5014
5015 MAY_LJMP(check_args(L, 3, "set_var"));
5016
5017 /* It is useles to retrieve the stream, but this function
5018 * runs only in a stream context.
5019 */
5020 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5021 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5022
5023 /* Converts the third argument in a sample. */
5024 hlua_lua2smp(L, 3, &smp);
5025
5026 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005027 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005028 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005029 return 0;
5030}
5031
Christopher Faulet85d79c92016-11-09 16:54:56 +01005032__LJMP static int hlua_unset_var(lua_State *L)
5033{
5034 struct hlua_txn *htxn;
5035 const char *name;
5036 size_t len;
5037 struct sample smp;
5038
5039 MAY_LJMP(check_args(L, 2, "unset_var"));
5040
5041 /* It is useles to retrieve the stream, but this function
5042 * runs only in a stream context.
5043 */
5044 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5045 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5046
5047 /* Unset the variable. */
5048 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5049 vars_unset_by_name(name, len, &smp);
5050 return 0;
5051}
5052
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005053__LJMP static int hlua_get_var(lua_State *L)
5054{
5055 struct hlua_txn *htxn;
5056 const char *name;
5057 size_t len;
5058 struct sample smp;
5059
5060 MAY_LJMP(check_args(L, 2, "get_var"));
5061
5062 /* It is useles to retrieve the stream, but this function
5063 * runs only in a stream context.
5064 */
5065 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5066 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5067
Willy Tarreau7560dd42016-03-10 16:28:58 +01005068 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005069 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005070 lua_pushnil(L);
5071 return 1;
5072 }
5073
5074 return hlua_smp2lua(L, &smp);
5075}
5076
Willy Tarreau59551662015-03-10 14:23:13 +01005077__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005078{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005079 struct hlua *hlua;
5080
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005081 MAY_LJMP(check_args(L, 2, "set_priv"));
5082
Willy Tarreau87b09662015-04-03 00:22:06 +02005083 /* It is useles to retrieve the stream, but this function
5084 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005085 */
5086 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005087 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005088
5089 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005090 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005091
5092 /* Get and store new value. */
5093 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5094 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5095
5096 return 0;
5097}
5098
Willy Tarreau59551662015-03-10 14:23:13 +01005099__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005100{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005101 struct hlua *hlua;
5102
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005103 MAY_LJMP(check_args(L, 1, "get_priv"));
5104
Willy Tarreau87b09662015-04-03 00:22:06 +02005105 /* It is useles to retrieve the stream, but this function
5106 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005107 */
5108 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005109 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005110
5111 /* Push configuration index in the stack. */
5112 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5113
5114 return 1;
5115}
5116
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005117/* Create stack entry containing a class TXN. This function
5118 * return 0 if the stack does not contains free slots,
5119 * otherwise it returns 1.
5120 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005121static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005122{
Willy Tarreaude491382015-04-06 11:04:28 +02005123 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005124
5125 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005126 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005127 return 0;
5128
5129 /* NOTE: The allocation never fails. The failure
5130 * throw an error, and the function never returns.
5131 * if the throw is not avalaible, the process is aborted.
5132 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005133 /* Create the object: obj[0] = userdata. */
5134 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005135 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005136 lua_rawseti(L, -2, 0);
5137
Willy Tarreaude491382015-04-06 11:04:28 +02005138 htxn->s = s;
5139 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005140 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005141 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005142
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005143 /* Create the "f" field that contains a list of fetches. */
5144 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005145 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005146 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005147 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005148
5149 /* Create the "sf" field that contains a list of stringsafe fetches. */
5150 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005151 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005152 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005153 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005154
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005155 /* Create the "c" field that contains a list of converters. */
5156 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005157 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005158 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005159 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005160
5161 /* Create the "sc" field that contains a list of stringsafe converters. */
5162 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005163 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005164 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005165 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005166
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005167 /* Create the "req" field that contains the request channel object. */
5168 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005169 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005170 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005171 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005172
5173 /* Create the "res" field that contains the response channel object. */
5174 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005175 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005176 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005177 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005178
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005179 /* Creates the HTTP object is the current proxy allows http. */
5180 lua_pushstring(L, "http");
5181 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005182 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005183 return 0;
5184 }
5185 else
5186 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005187 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005188
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005189 /* Pop a class sesison metatable and affect it to the userdata. */
5190 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5191 lua_setmetatable(L, -2);
5192
5193 return 1;
5194}
5195
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005196__LJMP static int hlua_txn_deflog(lua_State *L)
5197{
5198 const char *msg;
5199 struct hlua_txn *htxn;
5200
5201 MAY_LJMP(check_args(L, 2, "deflog"));
5202 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5203 msg = MAY_LJMP(luaL_checkstring(L, 2));
5204
5205 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5206 return 0;
5207}
5208
5209__LJMP static int hlua_txn_log(lua_State *L)
5210{
5211 int level;
5212 const char *msg;
5213 struct hlua_txn *htxn;
5214
5215 MAY_LJMP(check_args(L, 3, "log"));
5216 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5217 level = MAY_LJMP(luaL_checkinteger(L, 2));
5218 msg = MAY_LJMP(luaL_checkstring(L, 3));
5219
5220 if (level < 0 || level >= NB_LOG_LEVELS)
5221 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5222
5223 hlua_sendlog(htxn->s->be, level, msg);
5224 return 0;
5225}
5226
5227__LJMP static int hlua_txn_log_debug(lua_State *L)
5228{
5229 const char *msg;
5230 struct hlua_txn *htxn;
5231
5232 MAY_LJMP(check_args(L, 2, "Debug"));
5233 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5234 msg = MAY_LJMP(luaL_checkstring(L, 2));
5235 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5236 return 0;
5237}
5238
5239__LJMP static int hlua_txn_log_info(lua_State *L)
5240{
5241 const char *msg;
5242 struct hlua_txn *htxn;
5243
5244 MAY_LJMP(check_args(L, 2, "Info"));
5245 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5246 msg = MAY_LJMP(luaL_checkstring(L, 2));
5247 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5248 return 0;
5249}
5250
5251__LJMP static int hlua_txn_log_warning(lua_State *L)
5252{
5253 const char *msg;
5254 struct hlua_txn *htxn;
5255
5256 MAY_LJMP(check_args(L, 2, "Warning"));
5257 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5258 msg = MAY_LJMP(luaL_checkstring(L, 2));
5259 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5260 return 0;
5261}
5262
5263__LJMP static int hlua_txn_log_alert(lua_State *L)
5264{
5265 const char *msg;
5266 struct hlua_txn *htxn;
5267
5268 MAY_LJMP(check_args(L, 2, "Alert"));
5269 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5270 msg = MAY_LJMP(luaL_checkstring(L, 2));
5271 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5272 return 0;
5273}
5274
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005275__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5276{
5277 struct hlua_txn *htxn;
5278 int ll;
5279
5280 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5281 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5282 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5283
5284 if (ll < 0 || ll > 7)
5285 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5286
5287 htxn->s->logs.level = ll;
5288 return 0;
5289}
5290
5291__LJMP static int hlua_txn_set_tos(lua_State *L)
5292{
5293 struct hlua_txn *htxn;
5294 struct connection *cli_conn;
5295 int tos;
5296
5297 MAY_LJMP(check_args(L, 2, "set_tos"));
5298 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5299 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5300
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005301 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005302 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005303
5304 return 0;
5305}
5306
5307__LJMP static int hlua_txn_set_mark(lua_State *L)
5308{
5309#ifdef SO_MARK
5310 struct hlua_txn *htxn;
5311 struct connection *cli_conn;
5312 int mark;
5313
5314 MAY_LJMP(check_args(L, 2, "set_mark"));
5315 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5316 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5317
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005318 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005319 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005320#endif
5321 return 0;
5322}
5323
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005324/* This function is an Lua binding that send pending data
5325 * to the client, and close the stream interface.
5326 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005327__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005328{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005329 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005330 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005331 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005332
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005333 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005334 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005335 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005336
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005337 /* If the flags NOTERM is set, we cannot terminate the http
5338 * session, so we just end the execution of the current
5339 * lua code.
5340 */
5341 if (htxn->flags & HLUA_TXN_NOTERM) {
5342 WILL_LJMP(hlua_done(L));
5343 return 0;
5344 }
5345
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005346 ic = &htxn->s->req;
5347 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005348
Willy Tarreau630ef452015-08-28 10:06:15 +02005349 if (htxn->s->txn) {
5350 /* HTTP mode, let's stay in sync with the stream */
5351 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
5352 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5353 htxn->s->txn->req.sov = 0;
5354 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5355 oc->analysers = AN_RES_HTTP_XFER_BODY;
5356 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5357 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5358
Willy Tarreau630ef452015-08-28 10:06:15 +02005359 /* Note that if we want to support keep-alive, we need
5360 * to bypass the close/shutr_now calls below, but that
5361 * may only be done if the HTTP request was already
5362 * processed and the connection header is known (ie
5363 * not during TCP rules).
5364 */
5365 }
5366
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005367 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005368 channel_abort(ic);
5369 channel_auto_close(ic);
5370 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005371
5372 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005373 channel_auto_read(oc);
5374 channel_auto_close(oc);
5375 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005376
Willy Tarreau0458b082015-08-28 09:40:04 +02005377 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005378
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005379 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005380 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005381 return 0;
5382}
5383
5384__LJMP static int hlua_log(lua_State *L)
5385{
5386 int level;
5387 const char *msg;
5388
5389 MAY_LJMP(check_args(L, 2, "log"));
5390 level = MAY_LJMP(luaL_checkinteger(L, 1));
5391 msg = MAY_LJMP(luaL_checkstring(L, 2));
5392
5393 if (level < 0 || level >= NB_LOG_LEVELS)
5394 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5395
5396 hlua_sendlog(NULL, level, msg);
5397 return 0;
5398}
5399
5400__LJMP static int hlua_log_debug(lua_State *L)
5401{
5402 const char *msg;
5403
5404 MAY_LJMP(check_args(L, 1, "debug"));
5405 msg = MAY_LJMP(luaL_checkstring(L, 1));
5406 hlua_sendlog(NULL, LOG_DEBUG, msg);
5407 return 0;
5408}
5409
5410__LJMP static int hlua_log_info(lua_State *L)
5411{
5412 const char *msg;
5413
5414 MAY_LJMP(check_args(L, 1, "info"));
5415 msg = MAY_LJMP(luaL_checkstring(L, 1));
5416 hlua_sendlog(NULL, LOG_INFO, msg);
5417 return 0;
5418}
5419
5420__LJMP static int hlua_log_warning(lua_State *L)
5421{
5422 const char *msg;
5423
5424 MAY_LJMP(check_args(L, 1, "warning"));
5425 msg = MAY_LJMP(luaL_checkstring(L, 1));
5426 hlua_sendlog(NULL, LOG_WARNING, msg);
5427 return 0;
5428}
5429
5430__LJMP static int hlua_log_alert(lua_State *L)
5431{
5432 const char *msg;
5433
5434 MAY_LJMP(check_args(L, 1, "alert"));
5435 msg = MAY_LJMP(luaL_checkstring(L, 1));
5436 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005437 return 0;
5438}
5439
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005440__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005441{
5442 int wakeup_ms = lua_tointeger(L, -1);
5443 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005444 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005445 return 0;
5446}
5447
5448__LJMP static int hlua_sleep(lua_State *L)
5449{
5450 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005451 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005452
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005453 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005454
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005455 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005456 wakeup_ms = tick_add(now_ms, delay);
5457 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005458
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005459 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5460 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005461}
5462
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005463__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005464{
5465 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005466 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005467
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005468 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005469
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005470 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005471 wakeup_ms = tick_add(now_ms, delay);
5472 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005473
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005474 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5475 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005476}
5477
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005478/* This functionis an LUA binding. it permits to give back
5479 * the hand at the HAProxy scheduler. It is used when the
5480 * LUA processing consumes a lot of time.
5481 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005482__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005483{
5484 return 0;
5485}
5486
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005487__LJMP static int hlua_yield(lua_State *L)
5488{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005489 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5490 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005491}
5492
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005493/* This function change the nice of the currently executed
5494 * task. It is used set low or high priority at the current
5495 * task.
5496 */
Willy Tarreau59551662015-03-10 14:23:13 +01005497__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005498{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005499 struct hlua *hlua;
5500 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005501
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005502 MAY_LJMP(check_args(L, 1, "set_nice"));
5503 hlua = hlua_gethlua(L);
5504 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005505
5506 /* If he task is not set, I'm in a start mode. */
5507 if (!hlua || !hlua->task)
5508 return 0;
5509
5510 if (nice < -1024)
5511 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005512 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005513 nice = 1024;
5514
5515 hlua->task->nice = nice;
5516 return 0;
5517}
5518
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005519/* This function is used as a calback of a task. It is called by the
5520 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5521 * return an E_AGAIN signal, the emmiter of this signal must set a
5522 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005523 *
5524 * Task wrapper are longjmp safe because the only one Lua code
5525 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005526 */
5527static struct task *hlua_process_task(struct task *task)
5528{
5529 struct hlua *hlua = task->context;
5530 enum hlua_exec status;
5531
Christopher Faulet5bc99722018-04-25 10:34:45 +02005532 if (task->thread_mask == MAX_THREADS_MASK)
5533 task_set_affinity(task, tid_bit);
5534
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005535 /* If it is the first call to the task, we must initialize the
5536 * execution timeouts.
5537 */
5538 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005539 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005540
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005541 /* Execute the Lua code. */
5542 status = hlua_ctx_resume(hlua, 1);
5543
5544 switch (status) {
5545 /* finished or yield */
5546 case HLUA_E_OK:
5547 hlua_ctx_destroy(hlua);
5548 task_delete(task);
5549 task_free(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02005550 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005551 break;
5552
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005553 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01005554 notification_gc(&hlua->com);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005555 if (hlua->wake_time != TICK_ETERNITY)
Emeric Brun253e53e2017-10-17 18:58:40 +02005556 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005557 break;
5558
5559 /* finished with error. */
5560 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005561 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005562 hlua_ctx_destroy(hlua);
5563 task_delete(task);
5564 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005565 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005566 break;
5567
5568 case HLUA_E_ERR:
5569 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005570 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005571 hlua_ctx_destroy(hlua);
5572 task_delete(task);
5573 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005574 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005575 break;
5576 }
Emeric Brun253e53e2017-10-17 18:58:40 +02005577 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005578}
5579
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005580/* This function is an LUA binding that register LUA function to be
5581 * executed after the HAProxy configuration parsing and before the
5582 * HAProxy scheduler starts. This function expect only one LUA
5583 * argument that is a function. This function returns nothing, but
5584 * throws if an error is encountered.
5585 */
5586__LJMP static int hlua_register_init(lua_State *L)
5587{
5588 struct hlua_init_function *init;
5589 int ref;
5590
5591 MAY_LJMP(check_args(L, 1, "register_init"));
5592
5593 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5594
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005595 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005596 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005597 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005598
5599 init->function_ref = ref;
5600 LIST_ADDQ(&hlua_init_functions, &init->l);
5601 return 0;
5602}
5603
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005604/* This functio is an LUA binding. It permits to register a task
5605 * executed in parallel of the main HAroxy activity. The task is
5606 * created and it is set in the HAProxy scheduler. It can be called
5607 * from the "init" section, "post init" or during the runtime.
5608 *
5609 * Lua prototype:
5610 *
5611 * <none> core.register_task(<function>)
5612 */
5613static int hlua_register_task(lua_State *L)
5614{
5615 struct hlua *hlua;
5616 struct task *task;
5617 int ref;
5618
5619 MAY_LJMP(check_args(L, 1, "register_task"));
5620
5621 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5622
Willy Tarreaubafbe012017-11-24 17:34:44 +01005623 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005624 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005625 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005626
Emeric Brunc60def82017-09-27 14:59:38 +02005627 task = task_new(MAX_THREADS_MASK);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005628 task->context = hlua;
5629 task->process = hlua_process_task;
5630
5631 if (!hlua_ctx_init(hlua, task))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005632 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005633
5634 /* Restore the function in the stack. */
5635 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5636 hlua->nargs = 0;
5637
5638 /* Schedule task. */
5639 task_schedule(task, now_ms);
5640
5641 return 0;
5642}
5643
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005644/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5645 * doesn't allow "yield" functions because the HAProxy engine cannot
5646 * resume converters.
5647 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005648static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005649{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005650 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005651 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005652 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005653
Willy Tarreaube508f12016-03-10 11:47:01 +01005654 if (!stream)
5655 return 0;
5656
Willy Tarreau87b09662015-04-03 00:22:06 +02005657 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005658 * Lua context can be not initialized. This behavior
5659 * permits to save performances because a systematic
5660 * Lua initialization cause 5% performances loss.
5661 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005662 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005663 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005664 if (!stream->hlua) {
5665 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5666 return 0;
5667 }
5668 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5669 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5670 return 0;
5671 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005672 }
5673
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005674 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005675 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005676
5677 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005678 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5679 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5680 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005681 else
5682 error = "critical error";
5683 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005684 return 0;
5685 }
5686
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005687 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005688 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005689 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005690 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005691 return 0;
5692 }
5693
5694 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005695 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005696
5697 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005698 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005699 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005700 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005701 return 0;
5702 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005703 hlua_smp2lua(stream->hlua->T, smp);
5704 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005705
5706 /* push keywords in the stack. */
5707 if (arg_p) {
5708 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005709 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005710 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005711 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005712 return 0;
5713 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005714 hlua_arg2lua(stream->hlua->T, arg_p);
5715 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005716 }
5717 }
5718
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005719 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005720 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005721
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005722 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005723 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005724 }
5725
5726 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005727 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005728 /* finished. */
5729 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005730 /* If the stack is empty, the function fails. */
5731 if (lua_gettop(stream->hlua->T) <= 0)
5732 return 0;
5733
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005734 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005735 hlua_lua2smp(stream->hlua->T, -1, smp);
5736 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005737 return 1;
5738
5739 /* yield. */
5740 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005741 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005742 return 0;
5743
5744 /* finished with error. */
5745 case HLUA_E_ERRMSG:
5746 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005747 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005748 fcn->name, lua_tostring(stream->hlua->T, -1));
5749 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005750 return 0;
5751
5752 case HLUA_E_ERR:
5753 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005754 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005755
5756 default:
5757 return 0;
5758 }
5759}
5760
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005761/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5762 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005763 * resume sample-fetches. This function will be called by the sample
5764 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005765 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005766static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5767 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005768{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005769 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005770 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005771 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005772 const struct chunk msg = { .len = 0 };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005773
Willy Tarreaube508f12016-03-10 11:47:01 +01005774 if (!stream)
5775 return 0;
5776
Willy Tarreau87b09662015-04-03 00:22:06 +02005777 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005778 * Lua context can be not initialized. This behavior
5779 * permits to save performances because a systematic
5780 * Lua initialization cause 5% performances loss.
5781 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005782 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005783 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005784 if (!stream->hlua) {
5785 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5786 return 0;
5787 }
5788 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5789 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5790 return 0;
5791 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005792 }
5793
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005794 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005795
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005796 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005797 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005798
5799 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005800 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5801 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5802 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005803 else
5804 error = "critical error";
5805 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005806 return 0;
5807 }
5808
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005809 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005810 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005811 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005812 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005813 return 0;
5814 }
5815
5816 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005817 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005818
5819 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005820 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005821 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005822 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005823 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005824 return 0;
5825 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005826 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005827
5828 /* push keywords in the stack. */
5829 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5830 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005831 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005832 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005833 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005834 return 0;
5835 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005836 hlua_arg2lua(stream->hlua->T, arg_p);
5837 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005838 }
5839
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005840 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005841 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005842
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005843 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005844 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005845 }
5846
5847 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005848 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005849 /* finished. */
5850 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005851 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005852 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005853 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005854 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005855 /* If the stack is empty, the function fails. */
5856 if (lua_gettop(stream->hlua->T) <= 0)
5857 return 0;
5858
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005859 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005860 hlua_lua2smp(stream->hlua->T, -1, smp);
5861 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005862
5863 /* Set the end of execution flag. */
5864 smp->flags &= ~SMP_F_MAY_CHANGE;
5865 return 1;
5866
5867 /* yield. */
5868 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005869 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005870 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005871 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005872 return 0;
5873
5874 /* finished with error. */
5875 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005876 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005877 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005878 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005879 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005880 fcn->name, lua_tostring(stream->hlua->T, -1));
5881 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005882 return 0;
5883
5884 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005885 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005886 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005887 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005888 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005889
5890 default:
5891 return 0;
5892 }
5893}
5894
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005895/* This function is an LUA binding used for registering
5896 * "sample-conv" functions. It expects a converter name used
5897 * in the haproxy configuration file, and an LUA function.
5898 */
5899__LJMP static int hlua_register_converters(lua_State *L)
5900{
5901 struct sample_conv_kw_list *sck;
5902 const char *name;
5903 int ref;
5904 int len;
5905 struct hlua_function *fcn;
5906
5907 MAY_LJMP(check_args(L, 2, "register_converters"));
5908
5909 /* First argument : converter name. */
5910 name = MAY_LJMP(luaL_checkstring(L, 1));
5911
5912 /* Second argument : lua function. */
5913 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5914
5915 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005916 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005917 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005918 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005919 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005920 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005921 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005922
5923 /* Fill fcn. */
5924 fcn->name = strdup(name);
5925 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005926 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005927 fcn->function_ref = ref;
5928
5929 /* List head */
5930 sck->list.n = sck->list.p = NULL;
5931
5932 /* converter keyword. */
5933 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005934 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005935 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005936 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005937
5938 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5939 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005940 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 +01005941 sck->kw[0].val_args = NULL;
5942 sck->kw[0].in_type = SMP_T_STR;
5943 sck->kw[0].out_type = SMP_T_STR;
5944 sck->kw[0].private = fcn;
5945
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005946 /* Register this new converter */
5947 sample_register_convs(sck);
5948
5949 return 0;
5950}
5951
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005952/* This fucntion is an LUA binding used for registering
5953 * "sample-fetch" functions. It expects a converter name used
5954 * in the haproxy configuration file, and an LUA function.
5955 */
5956__LJMP static int hlua_register_fetches(lua_State *L)
5957{
5958 const char *name;
5959 int ref;
5960 int len;
5961 struct sample_fetch_kw_list *sfk;
5962 struct hlua_function *fcn;
5963
5964 MAY_LJMP(check_args(L, 2, "register_fetches"));
5965
5966 /* First argument : sample-fetch name. */
5967 name = MAY_LJMP(luaL_checkstring(L, 1));
5968
5969 /* Second argument : lua function. */
5970 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5971
5972 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005973 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005974 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005975 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005976 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005977 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005978 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005979
5980 /* Fill fcn. */
5981 fcn->name = strdup(name);
5982 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005983 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005984 fcn->function_ref = ref;
5985
5986 /* List head */
5987 sfk->list.n = sfk->list.p = NULL;
5988
5989 /* sample-fetch keyword. */
5990 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005991 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005992 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005993 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005994
5995 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5996 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005997 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 +01005998 sfk->kw[0].val_args = NULL;
5999 sfk->kw[0].out_type = SMP_T_STR;
6000 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6001 sfk->kw[0].val = 0;
6002 sfk->kw[0].private = fcn;
6003
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006004 /* Register this new fetch. */
6005 sample_register_fetches(sfk);
6006
6007 return 0;
6008}
6009
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006010/* This function is a wrapper to execute each LUA function declared
6011 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006012 * return ACT_RET_CONT if the processing is finished (with or without
6013 * error) and return ACT_RET_YIELD if the function must be called again
6014 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006015 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006016static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006017 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006018{
6019 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006020 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006021 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006022 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006023 const struct chunk msg = { .len = 0 };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006024
6025 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01006026 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
6027 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
6028 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
6029 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006030 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006031 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006032 return ACT_RET_CONT;
6033 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006034
Willy Tarreau87b09662015-04-03 00:22:06 +02006035 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006036 * Lua context can be not initialized. This behavior
6037 * permits to save performances because a systematic
6038 * Lua initialization cause 5% performances loss.
6039 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006040 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006041 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006042 if (!s->hlua) {
6043 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6044 rule->arg.hlua_rule->fcn.name);
6045 return ACT_RET_CONT;
6046 }
6047 if (!hlua_ctx_init(s->hlua, s->task)) {
6048 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6049 rule->arg.hlua_rule->fcn.name);
6050 return ACT_RET_CONT;
6051 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006052 }
6053
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006054 consistency_set(s, dir, &s->hlua->cons);
6055
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006056 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006057 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006058
6059 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006060 if (!SET_SAFE_LJMP(s->hlua->T)) {
6061 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6062 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006063 else
6064 error = "critical error";
6065 SEND_ERR(px, "Lua function '%s': %s.\n",
6066 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006067 return ACT_RET_CONT;
6068 }
6069
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006070 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006071 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006072 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006073 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006074 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006075 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006076 }
6077
6078 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006079 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006080
Willy Tarreau87b09662015-04-03 00:22:06 +02006081 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006082 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006083 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006084 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006085 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006086 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006087 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006088 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006089
6090 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006091 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006092 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006093 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006094 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006095 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006096 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006097 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006098 lua_pushstring(s->hlua->T, *arg);
6099 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006100 }
6101
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006102 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006103 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006104
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006105 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006106 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006107 }
6108
6109 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006110 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006111 /* finished. */
6112 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006113 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006114 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006115 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006116 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006117 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006118 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006119 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006120
6121 /* yield. */
6122 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006123 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006124 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006125 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006126 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006127 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006128 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006129 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006130 /* Some actions can be wake up when a "write" event
6131 * is detected on a response channel. This is useful
6132 * only for actions targetted on the requests.
6133 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006134 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006135 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01006136 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006137 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006138 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006139 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006140 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006141 /* We can quit the fcuntion without consistency check
6142 * because HAProxy is not able to manipulate data, it
6143 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006144 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006145
6146 /* finished with error. */
6147 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006148 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006149 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006150 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006151 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006152 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006153 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006154 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6155 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006156 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006157
6158 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006159 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006160 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006161 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006162 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006163 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006164 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006165 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006166
6167 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006168 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006169 }
6170}
6171
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006172struct task *hlua_applet_wakeup(struct task *t)
6173{
6174 struct appctx *ctx = t->context;
6175 struct stream_interface *si = ctx->owner;
6176
6177 /* If the applet is wake up without any expected work, the sheduler
6178 * remove it from the run queue. This flag indicate that the applet
6179 * is waiting for write. If the buffer is full, the main processing
6180 * will send some data and after call the applet, otherwise it call
6181 * the applet ASAP.
6182 */
6183 si_applet_cant_put(si);
6184 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006185 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006186 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006187}
6188
6189static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6190{
6191 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006192 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006193 struct task *task;
6194 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006195 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006196
Willy Tarreaubafbe012017-11-24 17:34:44 +01006197 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006198 if (!hlua) {
6199 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6200 ctx->rule->arg.hlua_rule->fcn.name);
6201 return 0;
6202 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006203 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006204 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006205 ctx->ctx.hlua_apptcp.flags = 0;
6206
6207 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006208 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006209 if (!task) {
6210 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6211 ctx->rule->arg.hlua_rule->fcn.name);
6212 return 0;
6213 }
6214 task->nice = 0;
6215 task->context = ctx;
6216 task->process = hlua_applet_wakeup;
6217 ctx->ctx.hlua_apptcp.task = task;
6218
6219 /* In the execution wrappers linked with a stream, the
6220 * Lua context can be not initialized. This behavior
6221 * permits to save performances because a systematic
6222 * Lua initialization cause 5% performances loss.
6223 */
6224 if (!hlua_ctx_init(hlua, task)) {
6225 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6226 ctx->rule->arg.hlua_rule->fcn.name);
6227 return 0;
6228 }
6229
6230 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006231 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006232
6233 /* The following Lua calls can fail. */
6234 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006235 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6236 error = lua_tostring(hlua->T, -1);
6237 else
6238 error = "critical error";
6239 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6240 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006241 RESET_SAFE_LJMP(hlua->T);
6242 return 0;
6243 }
6244
6245 /* Check stack available size. */
6246 if (!lua_checkstack(hlua->T, 1)) {
6247 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6248 ctx->rule->arg.hlua_rule->fcn.name);
6249 RESET_SAFE_LJMP(hlua->T);
6250 return 0;
6251 }
6252
6253 /* Restore the function in the stack. */
6254 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6255
6256 /* Create and and push object stream in the stack. */
6257 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6258 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6259 ctx->rule->arg.hlua_rule->fcn.name);
6260 RESET_SAFE_LJMP(hlua->T);
6261 return 0;
6262 }
6263 hlua->nargs = 1;
6264
6265 /* push keywords in the stack. */
6266 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6267 if (!lua_checkstack(hlua->T, 1)) {
6268 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6269 ctx->rule->arg.hlua_rule->fcn.name);
6270 RESET_SAFE_LJMP(hlua->T);
6271 return 0;
6272 }
6273 lua_pushstring(hlua->T, *arg);
6274 hlua->nargs++;
6275 }
6276
6277 RESET_SAFE_LJMP(hlua->T);
6278
6279 /* Wakeup the applet ASAP. */
6280 si_applet_cant_get(si);
6281 si_applet_cant_put(si);
6282
6283 return 1;
6284}
6285
6286static void hlua_applet_tcp_fct(struct appctx *ctx)
6287{
6288 struct stream_interface *si = ctx->owner;
6289 struct stream *strm = si_strm(si);
6290 struct channel *res = si_ic(si);
6291 struct act_rule *rule = ctx->rule;
6292 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006293 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006294
6295 /* The applet execution is already done. */
6296 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
6297 return;
6298
6299 /* If the stream is disconnect or closed, ldo nothing. */
6300 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6301 return;
6302
6303 /* Execute the function. */
6304 switch (hlua_ctx_resume(hlua, 1)) {
6305 /* finished. */
6306 case HLUA_E_OK:
6307 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6308
6309 /* log time */
6310 strm->logs.tv_request = now;
6311
6312 /* eat the whole request */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006313 co_skip(si_oc(si), si_ob(si)->o);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006314 res->flags |= CF_READ_NULL;
6315 si_shutr(si);
6316 return;
6317
6318 /* yield. */
6319 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006320 if (hlua->wake_time != TICK_ETERNITY)
6321 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006322 return;
6323
6324 /* finished with error. */
6325 case HLUA_E_ERRMSG:
6326 /* Display log. */
6327 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6328 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6329 lua_pop(hlua->T, 1);
6330 goto error;
6331
6332 case HLUA_E_ERR:
6333 /* Display log. */
6334 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6335 rule->arg.hlua_rule->fcn.name);
6336 goto error;
6337
6338 default:
6339 goto error;
6340 }
6341
6342error:
6343
6344 /* For all other cases, just close the stream. */
6345 si_shutw(si);
6346 si_shutr(si);
6347 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6348}
6349
6350static void hlua_applet_tcp_release(struct appctx *ctx)
6351{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006352 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006353 task_free(ctx->ctx.hlua_apptcp.task);
6354 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006355 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006356 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006357}
6358
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006359/* The function returns 1 if the initialisation is complete, 0 if
6360 * an errors occurs and -1 if more data are required for initializing
6361 * the applet.
6362 */
6363static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6364{
6365 struct stream_interface *si = ctx->owner;
6366 struct channel *req = si_oc(si);
6367 struct http_msg *msg;
6368 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006369 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006370 char **arg;
6371 struct hdr_ctx hdr;
6372 struct task *task;
6373 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006374 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006375
6376 /* Wait for a full HTTP request. */
6377 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6378 if (smp.flags & SMP_F_MAY_CHANGE)
6379 return -1;
6380 return 0;
6381 }
6382 txn = strm->txn;
6383 msg = &txn->req;
6384
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006385 /* We want two things in HTTP mode :
6386 * - enforce server-close mode if we were in keep-alive, so that the
6387 * applet is released after each response ;
6388 * - enable request body transfer to the applet in order to resync
6389 * with the response body.
6390 */
6391 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6392 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006393
Willy Tarreaubafbe012017-11-24 17:34:44 +01006394 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006395 if (!hlua) {
6396 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6397 ctx->rule->arg.hlua_rule->fcn.name);
6398 return 0;
6399 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006400 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006401 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006402 ctx->ctx.hlua_apphttp.left_bytes = -1;
6403 ctx->ctx.hlua_apphttp.flags = 0;
6404
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006405 if (txn->req.flags & HTTP_MSGF_VER_11)
6406 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6407
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006408 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006409 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006410 if (!task) {
6411 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6412 ctx->rule->arg.hlua_rule->fcn.name);
6413 return 0;
6414 }
6415 task->nice = 0;
6416 task->context = ctx;
6417 task->process = hlua_applet_wakeup;
6418 ctx->ctx.hlua_apphttp.task = task;
6419
6420 /* In the execution wrappers linked with a stream, the
6421 * Lua context can be not initialized. This behavior
6422 * permits to save performances because a systematic
6423 * Lua initialization cause 5% performances loss.
6424 */
6425 if (!hlua_ctx_init(hlua, task)) {
6426 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6427 ctx->rule->arg.hlua_rule->fcn.name);
6428 return 0;
6429 }
6430
6431 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006432 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006433
6434 /* The following Lua calls can fail. */
6435 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006436 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6437 error = lua_tostring(hlua->T, -1);
6438 else
6439 error = "critical error";
6440 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6441 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006442 return 0;
6443 }
6444
6445 /* Check stack available size. */
6446 if (!lua_checkstack(hlua->T, 1)) {
6447 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6448 ctx->rule->arg.hlua_rule->fcn.name);
6449 RESET_SAFE_LJMP(hlua->T);
6450 return 0;
6451 }
6452
6453 /* Restore the function in the stack. */
6454 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6455
6456 /* Create and and push object stream in the stack. */
6457 if (!hlua_applet_http_new(hlua->T, ctx)) {
6458 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6459 ctx->rule->arg.hlua_rule->fcn.name);
6460 RESET_SAFE_LJMP(hlua->T);
6461 return 0;
6462 }
6463 hlua->nargs = 1;
6464
6465 /* Look for a 100-continue expected. */
6466 if (msg->flags & HTTP_MSGF_VER_11) {
6467 hdr.idx = 0;
6468 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
6469 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6470 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6471 }
6472
6473 /* push keywords in the stack. */
6474 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6475 if (!lua_checkstack(hlua->T, 1)) {
6476 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6477 ctx->rule->arg.hlua_rule->fcn.name);
6478 RESET_SAFE_LJMP(hlua->T);
6479 return 0;
6480 }
6481 lua_pushstring(hlua->T, *arg);
6482 hlua->nargs++;
6483 }
6484
6485 RESET_SAFE_LJMP(hlua->T);
6486
6487 /* Wakeup the applet when data is ready for read. */
6488 si_applet_cant_get(si);
6489
6490 return 1;
6491}
6492
6493static void hlua_applet_http_fct(struct appctx *ctx)
6494{
6495 struct stream_interface *si = ctx->owner;
6496 struct stream *strm = si_strm(si);
6497 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006498 struct act_rule *rule = ctx->rule;
6499 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006500 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006501 char *blk1;
6502 int len1;
6503 char *blk2;
6504 int len2;
6505 int ret;
6506
6507 /* If the stream is disconnect or closed, ldo nothing. */
6508 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6509 return;
6510
6511 /* Set the currently running flag. */
6512 if (!HLUA_IS_RUNNING(hlua) &&
6513 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6514
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006515 /* Wait for full HTTP analysys. */
6516 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6517 si_applet_cant_get(si);
6518 return;
6519 }
6520
6521 /* Store the max amount of bytes that we can read. */
6522 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6523
6524 /* We need to flush the request header. This left the body
6525 * for the Lua.
6526 */
6527
6528 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006529 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006530 if (ret == -1)
6531 return;
6532
6533 /* No data available, ask for more data. */
6534 if (ret == 1)
6535 len2 = 0;
6536 if (ret == 0)
6537 len1 = 0;
6538 if (len1 + len2 < strm->txn->req.eoh + 2) {
6539 si_applet_cant_get(si);
6540 return;
6541 }
6542
6543 /* skip the requests bytes. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006544 co_skip(si_oc(si), strm->txn->req.eoh + 2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006545 }
6546
6547 /* Executes The applet if it is not done. */
6548 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6549
6550 /* Execute the function. */
6551 switch (hlua_ctx_resume(hlua, 1)) {
6552 /* finished. */
6553 case HLUA_E_OK:
6554 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6555 break;
6556
6557 /* yield. */
6558 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006559 if (hlua->wake_time != TICK_ETERNITY)
6560 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006561 return;
6562
6563 /* finished with error. */
6564 case HLUA_E_ERRMSG:
6565 /* Display log. */
6566 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6567 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6568 lua_pop(hlua->T, 1);
6569 goto error;
6570
6571 case HLUA_E_ERR:
6572 /* Display log. */
6573 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6574 rule->arg.hlua_rule->fcn.name);
6575 goto error;
6576
6577 default:
6578 goto error;
6579 }
6580 }
6581
6582 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6583
6584 /* We must send the final chunk. */
6585 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6586 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6587
6588 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006589 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006590
6591 /* critical error. */
6592 if (ret == -2 || ret == -3) {
6593 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6594 rule->arg.hlua_rule->fcn.name);
6595 goto error;
6596 }
6597
6598 /* no enough space error. */
6599 if (ret == -1) {
6600 si_applet_cant_put(si);
6601 return;
6602 }
6603
6604 /* set the last chunk sent. */
6605 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6606 }
6607
6608 /* close the connection. */
6609
6610 /* status / log */
6611 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6612 strm->logs.tv_request = now;
6613
6614 /* eat the whole request */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006615 co_skip(si_oc(si), si_ob(si)->o);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006616 res->flags |= CF_READ_NULL;
6617 si_shutr(si);
6618
6619 return;
6620 }
6621
6622error:
6623
6624 /* If we are in HTTP mode, and we are not send any
6625 * data, return a 500 server error in best effort:
6626 * if there are no room avalaible in the buffer,
6627 * just close the connection.
6628 */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006629 ci_putblk(res, error_500, strlen(error_500));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006630 if (!(strm->flags & SF_ERR_MASK))
6631 strm->flags |= SF_ERR_RESOURCE;
6632 si_shutw(si);
6633 si_shutr(si);
6634 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6635}
6636
6637static void hlua_applet_http_release(struct appctx *ctx)
6638{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006639 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006640 task_free(ctx->ctx.hlua_apphttp.task);
6641 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006642 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006643 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006644}
6645
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006646/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6647 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006648 *
6649 * This function can fail with an abort() due to an Lua critical error.
6650 * We are in the configuration parsing process of HAProxy, this abort() is
6651 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006652 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006653static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6654 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006655{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006656 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006657 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006658
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006659 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006660 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006661 if (!rule->arg.hlua_rule) {
6662 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006663 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006664 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006665
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006666 /* Memory for arguments. */
6667 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6668 if (!rule->arg.hlua_rule->args) {
6669 memprintf(err, "out of memory error");
6670 return ACT_RET_PRS_ERR;
6671 }
6672
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006673 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006674 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006675
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006676 /* Expect some arguments */
6677 for (i = 0; i < fcn->nargs; i++) {
6678 if (*args[i+1] == '\0') {
6679 memprintf(err, "expect %d arguments", fcn->nargs);
6680 return ACT_RET_PRS_ERR;
6681 }
6682 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6683 if (!rule->arg.hlua_rule->args[i]) {
6684 memprintf(err, "out of memory error");
6685 return ACT_RET_PRS_ERR;
6686 }
6687 (*cur_arg)++;
6688 }
6689 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006690
Thierry FOURNIER42148732015-09-02 17:17:33 +02006691 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006692 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006693 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006694}
6695
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006696static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6697 struct act_rule *rule, char **err)
6698{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006699 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006700
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006701 /* HTTP applets are forbidden in tcp-request rules.
6702 * HTTP applet request requires everything initilized by
6703 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6704 * The applet will be immediately initilized, but its before
6705 * the call of this analyzer.
6706 */
6707 if (rule->from != ACT_F_HTTP_REQ) {
6708 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6709 return ACT_RET_PRS_ERR;
6710 }
6711
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006712 /* Memory for the rule. */
6713 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6714 if (!rule->arg.hlua_rule) {
6715 memprintf(err, "out of memory error");
6716 return ACT_RET_PRS_ERR;
6717 }
6718
6719 /* Reference the Lua function and store the reference. */
6720 rule->arg.hlua_rule->fcn = *fcn;
6721
6722 /* TODO: later accept arguments. */
6723 rule->arg.hlua_rule->args = NULL;
6724
6725 /* Add applet pointer in the rule. */
6726 rule->applet.obj_type = OBJ_TYPE_APPLET;
6727 rule->applet.name = fcn->name;
6728 rule->applet.init = hlua_applet_http_init;
6729 rule->applet.fct = hlua_applet_http_fct;
6730 rule->applet.release = hlua_applet_http_release;
6731 rule->applet.timeout = hlua_timeout_applet;
6732
6733 return ACT_RET_PRS_OK;
6734}
6735
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006736/* This function is an LUA binding used for registering
6737 * "sample-conv" functions. It expects a converter name used
6738 * in the haproxy configuration file, and an LUA function.
6739 */
6740__LJMP static int hlua_register_action(lua_State *L)
6741{
6742 struct action_kw_list *akl;
6743 const char *name;
6744 int ref;
6745 int len;
6746 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006747 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006748
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006749 /* Initialise the number of expected arguments at 0. */
6750 nargs = 0;
6751
6752 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6753 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006754
6755 /* First argument : converter name. */
6756 name = MAY_LJMP(luaL_checkstring(L, 1));
6757
6758 /* Second argument : environment. */
6759 if (lua_type(L, 2) != LUA_TTABLE)
6760 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6761
6762 /* Third argument : lua function. */
6763 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6764
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006765 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6766 if (lua_gettop(L) >= 4)
6767 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6768
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006769 /* browse the second argulent as an array. */
6770 lua_pushnil(L);
6771 while (lua_next(L, 2) != 0) {
6772 if (lua_type(L, -1) != LUA_TSTRING)
6773 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6774
6775 /* Check required environment. Only accepted "http" or "tcp". */
6776 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006777 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006778 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006779 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006780 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006781 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006782 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006783
6784 /* Fill fcn. */
6785 fcn->name = strdup(name);
6786 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006787 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006788 fcn->function_ref = ref;
6789
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006790 /* Set the expected number od arguments. */
6791 fcn->nargs = nargs;
6792
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006793 /* List head */
6794 akl->list.n = akl->list.p = NULL;
6795
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006796 /* action keyword. */
6797 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006798 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006799 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006800 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006801
6802 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6803
6804 akl->kw[0].match_pfx = 0;
6805 akl->kw[0].private = fcn;
6806 akl->kw[0].parse = action_register_lua;
6807
6808 /* select the action registering point. */
6809 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6810 tcp_req_cont_keywords_register(akl);
6811 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6812 tcp_res_cont_keywords_register(akl);
6813 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6814 http_req_keywords_register(akl);
6815 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6816 http_res_keywords_register(akl);
6817 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006818 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006819 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6820 "are expected.", lua_tostring(L, -1)));
6821
6822 /* pop the environment string. */
6823 lua_pop(L, 1);
6824 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006825 return ACT_RET_PRS_OK;
6826}
6827
6828static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6829 struct act_rule *rule, char **err)
6830{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006831 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006832
6833 /* Memory for the rule. */
6834 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6835 if (!rule->arg.hlua_rule) {
6836 memprintf(err, "out of memory error");
6837 return ACT_RET_PRS_ERR;
6838 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006839
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006840 /* Reference the Lua function and store the reference. */
6841 rule->arg.hlua_rule->fcn = *fcn;
6842
6843 /* TODO: later accept arguments. */
6844 rule->arg.hlua_rule->args = NULL;
6845
6846 /* Add applet pointer in the rule. */
6847 rule->applet.obj_type = OBJ_TYPE_APPLET;
6848 rule->applet.name = fcn->name;
6849 rule->applet.init = hlua_applet_tcp_init;
6850 rule->applet.fct = hlua_applet_tcp_fct;
6851 rule->applet.release = hlua_applet_tcp_release;
6852 rule->applet.timeout = hlua_timeout_applet;
6853
6854 return 0;
6855}
6856
6857/* This function is an LUA binding used for registering
6858 * "sample-conv" functions. It expects a converter name used
6859 * in the haproxy configuration file, and an LUA function.
6860 */
6861__LJMP static int hlua_register_service(lua_State *L)
6862{
6863 struct action_kw_list *akl;
6864 const char *name;
6865 const char *env;
6866 int ref;
6867 int len;
6868 struct hlua_function *fcn;
6869
6870 MAY_LJMP(check_args(L, 3, "register_service"));
6871
6872 /* First argument : converter name. */
6873 name = MAY_LJMP(luaL_checkstring(L, 1));
6874
6875 /* Second argument : environment. */
6876 env = MAY_LJMP(luaL_checkstring(L, 2));
6877
6878 /* Third argument : lua function. */
6879 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6880
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006881 /* Allocate and fill the sample fetch keyword struct. */
6882 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6883 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006884 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006885 fcn = calloc(1, sizeof(*fcn));
6886 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006887 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006888
6889 /* Fill fcn. */
6890 len = strlen("<lua.>") + strlen(name) + 1;
6891 fcn->name = calloc(1, len);
6892 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006893 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006894 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6895 fcn->function_ref = ref;
6896
6897 /* List head */
6898 akl->list.n = akl->list.p = NULL;
6899
6900 /* converter keyword. */
6901 len = strlen("lua.") + strlen(name) + 1;
6902 akl->kw[0].kw = calloc(1, len);
6903 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006904 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006905
6906 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6907
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01006908 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006909 if (strcmp(env, "tcp") == 0)
6910 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006911 else if (strcmp(env, "http") == 0)
6912 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006913 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006914 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01006915 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006916
6917 akl->kw[0].match_pfx = 0;
6918 akl->kw[0].private = fcn;
6919
6920 /* End of array. */
6921 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6922
6923 /* Register this new converter */
6924 service_keywords_register(akl);
6925
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006926 return 0;
6927}
6928
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006929/* This function initialises Lua cli handler. It copies the
6930 * arguments in the Lua stack and create channel IO objects.
6931 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006932static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006933{
6934 struct hlua *hlua;
6935 struct hlua_function *fcn;
6936 int i;
6937 const char *error;
6938
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006939 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006940 appctx->ctx.hlua_cli.fcn = private;
6941
Willy Tarreaubafbe012017-11-24 17:34:44 +01006942 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006943 if (!hlua) {
6944 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006945 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006946 }
6947 HLUA_INIT(hlua);
6948 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006949
6950 /* Create task used by signal to wakeup applets.
6951 * We use the same wakeup fonction than the Lua applet_tcp and
6952 * applet_http. It is absolutely compatible.
6953 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006954 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006955 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01006956 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006957 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006958 }
6959 appctx->ctx.hlua_cli.task->nice = 0;
6960 appctx->ctx.hlua_cli.task->context = appctx;
6961 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
6962
6963 /* Initialises the Lua context */
6964 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
6965 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006966 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006967 }
6968
6969 /* The following Lua calls can fail. */
6970 if (!SET_SAFE_LJMP(hlua->T)) {
6971 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6972 error = lua_tostring(hlua->T, -1);
6973 else
6974 error = "critical error";
6975 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
6976 goto error;
6977 }
6978
6979 /* Check stack available size. */
6980 if (!lua_checkstack(hlua->T, 2)) {
6981 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6982 goto error;
6983 }
6984
6985 /* Restore the function in the stack. */
6986 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
6987
6988 /* Once the arguments parsed, the CLI is like an AppletTCP,
6989 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006990 */
6991 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
6992 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6993 goto error;
6994 }
6995 hlua->nargs = 1;
6996
6997 /* push keywords in the stack. */
6998 for (i = 0; *args[i]; i++) {
6999 /* Check stack available size. */
7000 if (!lua_checkstack(hlua->T, 1)) {
7001 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7002 goto error;
7003 }
7004 lua_pushstring(hlua->T, args[i]);
7005 hlua->nargs++;
7006 }
7007
7008 /* We must initialize the execution timeouts. */
7009 hlua->max_time = hlua_timeout_session;
7010
7011 /* At this point the execution is safe. */
7012 RESET_SAFE_LJMP(hlua->T);
7013
7014 /* It's ok */
7015 return 0;
7016
7017 /* It's not ok. */
7018error:
7019 RESET_SAFE_LJMP(hlua->T);
7020 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007021 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007022 return 1;
7023}
7024
7025static int hlua_cli_io_handler_fct(struct appctx *appctx)
7026{
7027 struct hlua *hlua;
7028 struct stream_interface *si;
7029 struct hlua_function *fcn;
7030
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007031 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007032 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007033 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007034
7035 /* If the stream is disconnect or closed, ldo nothing. */
7036 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7037 return 1;
7038
7039 /* Execute the function. */
7040 switch (hlua_ctx_resume(hlua, 1)) {
7041
7042 /* finished. */
7043 case HLUA_E_OK:
7044 return 1;
7045
7046 /* yield. */
7047 case HLUA_E_AGAIN:
7048 /* We want write. */
7049 if (HLUA_IS_WAKERESWR(hlua))
7050 si_applet_cant_put(si);
7051 /* Set the timeout. */
7052 if (hlua->wake_time != TICK_ETERNITY)
7053 task_schedule(hlua->task, hlua->wake_time);
7054 return 0;
7055
7056 /* finished with error. */
7057 case HLUA_E_ERRMSG:
7058 /* Display log. */
7059 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
7060 fcn->name, lua_tostring(hlua->T, -1));
7061 lua_pop(hlua->T, 1);
7062 return 1;
7063
7064 case HLUA_E_ERR:
7065 /* Display log. */
7066 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
7067 fcn->name);
7068 return 1;
7069
7070 default:
7071 return 1;
7072 }
7073
7074 return 1;
7075}
7076
7077static void hlua_cli_io_release_fct(struct appctx *appctx)
7078{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007079 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007080 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007081}
7082
7083/* This function is an LUA binding used for registering
7084 * new keywords in the cli. It expects a list of keywords
7085 * which are the "path". It is limited to 5 keywords. A
7086 * description of the command, a function to be executed
7087 * for the parsing and a function for io handlers.
7088 */
7089__LJMP static int hlua_register_cli(lua_State *L)
7090{
7091 struct cli_kw_list *cli_kws;
7092 const char *message;
7093 int ref_io;
7094 int len;
7095 struct hlua_function *fcn;
7096 int index;
7097 int i;
7098
7099 MAY_LJMP(check_args(L, 3, "register_cli"));
7100
7101 /* First argument : an array of maximum 5 keywords. */
7102 if (!lua_istable(L, 1))
7103 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
7104
7105 /* Second argument : string with contextual message. */
7106 message = MAY_LJMP(luaL_checkstring(L, 2));
7107
7108 /* Third and fourth argument : lua function. */
7109 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
7110
7111 /* Allocate and fill the sample fetch keyword struct. */
7112 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
7113 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007114 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007115 fcn = calloc(1, sizeof(*fcn));
7116 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007117 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007118
7119 /* Fill path. */
7120 index = 0;
7121 lua_pushnil(L);
7122 while(lua_next(L, 1) != 0) {
7123 if (index >= 5)
7124 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
7125 if (lua_type(L, -1) != LUA_TSTRING)
7126 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
7127 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
7128 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007129 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007130 index++;
7131 lua_pop(L, 1);
7132 }
7133
7134 /* Copy help message. */
7135 cli_kws->kw[0].usage = strdup(message);
7136 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007137 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007138
7139 /* Fill fcn io handler. */
7140 len = strlen("<lua.cli>") + 1;
7141 for (i = 0; i < index; i++)
7142 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
7143 fcn->name = calloc(1, len);
7144 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007145 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007146 strncat((char *)fcn->name, "<lua.cli", len);
7147 for (i = 0; i < index; i++) {
7148 strncat((char *)fcn->name, ".", len);
7149 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
7150 }
7151 strncat((char *)fcn->name, ">", len);
7152 fcn->function_ref = ref_io;
7153
7154 /* Fill last entries. */
7155 cli_kws->kw[0].private = fcn;
7156 cli_kws->kw[0].parse = hlua_cli_parse_fct;
7157 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
7158 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
7159
7160 /* Register this new converter */
7161 cli_register_kw(cli_kws);
7162
7163 return 0;
7164}
7165
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007166static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7167 struct proxy *defpx, const char *file, int line,
7168 char **err, unsigned int *timeout)
7169{
7170 const char *error;
7171
7172 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
7173 if (error && *error != '\0') {
7174 memprintf(err, "%s: invalid timeout", args[0]);
7175 return -1;
7176 }
7177 return 0;
7178}
7179
7180static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7181 struct proxy *defpx, const char *file, int line,
7182 char **err)
7183{
7184 return hlua_read_timeout(args, section_type, curpx, defpx,
7185 file, line, err, &hlua_timeout_session);
7186}
7187
7188static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7189 struct proxy *defpx, const char *file, int line,
7190 char **err)
7191{
7192 return hlua_read_timeout(args, section_type, curpx, defpx,
7193 file, line, err, &hlua_timeout_task);
7194}
7195
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007196static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7197 struct proxy *defpx, const char *file, int line,
7198 char **err)
7199{
7200 return hlua_read_timeout(args, section_type, curpx, defpx,
7201 file, line, err, &hlua_timeout_applet);
7202}
7203
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007204static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7205 struct proxy *defpx, const char *file, int line,
7206 char **err)
7207{
7208 char *error;
7209
7210 hlua_nb_instruction = strtoll(args[1], &error, 10);
7211 if (*error != '\0') {
7212 memprintf(err, "%s: invalid number", args[0]);
7213 return -1;
7214 }
7215 return 0;
7216}
7217
Willy Tarreau32f61e22015-03-18 17:54:59 +01007218static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7219 struct proxy *defpx, const char *file, int line,
7220 char **err)
7221{
7222 char *error;
7223
7224 if (*(args[1]) == 0) {
7225 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7226 return -1;
7227 }
7228 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7229 if (*error != '\0') {
7230 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7231 return -1;
7232 }
7233 return 0;
7234}
7235
7236
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007237/* This function is called by the main configuration key "lua-load". It loads and
7238 * execute an lua file during the parsing of the HAProxy configuration file. It is
7239 * the main lua entry point.
7240 *
7241 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7242 * occured, otherwise it returns 0.
7243 *
7244 * In some error case, LUA set an error message in top of the stack. This function
7245 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007246 *
7247 * This function can fail with an abort() due to an Lua critical error.
7248 * We are in the configuration parsing process of HAProxy, this abort() is
7249 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007250 */
7251static int hlua_load(char **args, int section_type, struct proxy *curpx,
7252 struct proxy *defpx, const char *file, int line,
7253 char **err)
7254{
7255 int error;
7256
7257 /* Just load and compile the file. */
7258 error = luaL_loadfile(gL.T, args[1]);
7259 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007260 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007261 lua_pop(gL.T, 1);
7262 return -1;
7263 }
7264
7265 /* If no syntax error where detected, execute the code. */
7266 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7267 switch (error) {
7268 case LUA_OK:
7269 break;
7270 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007271 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007272 lua_pop(gL.T, 1);
7273 return -1;
7274 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007275 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007276 return -1;
7277 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007278 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007279 lua_pop(gL.T, 1);
7280 return -1;
7281 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007282 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007283 lua_pop(gL.T, 1);
7284 return -1;
7285 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007286 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007287 lua_pop(gL.T, 1);
7288 return -1;
7289 }
7290
7291 return 0;
7292}
7293
7294/* configuration keywords declaration */
7295static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007296 { CFG_GLOBAL, "lua-load", hlua_load },
7297 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7298 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007299 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007300 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007301 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007302 { 0, NULL, NULL },
7303}};
7304
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007305/* This function can fail with an abort() due to an Lua critical error.
7306 * We are in the initialisation process of HAProxy, this abort() is
7307 * tolerated.
7308 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007309int hlua_post_init()
7310{
7311 struct hlua_init_function *init;
7312 const char *msg;
7313 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007314 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007315
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007316 /* Call post initialisation function in safe environement. */
7317 if (!SET_SAFE_LJMP(gL.T)) {
7318 if (lua_type(gL.T, -1) == LUA_TSTRING)
7319 error = lua_tostring(gL.T, -1);
7320 else
7321 error = "critical error";
7322 fprintf(stderr, "Lua post-init: %s.\n", error);
7323 exit(1);
7324 }
7325 hlua_fcn_post_init(gL.T);
7326 RESET_SAFE_LJMP(gL.T);
7327
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007328 list_for_each_entry(init, &hlua_init_functions, l) {
7329 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7330 ret = hlua_ctx_resume(&gL, 0);
7331 switch (ret) {
7332 case HLUA_E_OK:
7333 lua_pop(gL.T, -1);
7334 return 1;
7335 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007336 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007337 return 0;
7338 case HLUA_E_ERRMSG:
7339 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01007340 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007341 return 0;
7342 case HLUA_E_ERR:
7343 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007344 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007345 return 0;
7346 }
7347 }
7348 return 1;
7349}
7350
Willy Tarreau32f61e22015-03-18 17:54:59 +01007351/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7352 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7353 * is the previously allocated size or the kind of object in case of a new
7354 * allocation. <nsize> is the requested new size.
7355 */
7356static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7357{
7358 struct hlua_mem_allocator *zone = ud;
7359
7360 if (nsize == 0) {
7361 /* it's a free */
7362 if (ptr)
7363 zone->allocated -= osize;
7364 free(ptr);
7365 return NULL;
7366 }
7367
7368 if (!ptr) {
7369 /* it's a new allocation */
7370 if (zone->limit && zone->allocated + nsize > zone->limit)
7371 return NULL;
7372
7373 ptr = malloc(nsize);
7374 if (ptr)
7375 zone->allocated += nsize;
7376 return ptr;
7377 }
7378
7379 /* it's a realloc */
7380 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7381 return NULL;
7382
7383 ptr = realloc(ptr, nsize);
7384 if (ptr)
7385 zone->allocated += nsize - osize;
7386 return ptr;
7387}
7388
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007389/* Ithis function can fail with an abort() due to an Lua critical error.
7390 * We are in the initialisation process of HAProxy, this abort() is
7391 * tolerated.
7392 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007393void hlua_init(void)
7394{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007395 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007396 int idx;
7397 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007398 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007399 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007400 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007401#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007402 struct srv_kw *kw;
7403 int tmp_error;
7404 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007405 char *args[] = { /* SSL client configuration. */
7406 "ssl",
7407 "verify",
7408 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007409 NULL
7410 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007411#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007412
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007413 HA_SPIN_INIT(&hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02007414
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007415 /* Initialise struct hlua and com signals pool */
Willy Tarreaubafbe012017-11-24 17:34:44 +01007416 pool_head_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007417
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007418 /* Register configuration keywords. */
7419 cfg_register_keywords(&cfg_kws);
7420
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007421 /* Init main lua stack. */
7422 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007423 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007424 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007425 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007426 hlua_sethlua(&gL);
7427 gL.Tref = LUA_REFNIL;
7428 gL.task = NULL;
7429
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007430 /* From this point, until the end of the initialisation fucntion,
7431 * the Lua function can fail with an abort. We are in the initialisation
7432 * process of HAProxy, this abort() is tolerated.
7433 */
7434
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007435 /* Initialise lua. */
7436 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007437
Thierry Fournier75933d42016-01-21 09:30:18 +01007438 /* Set safe environment for the initialisation. */
7439 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007440 if (lua_type(gL.T, -1) == LUA_TSTRING)
7441 error_msg = lua_tostring(gL.T, -1);
7442 else
7443 error_msg = "critical error";
7444 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007445 exit(1);
7446 }
7447
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007448 /*
7449 *
7450 * Create "core" object.
7451 *
7452 */
7453
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007454 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007455 lua_newtable(gL.T);
7456
7457 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007458 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007459 hlua_class_const_int(gL.T, log_levels[i], i);
7460
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007461 /* Register special functions. */
7462 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007463 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007464 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007465 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007466 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007467 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007468 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007469 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007470 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007471 hlua_class_function(gL.T, "sleep", hlua_sleep);
7472 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007473 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7474 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7475 hlua_class_function(gL.T, "set_map", hlua_set_map);
7476 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007477 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007478 hlua_class_function(gL.T, "log", hlua_log);
7479 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7480 hlua_class_function(gL.T, "Info", hlua_log_info);
7481 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7482 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007483 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007484 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007485
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007486 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007487
7488 /*
7489 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007490 * Register class Map
7491 *
7492 */
7493
7494 /* This table entry is the object "Map" base. */
7495 lua_newtable(gL.T);
7496
7497 /* register pattern types. */
7498 for (i=0; i<PAT_MATCH_NUM; i++)
7499 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007500 for (i=0; i<PAT_MATCH_NUM; i++) {
7501 snprintf(trash.str, trash.size, "_%s", pat_match_names[i]);
7502 hlua_class_const_int(gL.T, trash.str, i);
7503 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007504
7505 /* register constructor. */
7506 hlua_class_function(gL.T, "new", hlua_map_new);
7507
7508 /* Create and fill the metatable. */
7509 lua_newtable(gL.T);
7510
7511 /* Create and fille the __index entry. */
7512 lua_pushstring(gL.T, "__index");
7513 lua_newtable(gL.T);
7514
7515 /* Register . */
7516 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7517 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7518
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007519 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007520
Thierry Fournier45e78d72016-02-19 18:34:46 +01007521 /* Register previous table in the registry with reference and named entry.
7522 * The function hlua_register_metatable() pops the stack, so we
7523 * previously create a copy of the table.
7524 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007525 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007526 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007527
7528 /* Assign the metatable to the mai Map object. */
7529 lua_setmetatable(gL.T, -2);
7530
7531 /* Set a name to the table. */
7532 lua_setglobal(gL.T, "Map");
7533
7534 /*
7535 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007536 * Register class Channel
7537 *
7538 */
7539
7540 /* Create and fill the metatable. */
7541 lua_newtable(gL.T);
7542
7543 /* Create and fille the __index entry. */
7544 lua_pushstring(gL.T, "__index");
7545 lua_newtable(gL.T);
7546
7547 /* Register . */
7548 hlua_class_function(gL.T, "get", hlua_channel_get);
7549 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7550 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7551 hlua_class_function(gL.T, "set", hlua_channel_set);
7552 hlua_class_function(gL.T, "append", hlua_channel_append);
7553 hlua_class_function(gL.T, "send", hlua_channel_send);
7554 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7555 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7556 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007557 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007558
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007559 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007560
7561 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007562 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007563
7564 /*
7565 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007566 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007567 *
7568 */
7569
7570 /* Create and fill the metatable. */
7571 lua_newtable(gL.T);
7572
7573 /* Create and fille the __index entry. */
7574 lua_pushstring(gL.T, "__index");
7575 lua_newtable(gL.T);
7576
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007577 /* Browse existing fetches and create the associated
7578 * object method.
7579 */
7580 sf = NULL;
7581 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7582
7583 /* Dont register the keywork if the arguments check function are
7584 * not safe during the runtime.
7585 */
7586 if ((sf->val_args != NULL) &&
7587 (sf->val_args != val_payload_lv) &&
7588 (sf->val_args != val_hdr))
7589 continue;
7590
7591 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7592 * by an underscore.
7593 */
7594 strncpy(trash.str, sf->kw, trash.size);
7595 trash.str[trash.size - 1] = '\0';
7596 for (p = trash.str; *p; p++)
7597 if (*p == '.' || *p == '-' || *p == '+')
7598 *p = '_';
7599
7600 /* Register the function. */
7601 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007602 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007603 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007604 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007605 }
7606
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007607 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007608
7609 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007610 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007611
7612 /*
7613 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007614 * Register class Converters
7615 *
7616 */
7617
7618 /* Create and fill the metatable. */
7619 lua_newtable(gL.T);
7620
7621 /* Create and fill the __index entry. */
7622 lua_pushstring(gL.T, "__index");
7623 lua_newtable(gL.T);
7624
7625 /* Browse existing converters and create the associated
7626 * object method.
7627 */
7628 sc = NULL;
7629 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7630 /* Dont register the keywork if the arguments check function are
7631 * not safe during the runtime.
7632 */
7633 if (sc->val_args != NULL)
7634 continue;
7635
7636 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7637 * by an underscore.
7638 */
7639 strncpy(trash.str, sc->kw, trash.size);
7640 trash.str[trash.size - 1] = '\0';
7641 for (p = trash.str; *p; p++)
7642 if (*p == '.' || *p == '-' || *p == '+')
7643 *p = '_';
7644
7645 /* Register the function. */
7646 lua_pushstring(gL.T, trash.str);
7647 lua_pushlightuserdata(gL.T, sc);
7648 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007649 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007650 }
7651
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007652 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007653
7654 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007655 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007656
7657 /*
7658 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007659 * Register class HTTP
7660 *
7661 */
7662
7663 /* Create and fill the metatable. */
7664 lua_newtable(gL.T);
7665
7666 /* Create and fille the __index entry. */
7667 lua_pushstring(gL.T, "__index");
7668 lua_newtable(gL.T);
7669
7670 /* Register Lua functions. */
7671 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7672 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7673 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7674 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7675 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7676 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7677 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7678 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7679 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7680 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7681
7682 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7683 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7684 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7685 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7686 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7687 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007688 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007689
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007690 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007691
7692 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007693 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007694
7695 /*
7696 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007697 * Register class AppletTCP
7698 *
7699 */
7700
7701 /* Create and fill the metatable. */
7702 lua_newtable(gL.T);
7703
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007704 /* Create and fille the __index entry. */
7705 lua_pushstring(gL.T, "__index");
7706 lua_newtable(gL.T);
7707
7708 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007709 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7710 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7711 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7712 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7713 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007714 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7715 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7716 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007717
7718 lua_settable(gL.T, -3);
7719
7720 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007721 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007722
7723 /*
7724 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007725 * Register class AppletHTTP
7726 *
7727 */
7728
7729 /* Create and fill the metatable. */
7730 lua_newtable(gL.T);
7731
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007732 /* Create and fille the __index entry. */
7733 lua_pushstring(gL.T, "__index");
7734 lua_newtable(gL.T);
7735
7736 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007737 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7738 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007739 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7740 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7741 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007742 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7743 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7744 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7745 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7746 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7747 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7748
7749 lua_settable(gL.T, -3);
7750
7751 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007752 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007753
7754 /*
7755 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007756 * Register class TXN
7757 *
7758 */
7759
7760 /* Create and fill the metatable. */
7761 lua_newtable(gL.T);
7762
7763 /* Create and fille the __index entry. */
7764 lua_pushstring(gL.T, "__index");
7765 lua_newtable(gL.T);
7766
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007767 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007768 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7769 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007770 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007771 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007772 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007773 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007774 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7775 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7776 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007777 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7778 hlua_class_function(gL.T, "log", hlua_txn_log);
7779 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7780 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7781 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7782 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007783
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007784 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007785
7786 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007787 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007788
7789 /*
7790 *
7791 * Register class Socket
7792 *
7793 */
7794
7795 /* Create and fill the metatable. */
7796 lua_newtable(gL.T);
7797
7798 /* Create and fille the __index entry. */
7799 lua_pushstring(gL.T, "__index");
7800 lua_newtable(gL.T);
7801
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007802#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007803 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007804#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007805 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7806 hlua_class_function(gL.T, "send", hlua_socket_send);
7807 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7808 hlua_class_function(gL.T, "close", hlua_socket_close);
7809 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7810 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7811 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7812 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7813
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007814 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007815
7816 /* Register the garbage collector entry. */
7817 lua_pushstring(gL.T, "__gc");
7818 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007819 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007820
7821 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007822 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007823
7824 /* Proxy and server configuration initialisation. */
7825 memset(&socket_proxy, 0, sizeof(socket_proxy));
7826 init_new_proxy(&socket_proxy);
7827 socket_proxy.parent = NULL;
7828 socket_proxy.last_change = now.tv_sec;
7829 socket_proxy.id = "LUA-SOCKET";
7830 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7831 socket_proxy.maxconn = 0;
7832 socket_proxy.accept = NULL;
7833 socket_proxy.options2 |= PR_O2_INDEPSTR;
7834 socket_proxy.srv = NULL;
7835 socket_proxy.conn_retries = 0;
7836 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7837
7838 /* Init TCP server: unchanged parameters */
7839 memset(&socket_tcp, 0, sizeof(socket_tcp));
7840 socket_tcp.next = NULL;
7841 socket_tcp.proxy = &socket_proxy;
7842 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7843 LIST_INIT(&socket_tcp.actconns);
7844 LIST_INIT(&socket_tcp.pendconns);
Christopher Faulet40a007c2017-07-03 15:41:01 +02007845 socket_tcp.priv_conns = NULL;
7846 socket_tcp.idle_conns = NULL;
7847 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02007848 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007849 socket_tcp.last_change = 0;
7850 socket_tcp.id = "LUA-TCP-CONN";
7851 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7852 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7853 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7854
7855 /* XXX: Copy default parameter from default server,
7856 * but the default server is not initialized.
7857 */
7858 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7859 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7860 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7861 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7862 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7863 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7864 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7865 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7866 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7867 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7868
7869 socket_tcp.check.status = HCHK_STATUS_INI;
7870 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7871 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7872 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7873 socket_tcp.check.server = &socket_tcp;
7874
7875 socket_tcp.agent.status = HCHK_STATUS_INI;
7876 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7877 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7878 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7879 socket_tcp.agent.server = &socket_tcp;
7880
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007881 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007882
7883#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007884 /* Init TCP server: unchanged parameters */
7885 memset(&socket_ssl, 0, sizeof(socket_ssl));
7886 socket_ssl.next = NULL;
7887 socket_ssl.proxy = &socket_proxy;
7888 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7889 LIST_INIT(&socket_ssl.actconns);
7890 LIST_INIT(&socket_ssl.pendconns);
Christopher Faulet40a007c2017-07-03 15:41:01 +02007891 socket_tcp.priv_conns = NULL;
7892 socket_tcp.idle_conns = NULL;
7893 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02007894 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007895 socket_ssl.last_change = 0;
7896 socket_ssl.id = "LUA-SSL-CONN";
7897 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7898 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7899 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7900
7901 /* XXX: Copy default parameter from default server,
7902 * but the default server is not initialized.
7903 */
7904 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7905 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7906 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7907 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7908 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7909 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7910 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7911 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7912 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7913 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7914
7915 socket_ssl.check.status = HCHK_STATUS_INI;
7916 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7917 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7918 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7919 socket_ssl.check.server = &socket_ssl;
7920
7921 socket_ssl.agent.status = HCHK_STATUS_INI;
7922 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7923 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7924 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7925 socket_ssl.agent.server = &socket_ssl;
7926
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007927 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007928 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007929
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007930 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007931 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7932 /*
7933 *
7934 * If the keyword is not known, we can search in the registered
7935 * server keywords. This is usefull to configure special SSL
7936 * features like client certificates and ssl_verify.
7937 *
7938 */
7939 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7940 if (tmp_error != 0) {
7941 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7942 abort(); /* This must be never arrives because the command line
7943 not editable by the user. */
7944 }
7945 idx += kw->skip;
7946 }
7947 }
7948
7949 /* Initialize SSL server. */
Willy Tarreau17d45382016-12-22 21:16:08 +01007950 if (socket_ssl.xprt->prepare_srv)
7951 socket_ssl.xprt->prepare_srv(&socket_ssl);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007952#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007953
7954 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007955}
Willy Tarreaubb57d942016-12-21 19:04:56 +01007956
7957__attribute__((constructor))
7958static void __hlua_init(void)
7959{
7960 char *ptr = NULL;
7961 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
7962 hap_register_build_opts(ptr, 1);
7963}