blob: 370fc7ef34e9bd5e99a218a40feede39c048662a [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 */
sada05ed3302018-05-11 11:48:18 -07001632__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001633{
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 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001639
1640 /* Check if we run on the same thread than the xreator thread.
1641 * We cannot access to the socket if the thread is different.
1642 */
1643 if (socket->tid != tid)
1644 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1645
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001646 peer = xref_get_peer_and_lock(&socket->xref);
1647 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001648 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001649 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001650
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001651 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001652 appctx->ctx.hlua_cosocket.die = 1;
1653 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001654
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001655 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001656 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001657 return 0;
1658}
1659
sada05ed3302018-05-11 11:48:18 -07001660/* The close function calls close_helper.
1661 */
1662__LJMP static int hlua_socket_close(lua_State *L)
1663{
1664 MAY_LJMP(check_args(L, 1, "close"));
1665 return hlua_socket_close_helper(L);
1666}
1667
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001668/* This Lua function assumes that the stack contain three parameters.
1669 * 1 - USERDATA containing a struct socket
1670 * 2 - INTEGER with values of the macro defined below
1671 * If the integer is -1, we must read at most one line.
1672 * If the integer is -2, we ust read all the data until the
1673 * end of the stream.
1674 * If the integer is positive value, we must read a number of
1675 * bytes corresponding to this value.
1676 */
1677#define HLSR_READ_LINE (-1)
1678#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001679__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001680{
1681 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1682 int wanted = lua_tointeger(L, 2);
1683 struct hlua *hlua = hlua_gethlua(L);
1684 struct appctx *appctx;
1685 int len;
1686 int nblk;
1687 char *blk1;
1688 int len1;
1689 char *blk2;
1690 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001691 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001692 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001693 struct stream_interface *si;
1694 struct stream *s;
1695 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001696
1697 /* Check if this lua stack is schedulable. */
1698 if (!hlua || !hlua->task)
1699 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1700 "'frontend', 'backend' or 'task'"));
1701
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001702 /* Check if we run on the same thread than the xreator thread.
1703 * We cannot access to the socket if the thread is different.
1704 */
1705 if (socket->tid != tid)
1706 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1707
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001708 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001709 peer = xref_get_peer_and_lock(&socket->xref);
1710 if (!peer)
1711 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001712 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1713 si = appctx->owner;
1714 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001715
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001716 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001717 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001718 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001719 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001720 if (nblk < 0) /* Connection close. */
1721 goto connection_closed;
1722 if (nblk == 0) /* No data avalaible. */
1723 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001724
1725 /* remove final \r\n. */
1726 if (nblk == 1) {
1727 if (blk1[len1-1] == '\n') {
1728 len1--;
1729 skip_at_end++;
1730 if (blk1[len1-1] == '\r') {
1731 len1--;
1732 skip_at_end++;
1733 }
1734 }
1735 }
1736 else {
1737 if (blk2[len2-1] == '\n') {
1738 len2--;
1739 skip_at_end++;
1740 if (blk2[len2-1] == '\r') {
1741 len2--;
1742 skip_at_end++;
1743 }
1744 }
1745 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001746 }
1747
1748 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001749 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001750 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001751 if (nblk < 0) /* Connection close. */
1752 goto connection_closed;
1753 if (nblk == 0) /* No data avalaible. */
1754 goto connection_empty;
1755 }
1756
1757 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001758 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001759 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001760 if (nblk < 0) /* Connection close. */
1761 goto connection_closed;
1762 if (nblk == 0) /* No data avalaible. */
1763 goto connection_empty;
1764
1765 if (len1 > wanted) {
1766 nblk = 1;
1767 len1 = wanted;
1768 } if (nblk == 2 && len1 + len2 > wanted)
1769 len2 = wanted - len1;
1770 }
1771
1772 len = len1;
1773
1774 luaL_addlstring(&socket->b, blk1, len1);
1775 if (nblk == 2) {
1776 len += len2;
1777 luaL_addlstring(&socket->b, blk2, len2);
1778 }
1779
1780 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001781 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001782
1783 /* Don't wait anything. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001784 stream_int_notify(&s->si[0]);
1785 stream_int_update_applet(&s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001786
1787 /* If the pattern reclaim to read all the data
1788 * in the connection, got out.
1789 */
1790 if (wanted == HLSR_READ_ALL)
1791 goto connection_empty;
1792 else if (wanted >= 0 && len < wanted)
1793 goto connection_empty;
1794
1795 /* Return result. */
1796 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001797 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001798 return 1;
1799
1800connection_closed:
1801
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001802 xref_unlock(&socket->xref, peer);
1803
1804no_peer:
1805
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001806 /* If the buffer containds data. */
1807 if (socket->b.n > 0) {
1808 luaL_pushresult(&socket->b);
1809 return 1;
1810 }
1811 lua_pushnil(L);
1812 lua_pushstring(L, "connection closed.");
1813 return 2;
1814
1815connection_empty:
1816
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001817 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001818 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1819 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001820 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001821 }
1822 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001823 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001824 return 0;
1825}
1826
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001827/* This Lua function gets two parameters. The first one can be string
1828 * or a number. If the string is "*l", the user requires one line. If
1829 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001830 * If the value is a number, the user require a number of bytes equal
1831 * to the value. The default value is "*l" (a line).
1832 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001833 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001834 * integer takes this values:
1835 * -1 : read a line
1836 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001837 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001838 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001839 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001840 * concatenated with the read data.
1841 */
1842__LJMP static int hlua_socket_receive(struct lua_State *L)
1843{
1844 int wanted = HLSR_READ_LINE;
1845 const char *pattern;
1846 int type;
1847 char *error;
1848 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001849 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001850
1851 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1852 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1853
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001854 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001855
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001856 /* Check if we run on the same thread than the xreator thread.
1857 * We cannot access to the socket if the thread is different.
1858 */
1859 if (socket->tid != tid)
1860 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1861
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001862 /* check for pattern. */
1863 if (lua_gettop(L) >= 2) {
1864 type = lua_type(L, 2);
1865 if (type == LUA_TSTRING) {
1866 pattern = lua_tostring(L, 2);
1867 if (strcmp(pattern, "*a") == 0)
1868 wanted = HLSR_READ_ALL;
1869 else if (strcmp(pattern, "*l") == 0)
1870 wanted = HLSR_READ_LINE;
1871 else {
1872 wanted = strtoll(pattern, &error, 10);
1873 if (*error != '\0')
1874 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1875 }
1876 }
1877 else if (type == LUA_TNUMBER) {
1878 wanted = lua_tointeger(L, 2);
1879 if (wanted < 0)
1880 WILL_LJMP(luaL_error(L, "Unsupported size."));
1881 }
1882 }
1883
1884 /* Set pattern. */
1885 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01001886
1887 /* Check if we would replace the top by itself. */
1888 if (lua_gettop(L) != 2)
1889 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001890
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001891 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001892 luaL_buffinit(L, &socket->b);
1893
1894 /* Check prefix. */
1895 if (lua_gettop(L) >= 3) {
1896 if (lua_type(L, 3) != LUA_TSTRING)
1897 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1898 pattern = lua_tolstring(L, 3, &len);
1899 luaL_addlstring(&socket->b, pattern, len);
1900 }
1901
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001902 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001903}
1904
1905/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08001906 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001907 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001908static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001909{
1910 struct hlua_socket *socket;
1911 struct hlua *hlua = hlua_gethlua(L);
1912 struct appctx *appctx;
1913 size_t buf_len;
1914 const char *buf;
1915 int len;
1916 int send_len;
1917 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001918 struct xref *peer;
1919 struct stream_interface *si;
1920 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001921
1922 /* Check if this lua stack is schedulable. */
1923 if (!hlua || !hlua->task)
1924 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1925 "'frontend', 'backend' or 'task'"));
1926
1927 /* Get object */
1928 socket = MAY_LJMP(hlua_checksocket(L, 1));
1929 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001930 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001931
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001932 /* Check if we run on the same thread than the xreator thread.
1933 * We cannot access to the socket if the thread is different.
1934 */
1935 if (socket->tid != tid)
1936 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1937
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001938 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001939 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001940 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001941 lua_pushinteger(L, -1);
1942 return 1;
1943 }
1944 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1945 si = appctx->owner;
1946 s = si_strm(si);
1947
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001948 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001949 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001950 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001951 lua_pushinteger(L, -1);
1952 return 1;
1953 }
1954
1955 /* Update the input buffer data. */
1956 buf += sent;
1957 send_len = buf_len - sent;
1958
1959 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001960 if (sent >= buf_len) {
1961 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001962 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001963 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001964
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001965 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1966 * the request buffer if its not required.
1967 */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001968 if (s->req.buf->size == 0) {
Christopher Faulet33834b12016-12-19 09:29:06 +01001969 appctx = hlua->task->context;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001970 if (!channel_alloc_buffer(&s->req, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01001971 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001972 }
1973
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001974 /* Check for avalaible space. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001975 len = buffer_total_space(s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01001976 if (len <= 0) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001977 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001978 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
1979 xref_unlock(&socket->xref, peer);
Christopher Faulet33834b12016-12-19 09:29:06 +01001980 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001981 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001982 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01001983 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001984
1985 /* send data */
1986 if (len < send_len)
1987 send_len = len;
Willy Tarreau06d80a92017-10-19 14:32:15 +02001988 len = ci_putblk(&s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001989
1990 /* "Not enough space" (-1), "Buffer too little to contain
1991 * the data" (-2) are not expected because the available length
1992 * is tested.
1993 * Other unknown error are also not expected.
1994 */
1995 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001996 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001997 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001998
sada05ed3302018-05-11 11:48:18 -07001999 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002000 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002001 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002002 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002003 return 1;
2004 }
2005
2006 /* update buffers. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002007 stream_int_notify(&s->si[0]);
2008 stream_int_update_applet(&s->si[0]);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002009
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002010 s->req.rex = TICK_ETERNITY;
2011 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002012
2013 /* Update length sent. */
2014 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002015 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002016
2017 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002018 if (sent + len >= buf_len) {
2019 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002020 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002021 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002022
2023hlua_socket_write_yield_return:
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002024 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002025 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002026 return 0;
2027}
2028
2029/* This function initiate the send of data. It just check the input
2030 * parameters and push an integer in the Lua stack that contain the
2031 * amount of data writed in the buffer. This is used by the function
2032 * "hlua_socket_write_yield" that can yield.
2033 *
2034 * The Lua function gets between 3 and 4 parameters. The first one is
2035 * the associated object. The second is a string buffer. The third is
2036 * a facultative integer that represents where is the buffer position
2037 * of the start of the data that can send. The first byte is the
2038 * position "1". The default value is "1". The fourth argument is a
2039 * facultative integer that represents where is the buffer position
2040 * of the end of the data that can send. The default is the last byte.
2041 */
2042static int hlua_socket_send(struct lua_State *L)
2043{
2044 int i;
2045 int j;
2046 const char *buf;
2047 size_t buf_len;
2048
2049 /* Check number of arguments. */
2050 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2051 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2052
2053 /* Get the string. */
2054 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2055
2056 /* Get and check j. */
2057 if (lua_gettop(L) == 4) {
2058 j = MAY_LJMP(luaL_checkinteger(L, 4));
2059 if (j < 0)
2060 j = buf_len + j + 1;
2061 if (j > buf_len)
2062 j = buf_len + 1;
2063 lua_pop(L, 1);
2064 }
2065 else
2066 j = buf_len;
2067
2068 /* Get and check i. */
2069 if (lua_gettop(L) == 3) {
2070 i = MAY_LJMP(luaL_checkinteger(L, 3));
2071 if (i < 0)
2072 i = buf_len + i + 1;
2073 if (i > buf_len)
2074 i = buf_len + 1;
2075 lua_pop(L, 1);
2076 } else
2077 i = 1;
2078
2079 /* Check bth i and j. */
2080 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002081 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002082 return 1;
2083 }
2084 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002085 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002086 return 1;
2087 }
2088 if (i == 0)
2089 i = 1;
2090 if (j == 0)
2091 j = 1;
2092
2093 /* Pop the string. */
2094 lua_pop(L, 1);
2095
2096 /* Update the buffer length. */
2097 buf += i - 1;
2098 buf_len = j - i + 1;
2099 lua_pushlstring(L, buf, buf_len);
2100
2101 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002102 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002103
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002104 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002105}
2106
Willy Tarreau22b0a682015-06-17 19:43:49 +02002107#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002108__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2109{
2110 static char buffer[SOCKET_INFO_MAX_LEN];
2111 int ret;
2112 int len;
2113 char *p;
2114
2115 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2116 if (ret <= 0) {
2117 lua_pushnil(L);
2118 return 1;
2119 }
2120
2121 if (ret == AF_UNIX) {
2122 lua_pushstring(L, buffer+1);
2123 return 1;
2124 }
2125 else if (ret == AF_INET6) {
2126 buffer[0] = '[';
2127 len = strlen(buffer);
2128 buffer[len] = ']';
2129 len++;
2130 buffer[len] = ':';
2131 len++;
2132 p = buffer;
2133 }
2134 else if (ret == AF_INET) {
2135 p = buffer + 1;
2136 len = strlen(p);
2137 p[len] = ':';
2138 len++;
2139 }
2140 else {
2141 lua_pushnil(L);
2142 return 1;
2143 }
2144
2145 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2146 lua_pushnil(L);
2147 return 1;
2148 }
2149
2150 lua_pushstring(L, p);
2151 return 1;
2152}
2153
2154/* Returns information about the peer of the connection. */
2155__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2156{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002157 struct hlua_socket *socket;
2158 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002159 struct xref *peer;
2160 struct appctx *appctx;
2161 struct stream_interface *si;
2162 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002163 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002164
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002165 MAY_LJMP(check_args(L, 1, "getpeername"));
2166
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002167 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002168
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002169 /* Check if we run on the same thread than the xreator thread.
2170 * We cannot access to the socket if the thread is different.
2171 */
2172 if (socket->tid != tid)
2173 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2174
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002175 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002176 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002177 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002178 lua_pushnil(L);
2179 return 1;
2180 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002181 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2182 si = appctx->owner;
2183 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002184
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002185 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002187 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002188 lua_pushnil(L);
2189 return 1;
2190 }
2191
Willy Tarreaua71f6422016-11-16 17:00:14 +01002192 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002193 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002194 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002195 lua_pushnil(L);
2196 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002197 }
2198
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002199 ret = MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2200 xref_unlock(&socket->xref, peer);
2201 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002202}
2203
2204/* Returns information about my connection side. */
2205static int hlua_socket_getsockname(struct lua_State *L)
2206{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002207 struct hlua_socket *socket;
2208 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002209 struct appctx *appctx;
2210 struct xref *peer;
2211 struct stream_interface *si;
2212 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002213 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002214
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002215 MAY_LJMP(check_args(L, 1, "getsockname"));
2216
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002217 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002218
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002219 /* Check if we run on the same thread than the xreator thread.
2220 * We cannot access to the socket if the thread is different.
2221 */
2222 if (socket->tid != tid)
2223 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2224
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002225 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002226 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002227 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002228 lua_pushnil(L);
2229 return 1;
2230 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002231 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2232 si = appctx->owner;
2233 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002234
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002235 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002236 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002237 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002238 lua_pushnil(L);
2239 return 1;
2240 }
2241
Willy Tarreaua71f6422016-11-16 17:00:14 +01002242 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002243 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002244 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002245 lua_pushnil(L);
2246 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002247 }
2248
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002249 ret = hlua_socket_info(L, &conn->addr.from);
2250 xref_unlock(&socket->xref, peer);
2251 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002252}
2253
2254/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002255static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002256 .obj_type = OBJ_TYPE_APPLET,
2257 .name = "<LUA_TCP>",
2258 .fct = hlua_socket_handler,
2259 .release = hlua_socket_release,
2260};
2261
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002262__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002263{
2264 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2265 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002266 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002267 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002268 struct stream_interface *si;
2269 struct stream *s;
2270
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002271 /* Check if we run on the same thread than the xreator thread.
2272 * We cannot access to the socket if the thread is different.
2273 */
2274 if (socket->tid != tid)
2275 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2276
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002277 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002278 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002279 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002280 lua_pushnil(L);
2281 lua_pushstring(L, "Can't connect");
2282 return 2;
2283 }
2284 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2285 si = appctx->owner;
2286 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002287
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002288 /* Check if we run on the same thread than the xreator thread.
2289 * We cannot access to the socket if the thread is different.
2290 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002291 if (socket->tid != tid) {
2292 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002293 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002294 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002295
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002296 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002297 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002298 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002299 lua_pushnil(L);
2300 lua_pushstring(L, "Can't connect");
2301 return 2;
2302 }
2303
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002304 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002305
2306 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002307 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002308 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002309 lua_pushinteger(L, 1);
2310 return 1;
2311 }
2312
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002313 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2314 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002315 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002316 }
2317 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002318 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002319 return 0;
2320}
2321
2322/* This function fail or initite the connection. */
2323__LJMP static int hlua_socket_connect(struct lua_State *L)
2324{
2325 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002326 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002327 const char *ip;
2328 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002329 struct hlua *hlua;
2330 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002331 int low, high;
2332 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002333 struct xref *peer;
2334 struct stream_interface *si;
2335 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002336
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002337 if (lua_gettop(L) < 2)
2338 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002339
2340 /* Get args. */
2341 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002342
2343 /* Check if we run on the same thread than the xreator thread.
2344 * We cannot access to the socket if the thread is different.
2345 */
2346 if (socket->tid != tid)
2347 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2348
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002349 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002350 if (lua_gettop(L) >= 3) {
2351 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002352 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002353
Tim Duesterhus6edab862018-01-06 19:04:45 +01002354 /* Force the ip to end with a colon, to support IPv6 addresses
2355 * that are not enclosed within square brackets.
2356 */
2357 if (port > 0) {
2358 luaL_buffinit(L, &b);
2359 luaL_addstring(&b, ip);
2360 luaL_addchar(&b, ':');
2361 luaL_pushresult(&b);
2362 ip = lua_tolstring(L, lua_gettop(L), NULL);
2363 }
2364 }
2365
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002366 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002367 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002368 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002369 lua_pushnil(L);
2370 return 1;
2371 }
2372 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2373 si = appctx->owner;
2374 s = si_strm(si);
2375
2376 /* Initialise connection. */
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002377 conn = cs_conn(si_alloc_cs(&s->si[1], NULL));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002378 if (!conn) {
2379 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002380 WILL_LJMP(luaL_error(L, "connect: internal error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002381 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002382
Willy Tarreau3adac082015-09-26 17:51:09 +02002383 /* needed for the connection not to be closed */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002384 conn->target = s->target;
Willy Tarreau3adac082015-09-26 17:51:09 +02002385
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002386 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002387 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002388 if (!addr) {
2389 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002390 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002391 }
2392 if (low != high) {
2393 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002394 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002395 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002396 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002397
2398 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002399 if (low == 0) {
2400 if (conn->addr.to.ss_family == AF_INET) {
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_in *)&conn->addr.to)->sin_port = htons(port);
2406 } else if (conn->addr.to.ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002407 if (port == -1) {
2408 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002409 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002410 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002411 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2412 }
2413 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002414
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002415 hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002416 appctx = objt_appctx(s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002417
2418 /* inform the stream that we want to be notified whenever the
2419 * connection completes.
2420 */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002421 si_applet_cant_get(&s->si[0]);
2422 si_applet_cant_put(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002423 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002424
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002425 hlua->flags |= HLUA_MUST_GC;
2426
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002427 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2428 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002429 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002430 }
2431 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002432
2433 task_wakeup(s->task, TASK_WOKEN_INIT);
2434 /* Return yield waiting for connection. */
2435
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002436 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002437
2438 return 0;
2439}
2440
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002441#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002442__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2443{
2444 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002445 struct xref *peer;
2446 struct appctx *appctx;
2447 struct stream_interface *si;
2448 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002449
2450 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2451 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002452
2453 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002454 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002455 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002456 lua_pushnil(L);
2457 return 1;
2458 }
2459 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2460 si = appctx->owner;
2461 s = si_strm(si);
2462
2463 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002464 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002465 return MAY_LJMP(hlua_socket_connect(L));
2466}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002467#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002468
2469__LJMP static int hlua_socket_setoption(struct lua_State *L)
2470{
2471 return 0;
2472}
2473
2474__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2475{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002476 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002477 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002478 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002479 struct xref *peer;
2480 struct appctx *appctx;
2481 struct stream_interface *si;
2482 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002483
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002484 MAY_LJMP(check_args(L, 2, "settimeout"));
2485
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002486 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002487
2488 /* round up for inputs that are fractions and convert to millis */
2489 dtmout = (0.5 + MAY_LJMP(luaL_checknumber(L, 2))) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002490
Thierry Fournier17a921b2018-03-08 09:59:02 +01002491 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002492 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002493 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2494
Mark Lakes56cc1252018-03-27 09:48:06 +02002495 if (dtmout > INT_MAX) /* overflow check */
2496 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d", INT_MAX));
2497
2498 tmout = MS_TO_TICKS((int)dtmout);
2499
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002500 /* Check if we run on the same thread than the xreator thread.
2501 * We cannot access to the socket if the thread is different.
2502 */
2503 if (socket->tid != tid)
2504 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2505
Mark Lakes56cc1252018-03-27 09:48:06 +02002506 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002507 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002508 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002509 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2510 WILL_LJMP(lua_error(L));
2511 return 0;
2512 }
2513 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2514 si = appctx->owner;
2515 s = si_strm(si);
2516
2517 s->req.rto = tmout;
2518 s->req.wto = tmout;
2519 s->res.rto = tmout;
2520 s->res.wto = tmout;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002521 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002522
Thierry Fourniere9636f12018-03-08 09:54:32 +01002523 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002524 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002525}
2526
2527__LJMP static int hlua_socket_new(lua_State *L)
2528{
2529 struct hlua_socket *socket;
2530 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002531 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002532 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002533
2534 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002535 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002536 hlua_pusherror(L, "socket: full stack");
2537 goto out_fail_conf;
2538 }
2539
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002540 /* Create the object: obj[0] = userdata. */
2541 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002542 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002543 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002544 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002545 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002546
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002547 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002548 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002549 hlua_pusherror(L, "socket: uninitialized pools.");
2550 goto out_fail_conf;
2551 }
2552
Willy Tarreau87b09662015-04-03 00:22:06 +02002553 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002554 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2555 lua_setmetatable(L, -2);
2556
Willy Tarreaud420a972015-04-06 00:39:18 +02002557 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002558 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002559 if (!appctx) {
2560 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002561 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002562 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002563
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002564 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002565 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002566 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2567 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002568
Willy Tarreaud420a972015-04-06 00:39:18 +02002569 /* Now create a session, task and stream for this applet */
2570 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2571 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002572 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002573 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002574 }
2575
Willy Tarreau87787ac2017-08-28 16:22:54 +02002576 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002577 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002578 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002579 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002580 }
2581
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002582 /* Initialise cross reference between stream and Lua socket object. */
2583 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002584
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002585 /* Configure "right" stream interface. this "si" is used to connect
2586 * and retrieve data from the server. The connection is initialized
2587 * with the "struct server".
2588 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002589 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002590
2591 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002592 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2593 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002594
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002595 return 1;
2596
Willy Tarreaud420a972015-04-06 00:39:18 +02002597 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002598 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002599 out_fail_sess:
2600 appctx_free(appctx);
2601 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002602 WILL_LJMP(lua_error(L));
2603 return 0;
2604}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002605
2606/*
2607 *
2608 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002609 * Class Channel
2610 *
2611 *
2612 */
2613
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002614/* The state between the channel data and the HTTP parser state can be
2615 * unconsistent, so reset the parser and call it again. Warning, this
2616 * action not revalidate the request and not send a 400 if the modified
2617 * resuest is not valid.
2618 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002619 * This function never fails. The direction is set using dir, which equals
2620 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002621 */
2622static void hlua_resynchonize_proto(struct stream *stream, int dir)
2623{
2624 /* Protocol HTTP. */
2625 if (stream->be->mode == PR_MODE_HTTP) {
2626
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002627 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002628 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002629 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002630 http_txn_reset_res(stream->txn);
2631
2632 if (stream->txn->hdr_idx.v)
2633 hdr_idx_init(&stream->txn->hdr_idx);
2634
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002635 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002636 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002637 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002638 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2639 }
2640}
2641
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002642/* This function is called before the Lua execution. It stores
2643 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002644 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002645static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002646{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002647 c->mode = stream->be->mode;
2648 switch (c->mode) {
2649 case PR_MODE_HTTP:
2650 c->data.http.dir = opt & SMP_OPT_DIR;
2651 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2652 c->data.http.state = stream->txn->req.msg_state;
2653 else
2654 c->data.http.state = stream->txn->rsp.msg_state;
2655 break;
2656 default:
2657 break;
2658 }
2659}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002660
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002661/* This function is called after the Lua execution. it
2662 * returns true if the parser state is consistent, otherwise,
2663 * it return false.
2664 *
2665 * In HTTP mode, the parser state must be in the same state
2666 * or greater when we exit the function. Even if we do a
2667 * control yield. This prevent to break the HTTP message
2668 * from the Lua code.
2669 */
2670static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2671{
2672 if (c->mode != stream->be->mode)
2673 return 0;
2674
2675 switch (c->mode) {
2676 case PR_MODE_HTTP:
2677 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002678 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002679 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2680 return stream->txn->req.msg_state >= c->data.http.state;
2681 else
2682 return stream->txn->rsp.msg_state >= c->data.http.state;
2683 default:
2684 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002685 }
2686 return 1;
2687}
2688
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002689/* Returns the struct hlua_channel join to the class channel in the
2690 * stack entry "ud" or throws an argument error.
2691 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002692__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002693{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002694 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002695}
2696
Willy Tarreau47860ed2015-03-10 14:07:50 +01002697/* Pushes the channel onto the top of the stack. If the stask does not have a
2698 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002699 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002700static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002701{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002702 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002703 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002704 return 0;
2705
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002706 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002707 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002708 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002709
2710 /* Pop a class sesison metatable and affect it to the userdata. */
2711 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2712 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002713 return 1;
2714}
2715
2716/* Duplicate all the data present in the input channel and put it
2717 * in a string LUA variables. Returns -1 and push a nil value in
2718 * the stack if the channel is closed and all the data are consumed,
2719 * returns 0 if no data are available, otherwise it returns the length
2720 * of the builded string.
2721 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002722static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002723{
2724 char *blk1;
2725 char *blk2;
2726 int len1;
2727 int len2;
2728 int ret;
2729 luaL_Buffer b;
2730
Willy Tarreau06d80a92017-10-19 14:32:15 +02002731 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002732 if (unlikely(ret == 0))
2733 return 0;
2734
2735 if (unlikely(ret < 0)) {
2736 lua_pushnil(L);
2737 return -1;
2738 }
2739
2740 luaL_buffinit(L, &b);
2741 luaL_addlstring(&b, blk1, len1);
2742 if (unlikely(ret == 2))
2743 luaL_addlstring(&b, blk2, len2);
2744 luaL_pushresult(&b);
2745
2746 if (unlikely(ret == 2))
2747 return len1 + len2;
2748 return len1;
2749}
2750
2751/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2752 * a yield. This function keep the data in the buffer.
2753 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002754__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002755{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002756 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002757
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002758 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2759
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002760 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002761 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002762 return 1;
2763}
2764
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002765/* Check arguments for the function "hlua_channel_dup_yield". */
2766__LJMP static int hlua_channel_dup(lua_State *L)
2767{
2768 MAY_LJMP(check_args(L, 1, "dup"));
2769 MAY_LJMP(hlua_checkchannel(L, 1));
2770 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2771}
2772
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002773/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2774 * a yield. This function consumes the data in the buffer. It returns
2775 * a string containing the data or a nil pointer if no data are available
2776 * and the channel is closed.
2777 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002778__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002779{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002780 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002781 int ret;
2782
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002783 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002784
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002785 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002786 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002787 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002788
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002789 if (unlikely(ret == -1))
2790 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002791
Willy Tarreau47860ed2015-03-10 14:07:50 +01002792 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002793 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002794 return 1;
2795}
2796
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002797/* Check arguments for the fucntion "hlua_channel_get_yield". */
2798__LJMP static int hlua_channel_get(lua_State *L)
2799{
2800 MAY_LJMP(check_args(L, 1, "get"));
2801 MAY_LJMP(hlua_checkchannel(L, 1));
2802 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2803}
2804
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002805/* This functions consumes and returns one line. If the channel is closed,
2806 * and the last data does not contains a final '\n', the data are returned
2807 * without the final '\n'. When no more data are avalaible, it returns nil
2808 * value.
2809 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002810__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002811{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002812 char *blk1;
2813 char *blk2;
2814 int len1;
2815 int len2;
2816 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002817 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002818 int ret;
2819 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002820
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002821 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2822
Willy Tarreau06d80a92017-10-19 14:32:15 +02002823 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002824 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002825 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002826
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002827 if (ret == -1) {
2828 lua_pushnil(L);
2829 return 1;
2830 }
2831
2832 luaL_buffinit(L, &b);
2833 luaL_addlstring(&b, blk1, len1);
2834 len = len1;
2835 if (unlikely(ret == 2)) {
2836 luaL_addlstring(&b, blk2, len2);
2837 len += len2;
2838 }
2839 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002840 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002841 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002842 return 1;
2843}
2844
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002845/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2846__LJMP static int hlua_channel_getline(lua_State *L)
2847{
2848 MAY_LJMP(check_args(L, 1, "getline"));
2849 MAY_LJMP(hlua_checkchannel(L, 1));
2850 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2851}
2852
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002853/* This function takes a string as input, and append it at the
2854 * input side of channel. If the data is too big, but a space
2855 * is probably available after sending some data, the function
2856 * yield. If the data is bigger than the buffer, or if the
2857 * channel is closed, it returns -1. otherwise, it returns the
2858 * amount of data writed.
2859 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002860__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002861{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002862 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002863 size_t len;
2864 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2865 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2866 int ret;
2867 int max;
2868
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002869 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2870 * the request buffer if its not required.
2871 */
2872 if (chn->buf->size == 0) {
2873 si_applet_cant_put(chn_prod(chn));
2874 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2875 }
2876
Willy Tarreau47860ed2015-03-10 14:07:50 +01002877 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002878 if (max > len - l)
2879 max = len - l;
2880
Willy Tarreau06d80a92017-10-19 14:32:15 +02002881 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002882 if (ret == -2 || ret == -3) {
2883 lua_pushinteger(L, -1);
2884 return 1;
2885 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002886 if (ret == -1) {
2887 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002888 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002889 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002890 l += ret;
2891 lua_pop(L, 1);
2892 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002893 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002894
Willy Tarreau47860ed2015-03-10 14:07:50 +01002895 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2896 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002897 /* There are no space avalaible, and the output buffer is empty.
2898 * in this case, we cannot add more data, so we cannot yield,
2899 * we return the amount of copyied data.
2900 */
2901 return 1;
2902 }
2903 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002904 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002905 return 1;
2906}
2907
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002908/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002909 * of the writed string, or -1 if the channel is closed or if the
2910 * buffer size is too little for the data.
2911 */
2912__LJMP static int hlua_channel_append(lua_State *L)
2913{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002914 size_t len;
2915
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002916 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002917 MAY_LJMP(hlua_checkchannel(L, 1));
2918 MAY_LJMP(luaL_checklstring(L, 2, &len));
2919 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002920 lua_pushinteger(L, 0);
2921
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002922 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002923}
2924
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002925/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002926 * his process by cleaning the buffer. The result is a replacement
2927 * of the current data. It returns the length of the writed string,
2928 * or -1 if the channel is closed or if the buffer size is too
2929 * little for the data.
2930 */
2931__LJMP static int hlua_channel_set(lua_State *L)
2932{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002933 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002934
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002935 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002936 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002937 lua_pushinteger(L, 0);
2938
Willy Tarreau47860ed2015-03-10 14:07:50 +01002939 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002940
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002941 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002942}
2943
2944/* Append data in the output side of the buffer. This data is immediatly
2945 * sent. The fcuntion returns the ammount of data writed. If the buffer
2946 * cannot contains the data, the function yield. The function returns -1
2947 * if the channel is closed.
2948 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002949__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002950{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002951 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002952 size_t len;
2953 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2954 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2955 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002956 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002957
Willy Tarreau47860ed2015-03-10 14:07:50 +01002958 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002959 lua_pushinteger(L, -1);
2960 return 1;
2961 }
2962
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002963 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2964 * the request buffer if its not required.
2965 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002966 if (chn->buf->size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002967 si_applet_cant_put(chn_prod(chn));
2968 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002969 }
2970
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002971 /* the writed data will be immediatly sent, so we can check
2972 * the avalaible space without taking in account the reserve.
2973 * The reserve is guaranted for the processing of incoming
2974 * data, because the buffer will be flushed.
2975 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002976 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002977
2978 /* If there are no space avalaible, and the output buffer is empty.
2979 * in this case, we cannot add more data, so we cannot yield,
2980 * we return the amount of copyied data.
2981 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002982 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002983 return 1;
2984
2985 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002986 if (max > len - l)
2987 max = len - l;
2988
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002989 /* The buffer avalaible size may be not contiguous. This test
2990 * detects a non contiguous buffer and realign it.
2991 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002992 if (bi_space_for_replace(chn->buf) < max)
2993 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002994
2995 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002996 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002997
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002998 /* buffer replace considers that the input part is filled.
2999 * so, I must forward these new data in the output part.
3000 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003001 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003002
3003 l += max;
3004 lua_pop(L, 1);
3005 lua_pushinteger(L, l);
3006
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003007 /* If there are no space avalaible, and the output buffer is empty.
3008 * in this case, we cannot add more data, so we cannot yield,
3009 * we return the amount of copyied data.
3010 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003011 max = chn->buf->size - buffer_len(chn->buf);
3012 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003013 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003014
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003015 if (l < len) {
3016 /* If we are waiting for space in the response buffer, we
3017 * must set the flag WAKERESWR. This flag required the task
3018 * wake up if any activity is detected on the response buffer.
3019 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003020 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003021 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003022 else
3023 HLUA_SET_WAKEREQWR(hlua);
3024 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003025 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003026
3027 return 1;
3028}
3029
3030/* Just a wraper of "_hlua_channel_send". This wrapper permits
3031 * yield the LUA process, and resume it without checking the
3032 * input arguments.
3033 */
3034__LJMP static int hlua_channel_send(lua_State *L)
3035{
3036 MAY_LJMP(check_args(L, 2, "send"));
3037 lua_pushinteger(L, 0);
3038
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003039 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003040}
3041
3042/* This function forward and amount of butes. The data pass from
3043 * the input side of the buffer to the output side, and can be
3044 * forwarded. This function never fails.
3045 *
3046 * The Lua function takes an amount of bytes to be forwarded in
3047 * imput. It returns the number of bytes forwarded.
3048 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003049__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003050{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003051 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003052 int len;
3053 int l;
3054 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003055 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003056
3057 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3058 len = MAY_LJMP(luaL_checkinteger(L, 2));
3059 l = MAY_LJMP(luaL_checkinteger(L, -1));
3060
3061 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01003062 if (max > chn->buf->i)
3063 max = chn->buf->i;
3064 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003065 l += max;
3066
3067 lua_pop(L, 1);
3068 lua_pushinteger(L, l);
3069
3070 /* Check if it miss bytes to forward. */
3071 if (l < len) {
3072 /* The the input channel or the output channel are closed, we
3073 * must return the amount of data forwarded.
3074 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003075 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003076 return 1;
3077
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003078 /* If we are waiting for space data in the response buffer, we
3079 * must set the flag WAKERESWR. This flag required the task
3080 * wake up if any activity is detected on the response buffer.
3081 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003082 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003083 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003084 else
3085 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003086
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003087 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01003088 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003089 }
3090
3091 return 1;
3092}
3093
3094/* Just check the input and prepare the stack for the previous
3095 * function "hlua_channel_forward_yield"
3096 */
3097__LJMP static int hlua_channel_forward(lua_State *L)
3098{
3099 MAY_LJMP(check_args(L, 2, "forward"));
3100 MAY_LJMP(hlua_checkchannel(L, 1));
3101 MAY_LJMP(luaL_checkinteger(L, 2));
3102
3103 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003104 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003105}
3106
3107/* Just returns the number of bytes available in the input
3108 * side of the buffer. This function never fails.
3109 */
3110__LJMP static int hlua_channel_get_in_len(lua_State *L)
3111{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003112 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003113
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003114 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003115 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01003116 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003117 return 1;
3118}
3119
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003120/* Returns true if the channel is full. */
3121__LJMP static int hlua_channel_is_full(lua_State *L)
3122{
3123 struct channel *chn;
3124 int rem;
3125
3126 MAY_LJMP(check_args(L, 1, "is_full"));
3127 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3128
3129 rem = chn->buf->size;
3130 rem -= chn->buf->o; /* Output size */
3131 rem -= chn->buf->i; /* Input size */
3132 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
3133
3134 lua_pushboolean(L, rem <= 0);
3135 return 1;
3136}
3137
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003138/* Just returns the number of bytes available in the output
3139 * side of the buffer. This function never fails.
3140 */
3141__LJMP static int hlua_channel_get_out_len(lua_State *L)
3142{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003143 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003144
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003145 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003146 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01003147 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003148 return 1;
3149}
3150
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003151/*
3152 *
3153 *
3154 * Class Fetches
3155 *
3156 *
3157 */
3158
3159/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003160 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003161 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003162__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003163{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003164 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003165}
3166
3167/* This function creates and push in the stack a fetch object according
3168 * with a current TXN.
3169 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003170static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003171{
Willy Tarreau7073c472015-04-06 11:15:40 +02003172 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003173
3174 /* Check stack size. */
3175 if (!lua_checkstack(L, 3))
3176 return 0;
3177
3178 /* Create the object: obj[0] = userdata.
3179 * Note that the base of the Fetches object is the
3180 * transaction object.
3181 */
3182 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003183 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003184 lua_rawseti(L, -2, 0);
3185
Willy Tarreau7073c472015-04-06 11:15:40 +02003186 hsmp->s = txn->s;
3187 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003188 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003189 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003190
3191 /* Pop a class sesison metatable and affect it to the userdata. */
3192 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3193 lua_setmetatable(L, -2);
3194
3195 return 1;
3196}
3197
3198/* This function is an LUA binding. It is called with each sample-fetch.
3199 * It uses closure argument to store the associated sample-fetch. It
3200 * returns only one argument or throws an error. An error is thrown
3201 * only if an error is encountered during the argument parsing. If
3202 * the "sample-fetch" function fails, nil is returned.
3203 */
3204__LJMP static int hlua_run_sample_fetch(lua_State *L)
3205{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003206 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003207 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003208 struct arg args[ARGM_NBARGS + 1];
3209 int i;
3210 struct sample smp;
3211
3212 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003213 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003214
3215 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003216 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003217
Thierry FOURNIERca988662015-12-20 18:43:03 +01003218 /* Check execution authorization. */
3219 if (f->use & SMP_USE_HTTP_ANY &&
3220 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3221 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3222 "is not available in Lua services", f->kw);
3223 WILL_LJMP(lua_error(L));
3224 }
3225
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003226 /* Get extra arguments. */
3227 for (i = 0; i < lua_gettop(L) - 1; i++) {
3228 if (i >= ARGM_NBARGS)
3229 break;
3230 hlua_lua2arg(L, i + 2, &args[i]);
3231 }
3232 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003233 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003234
3235 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003236 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003237
3238 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003239 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003240 lua_pushfstring(L, "error in arguments");
3241 WILL_LJMP(lua_error(L));
3242 }
3243
3244 /* Initialise the sample. */
3245 memset(&smp, 0, sizeof(smp));
3246
3247 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003248 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003249 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003250 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003251 lua_pushstring(L, "");
3252 else
3253 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003254 return 1;
3255 }
3256
3257 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003258 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003259 hlua_smp2lua_str(L, &smp);
3260 else
3261 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003262 return 1;
3263}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003264
3265/*
3266 *
3267 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003268 * Class Converters
3269 *
3270 *
3271 */
3272
3273/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003274 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003275 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003276__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003277{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003278 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003279}
3280
3281/* This function creates and push in the stack a Converters object
3282 * according with a current TXN.
3283 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003284static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003285{
Willy Tarreau7073c472015-04-06 11:15:40 +02003286 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003287
3288 /* Check stack size. */
3289 if (!lua_checkstack(L, 3))
3290 return 0;
3291
3292 /* Create the object: obj[0] = userdata.
3293 * Note that the base of the Converters object is the
3294 * same than the TXN object.
3295 */
3296 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003297 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003298 lua_rawseti(L, -2, 0);
3299
Willy Tarreau7073c472015-04-06 11:15:40 +02003300 hsmp->s = txn->s;
3301 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003302 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003303 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003304
Willy Tarreau87b09662015-04-03 00:22:06 +02003305 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003306 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3307 lua_setmetatable(L, -2);
3308
3309 return 1;
3310}
3311
3312/* This function is an LUA binding. It is called with each converter.
3313 * It uses closure argument to store the associated converter. It
3314 * returns only one argument or throws an error. An error is thrown
3315 * only if an error is encountered during the argument parsing. If
3316 * the converter function function fails, nil is returned.
3317 */
3318__LJMP static int hlua_run_sample_conv(lua_State *L)
3319{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003320 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003321 struct sample_conv *conv;
3322 struct arg args[ARGM_NBARGS + 1];
3323 int i;
3324 struct sample smp;
3325
3326 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003327 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003328
3329 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003330 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003331
3332 /* Get extra arguments. */
3333 for (i = 0; i < lua_gettop(L) - 2; i++) {
3334 if (i >= ARGM_NBARGS)
3335 break;
3336 hlua_lua2arg(L, i + 3, &args[i]);
3337 }
3338 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003339 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003340
3341 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003342 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003343
3344 /* Run the special args checker. */
3345 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3346 hlua_pusherror(L, "error in arguments");
3347 WILL_LJMP(lua_error(L));
3348 }
3349
3350 /* Initialise the sample. */
3351 if (!hlua_lua2smp(L, 2, &smp)) {
3352 hlua_pusherror(L, "error in the input argument");
3353 WILL_LJMP(lua_error(L));
3354 }
3355
Willy Tarreau1777ea62016-03-10 16:15:46 +01003356 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3357
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003358 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003359 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003360 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003361 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003362 WILL_LJMP(lua_error(L));
3363 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003364 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3365 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003366 hlua_pusherror(L, "error during the input argument casting");
3367 WILL_LJMP(lua_error(L));
3368 }
3369
3370 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003371 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003372 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003373 lua_pushstring(L, "");
3374 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003375 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003376 return 1;
3377 }
3378
3379 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003380 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003381 hlua_smp2lua_str(L, &smp);
3382 else
3383 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003384 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003385}
3386
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003387/*
3388 *
3389 *
3390 * Class AppletTCP
3391 *
3392 *
3393 */
3394
3395/* Returns a struct hlua_txn if the stack entry "ud" is
3396 * a class stream, otherwise it throws an error.
3397 */
3398__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3399{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003400 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003401}
3402
3403/* This function creates and push in the stack an Applet object
3404 * according with a current TXN.
3405 */
3406static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3407{
3408 struct hlua_appctx *appctx;
3409 struct stream_interface *si = ctx->owner;
3410 struct stream *s = si_strm(si);
3411 struct proxy *p = s->be;
3412
3413 /* Check stack size. */
3414 if (!lua_checkstack(L, 3))
3415 return 0;
3416
3417 /* Create the object: obj[0] = userdata.
3418 * Note that the base of the Converters object is the
3419 * same than the TXN object.
3420 */
3421 lua_newtable(L);
3422 appctx = lua_newuserdata(L, sizeof(*appctx));
3423 lua_rawseti(L, -2, 0);
3424 appctx->appctx = ctx;
3425 appctx->htxn.s = s;
3426 appctx->htxn.p = p;
3427
3428 /* Create the "f" field that contains a list of fetches. */
3429 lua_pushstring(L, "f");
3430 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3431 return 0;
3432 lua_settable(L, -3);
3433
3434 /* Create the "sf" field that contains a list of stringsafe fetches. */
3435 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003436 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003437 return 0;
3438 lua_settable(L, -3);
3439
3440 /* Create the "c" field that contains a list of converters. */
3441 lua_pushstring(L, "c");
3442 if (!hlua_converters_new(L, &appctx->htxn, 0))
3443 return 0;
3444 lua_settable(L, -3);
3445
3446 /* Create the "sc" field that contains a list of stringsafe converters. */
3447 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003448 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003449 return 0;
3450 lua_settable(L, -3);
3451
3452 /* Pop a class stream metatable and affect it to the table. */
3453 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3454 lua_setmetatable(L, -2);
3455
3456 return 1;
3457}
3458
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003459__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3460{
3461 struct hlua_appctx *appctx;
3462 struct stream *s;
3463 const char *name;
3464 size_t len;
3465 struct sample smp;
3466
3467 MAY_LJMP(check_args(L, 3, "set_var"));
3468
3469 /* It is useles to retrieve the stream, but this function
3470 * runs only in a stream context.
3471 */
3472 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3473 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3474 s = appctx->htxn.s;
3475
3476 /* Converts the third argument in a sample. */
3477 hlua_lua2smp(L, 3, &smp);
3478
3479 /* Store the sample in a variable. */
3480 smp_set_owner(&smp, s->be, s->sess, s, 0);
3481 vars_set_by_name(name, len, &smp);
3482 return 0;
3483}
3484
3485__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3486{
3487 struct hlua_appctx *appctx;
3488 struct stream *s;
3489 const char *name;
3490 size_t len;
3491 struct sample smp;
3492
3493 MAY_LJMP(check_args(L, 2, "unset_var"));
3494
3495 /* It is useles to retrieve the stream, but this function
3496 * runs only in a stream context.
3497 */
3498 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3499 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3500 s = appctx->htxn.s;
3501
3502 /* Unset the variable. */
3503 smp_set_owner(&smp, s->be, s->sess, s, 0);
3504 vars_unset_by_name(name, len, &smp);
3505 return 0;
3506}
3507
3508__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3509{
3510 struct hlua_appctx *appctx;
3511 struct stream *s;
3512 const char *name;
3513 size_t len;
3514 struct sample smp;
3515
3516 MAY_LJMP(check_args(L, 2, "get_var"));
3517
3518 /* It is useles to retrieve the stream, but this function
3519 * runs only in a stream context.
3520 */
3521 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3522 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3523 s = appctx->htxn.s;
3524
3525 smp_set_owner(&smp, s->be, s->sess, s, 0);
3526 if (!vars_get_by_name(name, len, &smp)) {
3527 lua_pushnil(L);
3528 return 1;
3529 }
3530
3531 return hlua_smp2lua(L, &smp);
3532}
3533
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003534__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3535{
3536 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3537 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003538 struct hlua *hlua;
3539
3540 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003541 if (!s->hlua)
3542 return 0;
3543 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003544
3545 MAY_LJMP(check_args(L, 2, "set_priv"));
3546
3547 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003548 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003549
3550 /* Get and store new value. */
3551 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3552 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3553
3554 return 0;
3555}
3556
3557__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3558{
3559 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3560 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003561 struct hlua *hlua;
3562
3563 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003564 if (!s->hlua) {
3565 lua_pushnil(L);
3566 return 1;
3567 }
3568 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003569
3570 /* Push configuration index in the stack. */
3571 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3572
3573 return 1;
3574}
3575
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003576/* If expected data not yet available, it returns a yield. This function
3577 * consumes the data in the buffer. It returns a string containing the
3578 * data. This string can be empty.
3579 */
3580__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3581{
3582 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3583 struct stream_interface *si = appctx->appctx->owner;
3584 int ret;
3585 char *blk1;
3586 int len1;
3587 char *blk2;
3588 int len2;
3589
3590 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003591 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003592
3593 /* Data not yet avalaible. return yield. */
3594 if (ret == 0) {
3595 si_applet_cant_get(si);
3596 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3597 }
3598
3599 /* End of data: commit the total strings and return. */
3600 if (ret < 0) {
3601 luaL_pushresult(&appctx->b);
3602 return 1;
3603 }
3604
3605 /* Ensure that the block 2 length is usable. */
3606 if (ret == 1)
3607 len2 = 0;
3608
3609 /* dont check the max length read and dont check. */
3610 luaL_addlstring(&appctx->b, blk1, len1);
3611 luaL_addlstring(&appctx->b, blk2, len2);
3612
3613 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003614 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003615 luaL_pushresult(&appctx->b);
3616 return 1;
3617}
3618
3619/* Check arguments for the fucntion "hlua_channel_get_yield". */
3620__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3621{
3622 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3623
3624 /* Initialise the string catenation. */
3625 luaL_buffinit(L, &appctx->b);
3626
3627 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3628}
3629
3630/* If expected data not yet available, it returns a yield. This function
3631 * consumes the data in the buffer. It returns a string containing the
3632 * data. This string can be empty.
3633 */
3634__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3635{
3636 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3637 struct stream_interface *si = appctx->appctx->owner;
3638 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3639 int ret;
3640 char *blk1;
3641 int len1;
3642 char *blk2;
3643 int len2;
3644
3645 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003646 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003647
3648 /* Data not yet avalaible. return yield. */
3649 if (ret == 0) {
3650 si_applet_cant_get(si);
3651 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3652 }
3653
3654 /* End of data: commit the total strings and return. */
3655 if (ret < 0) {
3656 luaL_pushresult(&appctx->b);
3657 return 1;
3658 }
3659
3660 /* Ensure that the block 2 length is usable. */
3661 if (ret == 1)
3662 len2 = 0;
3663
3664 if (len == -1) {
3665
3666 /* If len == -1, catenate all the data avalaile and
3667 * yield because we want to get all the data until
3668 * the end of data stream.
3669 */
3670 luaL_addlstring(&appctx->b, blk1, len1);
3671 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003672 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003673 si_applet_cant_get(si);
3674 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3675
3676 } else {
3677
3678 /* Copy the fisrt block caping to the length required. */
3679 if (len1 > len)
3680 len1 = len;
3681 luaL_addlstring(&appctx->b, blk1, len1);
3682 len -= len1;
3683
3684 /* Copy the second block. */
3685 if (len2 > len)
3686 len2 = len;
3687 luaL_addlstring(&appctx->b, blk2, len2);
3688 len -= len2;
3689
3690 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003691 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003692
3693 /* If we are no other data avalaible, yield waiting for new data. */
3694 if (len > 0) {
3695 lua_pushinteger(L, len);
3696 lua_replace(L, 2);
3697 si_applet_cant_get(si);
3698 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3699 }
3700
3701 /* return the result. */
3702 luaL_pushresult(&appctx->b);
3703 return 1;
3704 }
3705
3706 /* we never executes this */
3707 hlua_pusherror(L, "Lua: internal error");
3708 WILL_LJMP(lua_error(L));
3709 return 0;
3710}
3711
3712/* Check arguments for the fucntion "hlua_channel_get_yield". */
3713__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3714{
3715 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3716 int len = -1;
3717
3718 if (lua_gettop(L) > 2)
3719 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3720 if (lua_gettop(L) >= 2) {
3721 len = MAY_LJMP(luaL_checkinteger(L, 2));
3722 lua_pop(L, 1);
3723 }
3724
3725 /* Confirm or set the required length */
3726 lua_pushinteger(L, len);
3727
3728 /* Initialise the string catenation. */
3729 luaL_buffinit(L, &appctx->b);
3730
3731 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3732}
3733
3734/* Append data in the output side of the buffer. This data is immediatly
3735 * sent. The fcuntion returns the ammount of data writed. If the buffer
3736 * cannot contains the data, the function yield. The function returns -1
3737 * if the channel is closed.
3738 */
3739__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3740{
3741 size_t len;
3742 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3743 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3744 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3745 struct stream_interface *si = appctx->appctx->owner;
3746 struct channel *chn = si_ic(si);
3747 int max;
3748
3749 /* Get the max amount of data which can write as input in the channel. */
3750 max = channel_recv_max(chn);
3751 if (max > (len - l))
3752 max = len - l;
3753
3754 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003755 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003756
3757 /* update counters. */
3758 l += max;
3759 lua_pop(L, 1);
3760 lua_pushinteger(L, l);
3761
3762 /* If some data is not send, declares the situation to the
3763 * applet, and returns a yield.
3764 */
3765 if (l < len) {
3766 si_applet_cant_put(si);
3767 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3768 }
3769
3770 return 1;
3771}
3772
3773/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3774 * yield the LUA process, and resume it without checking the
3775 * input arguments.
3776 */
3777__LJMP static int hlua_applet_tcp_send(lua_State *L)
3778{
3779 MAY_LJMP(check_args(L, 2, "send"));
3780 lua_pushinteger(L, 0);
3781
3782 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3783}
3784
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003785/*
3786 *
3787 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003788 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003789 *
3790 *
3791 */
3792
3793/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003794 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003795 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003796__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003797{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003798 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003799}
3800
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003801/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003802 * according with a current TXN.
3803 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003804static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003805{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003806 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003807 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003808 struct stream_interface *si = ctx->owner;
3809 struct stream *s = si_strm(si);
3810 struct proxy *px = s->be;
3811 struct http_txn *txn = s->txn;
3812 const char *path;
3813 const char *end;
3814 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003815
3816 /* Check stack size. */
3817 if (!lua_checkstack(L, 3))
3818 return 0;
3819
3820 /* Create the object: obj[0] = userdata.
3821 * Note that the base of the Converters object is the
3822 * same than the TXN object.
3823 */
3824 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003825 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003826 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003827 appctx->appctx = ctx;
3828 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003829 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003830 appctx->htxn.s = s;
3831 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003832
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003833 /* Create the "f" field that contains a list of fetches. */
3834 lua_pushstring(L, "f");
3835 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3836 return 0;
3837 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003838
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003839 /* Create the "sf" field that contains a list of stringsafe fetches. */
3840 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003841 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003842 return 0;
3843 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003844
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003845 /* Create the "c" field that contains a list of converters. */
3846 lua_pushstring(L, "c");
3847 if (!hlua_converters_new(L, &appctx->htxn, 0))
3848 return 0;
3849 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003850
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003851 /* Create the "sc" field that contains a list of stringsafe converters. */
3852 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003853 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003854 return 0;
3855 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003856
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003857 /* Stores the request method. */
3858 lua_pushstring(L, "method");
3859 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3860 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003861
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003862 /* Stores the http version. */
3863 lua_pushstring(L, "version");
3864 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3865 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003866
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003867 /* creates an array of headers. hlua_http_get_headers() crates and push
3868 * the array on the top of the stack.
3869 */
3870 lua_pushstring(L, "headers");
3871 htxn.s = s;
3872 htxn.p = px;
3873 htxn.dir = SMP_OPT_DIR_REQ;
3874 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3875 return 0;
3876 lua_settable(L, -3);
3877
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003878 /* Get path and qs */
3879 path = http_get_path(txn);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003880 if (path) {
3881 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3882 p = path;
3883 while (p < end && *p != '?')
3884 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003885
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003886 /* Stores the request path. */
3887 lua_pushstring(L, "path");
3888 lua_pushlstring(L, path, p - path);
3889 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003890
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003891 /* Stores the query string. */
3892 lua_pushstring(L, "qs");
3893 if (*p == '?')
3894 p++;
3895 lua_pushlstring(L, p, end - p);
3896 lua_settable(L, -3);
3897 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003898
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003899 /* Stores the request path. */
3900 lua_pushstring(L, "length");
3901 lua_pushinteger(L, txn->req.body_len);
3902 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003903
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003904 /* Create an array of HTTP request headers. */
3905 lua_pushstring(L, "headers");
3906 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3907 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003908
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003909 /* Create an empty array of HTTP request headers. */
3910 lua_pushstring(L, "response");
3911 lua_newtable(L);
3912 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003913
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003914 /* Pop a class stream metatable and affect it to the table. */
3915 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3916 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003917
3918 return 1;
3919}
3920
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003921__LJMP static int hlua_applet_http_set_var(lua_State *L)
3922{
3923 struct hlua_appctx *appctx;
3924 struct stream *s;
3925 const char *name;
3926 size_t len;
3927 struct sample smp;
3928
3929 MAY_LJMP(check_args(L, 3, "set_var"));
3930
3931 /* It is useles to retrieve the stream, but this function
3932 * runs only in a stream context.
3933 */
3934 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3935 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3936 s = appctx->htxn.s;
3937
3938 /* Converts the third argument in a sample. */
3939 hlua_lua2smp(L, 3, &smp);
3940
3941 /* Store the sample in a variable. */
3942 smp_set_owner(&smp, s->be, s->sess, s, 0);
3943 vars_set_by_name(name, len, &smp);
3944 return 0;
3945}
3946
3947__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3948{
3949 struct hlua_appctx *appctx;
3950 struct stream *s;
3951 const char *name;
3952 size_t len;
3953 struct sample smp;
3954
3955 MAY_LJMP(check_args(L, 2, "unset_var"));
3956
3957 /* It is useles to retrieve the stream, but this function
3958 * runs only in a stream context.
3959 */
3960 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3961 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3962 s = appctx->htxn.s;
3963
3964 /* Unset the variable. */
3965 smp_set_owner(&smp, s->be, s->sess, s, 0);
3966 vars_unset_by_name(name, len, &smp);
3967 return 0;
3968}
3969
3970__LJMP static int hlua_applet_http_get_var(lua_State *L)
3971{
3972 struct hlua_appctx *appctx;
3973 struct stream *s;
3974 const char *name;
3975 size_t len;
3976 struct sample smp;
3977
3978 MAY_LJMP(check_args(L, 2, "get_var"));
3979
3980 /* It is useles to retrieve the stream, but this function
3981 * runs only in a stream context.
3982 */
3983 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3984 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3985 s = appctx->htxn.s;
3986
3987 smp_set_owner(&smp, s->be, s->sess, s, 0);
3988 if (!vars_get_by_name(name, len, &smp)) {
3989 lua_pushnil(L);
3990 return 1;
3991 }
3992
3993 return hlua_smp2lua(L, &smp);
3994}
3995
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003996__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3997{
3998 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3999 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004000 struct hlua *hlua;
4001
4002 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004003 if (!s->hlua)
4004 return 0;
4005 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004006
4007 MAY_LJMP(check_args(L, 2, "set_priv"));
4008
4009 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004010 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004011
4012 /* Get and store new value. */
4013 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4014 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4015
4016 return 0;
4017}
4018
4019__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4020{
4021 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4022 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004023 struct hlua *hlua;
4024
4025 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004026 if (!s->hlua) {
4027 lua_pushnil(L);
4028 return 1;
4029 }
4030 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004031
4032 /* Push configuration index in the stack. */
4033 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4034
4035 return 1;
4036}
4037
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004038/* If expected data not yet available, it returns a yield. This function
4039 * consumes the data in the buffer. It returns a string containing the
4040 * data. This string can be empty.
4041 */
4042__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004043{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004044 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4045 struct stream_interface *si = appctx->appctx->owner;
4046 struct channel *chn = si_ic(si);
4047 int ret;
4048 char *blk1;
4049 int len1;
4050 char *blk2;
4051 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004052
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004053 /* Maybe we cant send a 100-continue ? */
4054 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau06d80a92017-10-19 14:32:15 +02004055 ret = ci_putblk(chn, HTTP_100C, strlen(HTTP_100C));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004056 /* if ret == -2 or -3 the channel closed or the message si too
4057 * big for the buffers. We cant send anything. So, we ignoring
4058 * the error, considers that the 100-continue is sent, and try
4059 * to receive.
4060 * If ret is -1, we dont have room in the buffer, so we yield.
4061 */
4062 if (ret == -1) {
4063 si_applet_cant_put(si);
4064 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4065 }
4066 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4067 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004068
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004069 /* Check for the end of the data. */
4070 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4071 luaL_pushresult(&appctx->b);
4072 return 1;
4073 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004074
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004075 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004076 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004077
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004078 /* Data not yet avalaible. return yield. */
4079 if (ret == 0) {
4080 si_applet_cant_get(si);
4081 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4082 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004083
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004084 /* End of data: commit the total strings and return. */
4085 if (ret < 0) {
4086 luaL_pushresult(&appctx->b);
4087 return 1;
4088 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004089
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004090 /* Ensure that the block 2 length is usable. */
4091 if (ret == 1)
4092 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004093
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004094 /* Copy the fisrt block caping to the length required. */
4095 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4096 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4097 luaL_addlstring(&appctx->b, blk1, len1);
4098 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004099
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004100 /* Copy the second block. */
4101 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4102 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4103 luaL_addlstring(&appctx->b, blk2, len2);
4104 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004105
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004106 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004107 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004108 luaL_pushresult(&appctx->b);
4109 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004110}
4111
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004112/* Check arguments for the fucntion "hlua_channel_get_yield". */
4113__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004114{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004115 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004116
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004117 /* Initialise the string catenation. */
4118 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004119
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004120 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004121}
4122
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004123/* If expected data not yet available, it returns a yield. This function
4124 * consumes the data in the buffer. It returns a string containing the
4125 * data. This string can be empty.
4126 */
4127__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004128{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004129 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4130 struct stream_interface *si = appctx->appctx->owner;
4131 int len = MAY_LJMP(luaL_checkinteger(L, 2));
4132 struct channel *chn = si_ic(si);
4133 int ret;
4134 char *blk1;
4135 int len1;
4136 char *blk2;
4137 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004138
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004139 /* Maybe we cant send a 100-continue ? */
4140 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau06d80a92017-10-19 14:32:15 +02004141 ret = ci_putblk(chn, HTTP_100C, strlen(HTTP_100C));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004142 /* if ret == -2 or -3 the channel closed or the message si too
4143 * big for the buffers. We cant send anything. So, we ignoring
4144 * the error, considers that the 100-continue is sent, and try
4145 * to receive.
4146 * If ret is -1, we dont have room in the buffer, so we yield.
4147 */
4148 if (ret == -1) {
4149 si_applet_cant_put(si);
4150 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4151 }
4152 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4153 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004154
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004155 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004156 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004157
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004158 /* Data not yet avalaible. return yield. */
4159 if (ret == 0) {
4160 si_applet_cant_get(si);
4161 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4162 }
4163
4164 /* End of data: commit the total strings and return. */
4165 if (ret < 0) {
4166 luaL_pushresult(&appctx->b);
4167 return 1;
4168 }
4169
4170 /* Ensure that the block 2 length is usable. */
4171 if (ret == 1)
4172 len2 = 0;
4173
4174 /* Copy the fisrt block caping to the length required. */
4175 if (len1 > len)
4176 len1 = len;
4177 luaL_addlstring(&appctx->b, blk1, len1);
4178 len -= len1;
4179
4180 /* Copy the second block. */
4181 if (len2 > len)
4182 len2 = len;
4183 luaL_addlstring(&appctx->b, blk2, len2);
4184 len -= len2;
4185
4186 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004187 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004188 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4189 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4190
4191 /* If we are no other data avalaible, yield waiting for new data. */
4192 if (len > 0) {
4193 lua_pushinteger(L, len);
4194 lua_replace(L, 2);
4195 si_applet_cant_get(si);
4196 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4197 }
4198
4199 /* return the result. */
4200 luaL_pushresult(&appctx->b);
4201 return 1;
4202}
4203
4204/* Check arguments for the fucntion "hlua_channel_get_yield". */
4205__LJMP static int hlua_applet_http_recv(lua_State *L)
4206{
4207 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4208 int len = -1;
4209
4210 /* Check arguments. */
4211 if (lua_gettop(L) > 2)
4212 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4213 if (lua_gettop(L) >= 2) {
4214 len = MAY_LJMP(luaL_checkinteger(L, 2));
4215 lua_pop(L, 1);
4216 }
4217
4218 /* Check the required length */
4219 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4220 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4221 lua_pushinteger(L, len);
4222
4223 /* Initialise the string catenation. */
4224 luaL_buffinit(L, &appctx->b);
4225
4226 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4227}
4228
4229/* Append data in the output side of the buffer. This data is immediatly
4230 * sent. The fcuntion returns the ammount of data writed. If the buffer
4231 * cannot contains the data, the function yield. The function returns -1
4232 * if the channel is closed.
4233 */
4234__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4235{
4236 size_t len;
4237 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4238 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4239 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4240 struct stream_interface *si = appctx->appctx->owner;
4241 struct channel *chn = si_ic(si);
4242 int max;
4243
4244 /* Get the max amount of data which can write as input in the channel. */
4245 max = channel_recv_max(chn);
4246 if (max > (len - l))
4247 max = len - l;
4248
4249 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004250 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004251
4252 /* update counters. */
4253 l += max;
4254 lua_pop(L, 1);
4255 lua_pushinteger(L, l);
4256
4257 /* If some data is not send, declares the situation to the
4258 * applet, and returns a yield.
4259 */
4260 if (l < len) {
4261 si_applet_cant_put(si);
4262 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
4263 }
4264
4265 return 1;
4266}
4267
4268/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4269 * yield the LUA process, and resume it without checking the
4270 * input arguments.
4271 */
4272__LJMP static int hlua_applet_http_send(lua_State *L)
4273{
4274 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4275 size_t len;
4276 char hex[10];
4277
4278 MAY_LJMP(luaL_checklstring(L, 2, &len));
4279
4280 /* If transfer encoding chunked is selected, we surround the data
4281 * by chunk data.
4282 */
4283 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4284 snprintf(hex, 9, "%x", (unsigned int)len);
4285 lua_pushfstring(L, "%s\r\n", hex);
4286 lua_insert(L, 2); /* swap the last 2 entries. */
4287 lua_pushstring(L, "\r\n");
4288 lua_concat(L, 3);
4289 }
4290
4291 /* This interger is used for followinf the amount of data sent. */
4292 lua_pushinteger(L, 0);
4293
4294 /* We want to send some data. Headers must be sent. */
4295 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4296 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4297 WILL_LJMP(lua_error(L));
4298 }
4299
4300 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4301}
4302
4303__LJMP static int hlua_applet_http_addheader(lua_State *L)
4304{
4305 const char *name;
4306 int ret;
4307
4308 MAY_LJMP(hlua_checkapplet_http(L, 1));
4309 name = MAY_LJMP(luaL_checkstring(L, 2));
4310 MAY_LJMP(luaL_checkstring(L, 3));
4311
4312 /* Push in the stack the "response" entry. */
4313 ret = lua_getfield(L, 1, "response");
4314 if (ret != LUA_TTABLE) {
4315 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4316 "is expected as an array. %s found", lua_typename(L, ret));
4317 WILL_LJMP(lua_error(L));
4318 }
4319
4320 /* check if the header is already registered if it is not
4321 * the case, register it.
4322 */
4323 ret = lua_getfield(L, -1, name);
4324 if (ret == LUA_TNIL) {
4325
4326 /* Entry not found. */
4327 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4328
4329 /* Insert the new header name in the array in the top of the stack.
4330 * It left the new array in the top of the stack.
4331 */
4332 lua_newtable(L);
4333 lua_pushvalue(L, 2);
4334 lua_pushvalue(L, -2);
4335 lua_settable(L, -4);
4336
4337 } else if (ret != LUA_TTABLE) {
4338
4339 /* corruption error. */
4340 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4341 "is expected as an array. %s found", name, lua_typename(L, ret));
4342 WILL_LJMP(lua_error(L));
4343 }
4344
4345 /* Now the top od thestack is an array of values. We push
4346 * the header value as new entry.
4347 */
4348 lua_pushvalue(L, 3);
4349 ret = lua_rawlen(L, -2);
4350 lua_rawseti(L, -2, ret + 1);
4351 lua_pushboolean(L, 1);
4352 return 1;
4353}
4354
4355__LJMP static int hlua_applet_http_status(lua_State *L)
4356{
4357 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4358 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004359 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004360
4361 if (status < 100 || status > 599) {
4362 lua_pushboolean(L, 0);
4363 return 1;
4364 }
4365
4366 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004367 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004368 lua_pushboolean(L, 1);
4369 return 1;
4370}
4371
4372/* We will build the status line and the headers of the HTTP response.
4373 * We will try send at once if its not possible, we give back the hand
4374 * waiting for more room.
4375 */
4376__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4377{
4378 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4379 struct stream_interface *si = appctx->appctx->owner;
4380 struct channel *chn = si_ic(si);
4381 int ret;
4382 size_t len;
4383 const char *msg;
4384
4385 /* Get the message as the first argument on the stack. */
4386 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4387
4388 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004389 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004390
4391 /* if ret == -2 or -3 the channel closed or the message si too
4392 * big for the buffers.
4393 */
4394 if (ret == -2 || ret == -3) {
4395 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4396 WILL_LJMP(lua_error(L));
4397 }
4398
4399 /* If ret is -1, we dont have room in the buffer, so we yield. */
4400 if (ret == -1) {
4401 si_applet_cant_put(si);
4402 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4403 }
4404
4405 /* Headers sent, set the flag. */
4406 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4407 return 0;
4408}
4409
4410__LJMP static int hlua_applet_http_start_response(lua_State *L)
4411{
4412 struct chunk *tmp = get_trash_chunk();
4413 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004414 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02004415 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004416 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02004417 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004418 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004419 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004420 int hdr_chunked = 0;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004421 const char *reason = appctx->appctx->ctx.hlua_apphttp.reason;
4422
4423 if (reason == NULL)
4424 reason = get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004425
4426 /* Use the same http version than the request. */
4427 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004428 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004429 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004430 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004431
4432 /* Get the array associated to the field "response" in the object AppletHTTP. */
4433 lua_pushvalue(L, 0);
4434 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4435 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4436 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4437 WILL_LJMP(lua_error(L));
4438 }
4439
4440 /* Browse the list of headers. */
4441 lua_pushnil(L);
4442 while(lua_next(L, -2) != 0) {
4443
4444 /* We expect a string as -2. */
4445 if (lua_type(L, -2) != LUA_TSTRING) {
4446 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4447 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4448 lua_typename(L, lua_type(L, -2)));
4449 WILL_LJMP(lua_error(L));
4450 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004451 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004452
4453 /* We expect an array as -1. */
4454 if (lua_type(L, -1) != LUA_TTABLE) {
4455 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4456 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4457 name,
4458 lua_typename(L, lua_type(L, -1)));
4459 WILL_LJMP(lua_error(L));
4460 }
4461
4462 /* Browse the table who is on the top of the stack. */
4463 lua_pushnil(L);
4464 while(lua_next(L, -2) != 0) {
4465
4466 /* We expect a number as -2. */
4467 if (lua_type(L, -2) != LUA_TNUMBER) {
4468 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4469 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4470 name,
4471 lua_typename(L, lua_type(L, -2)));
4472 WILL_LJMP(lua_error(L));
4473 }
4474 id = lua_tointeger(L, -2);
4475
4476 /* We expect a string as -2. */
4477 if (lua_type(L, -1) != LUA_TSTRING) {
4478 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4479 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4480 name, id,
4481 lua_typename(L, lua_type(L, -1)));
4482 WILL_LJMP(lua_error(L));
4483 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004484 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004485
4486 /* Catenate a new header. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004487 if (tmp->len + name_len + 2 + value_len + 2 < tmp->size) {
4488 memcpy(tmp->str + tmp->len, name, name_len);
4489 tmp->len += name_len;
4490 tmp->str[tmp->len++] = ':';
4491 tmp->str[tmp->len++] = ' ';
4492
4493 memcpy(tmp->str + tmp->len, value, value_len);
4494 tmp->len += value_len;
4495 tmp->str[tmp->len++] = '\r';
4496 tmp->str[tmp->len++] = '\n';
4497 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004498
4499 /* Protocol checks. */
4500
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004501 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004502 * is done without control. If it contains a bad value,
4503 * the content-length remains negative so that we can
4504 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004505 */
Willy Tarreaua3294632017-08-23 11:24:47 +02004506 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004507 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004508
4509 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004510 if (name_len == 17 && value_len == 7 &&
4511 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004512 strcasecmp("chunked", value) == 0)
4513 hdr_chunked = 1;
4514
4515 /* Remove the array from the stack, and get next element with a remaining string. */
4516 lua_pop(L, 1);
4517 }
4518
4519 /* Remove the array from the stack, and get next element with a remaining string. */
4520 lua_pop(L, 1);
4521 }
4522
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004523 /* If we dont have a content-length set, and the HTTP version is 1.1
4524 * and the status code implies the presence of a message body, we must
4525 * announce a transfer encoding chunked. This is required by haproxy
4526 * for the keepalive compliance. If the applet annouces a transfer-encoding
4527 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004528 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004529 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004530 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
4531 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4532 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4533 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004534 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4535 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4536 }
4537
4538 /* Finalize headers. */
4539 chunk_appendf(tmp, "\r\n");
4540
4541 /* Remove the last entry and the array of headers */
4542 lua_pop(L, 2);
4543
4544 /* Push the headers block. */
4545 lua_pushlstring(L, tmp->str, tmp->len);
4546
4547 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4548}
4549
4550/*
4551 *
4552 *
4553 * Class HTTP
4554 *
4555 *
4556 */
4557
4558/* Returns a struct hlua_txn if the stack entry "ud" is
4559 * a class stream, otherwise it throws an error.
4560 */
4561__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4562{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004563 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004564}
4565
4566/* This function creates and push in the stack a HTTP object
4567 * according with a current TXN.
4568 */
4569static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4570{
4571 struct hlua_txn *htxn;
4572
4573 /* Check stack size. */
4574 if (!lua_checkstack(L, 3))
4575 return 0;
4576
4577 /* Create the object: obj[0] = userdata.
4578 * Note that the base of the Converters object is the
4579 * same than the TXN object.
4580 */
4581 lua_newtable(L);
4582 htxn = lua_newuserdata(L, sizeof(*htxn));
4583 lua_rawseti(L, -2, 0);
4584
4585 htxn->s = txn->s;
4586 htxn->p = txn->p;
4587
4588 /* Pop a class stream metatable and affect it to the table. */
4589 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4590 lua_setmetatable(L, -2);
4591
4592 return 1;
4593}
4594
4595/* This function creates ans returns an array of HTTP headers.
4596 * This function does not fails. It is used as wrapper with the
4597 * 2 following functions.
4598 */
4599__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4600{
4601 const char *cur_ptr, *cur_next, *p;
4602 int old_idx, cur_idx;
4603 struct hdr_idx_elem *cur_hdr;
4604 const char *hn, *hv;
4605 int hnl, hvl;
4606 int type;
4607 const char *in;
4608 char *out;
4609 int len;
4610
4611 /* Create the table. */
4612 lua_newtable(L);
4613
4614 if (!htxn->s->txn)
4615 return 1;
4616
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004617 /* Check if a valid response is parsed */
4618 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4619 return 1;
4620
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004621 /* Build array of headers. */
4622 old_idx = 0;
4623 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4624
4625 while (1) {
4626 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4627 if (!cur_idx)
4628 break;
4629 old_idx = cur_idx;
4630
4631 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4632 cur_ptr = cur_next;
4633 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4634
4635 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4636 * and the next header starts at cur_next. We'll check
4637 * this header in the list as well as against the default
4638 * rule.
4639 */
4640
4641 /* look for ': *'. */
4642 hn = cur_ptr;
4643 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4644 if (p >= cur_ptr+cur_hdr->len)
4645 continue;
4646 hnl = p - hn;
4647 p++;
4648 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4649 p++;
4650 if (p >= cur_ptr+cur_hdr->len)
4651 continue;
4652 hv = p;
4653 hvl = cur_ptr+cur_hdr->len-p;
4654
4655 /* Lowercase the key. Don't check the size of trash, it have
4656 * the size of one buffer and the input data contains in one
4657 * buffer.
4658 */
4659 out = trash.str;
4660 for (in=hn; in<hn+hnl; in++, out++)
4661 *out = tolower(*in);
4662 *out = '\0';
4663
4664 /* Check for existing entry:
4665 * assume that the table is on the top of the stack, and
4666 * push the key in the stack, the function lua_gettable()
4667 * perform the lookup.
4668 */
4669 lua_pushlstring(L, trash.str, hnl);
4670 lua_gettable(L, -2);
4671 type = lua_type(L, -1);
4672
4673 switch (type) {
4674 case LUA_TNIL:
4675 /* Table not found, create it. */
4676 lua_pop(L, 1); /* remove the nil value. */
4677 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4678 lua_newtable(L); /* create and push empty table. */
4679 lua_pushlstring(L, hv, hvl); /* push header value. */
4680 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4681 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4682 break;
4683
4684 case LUA_TTABLE:
4685 /* Entry found: push the value in the table. */
4686 len = lua_rawlen(L, -1);
4687 lua_pushlstring(L, hv, hvl); /* push header value. */
4688 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4689 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4690 break;
4691
4692 default:
4693 /* Other cases are errors. */
4694 hlua_pusherror(L, "internal error during the parsing of headers.");
4695 WILL_LJMP(lua_error(L));
4696 }
4697 }
4698
4699 return 1;
4700}
4701
4702__LJMP static int hlua_http_req_get_headers(lua_State *L)
4703{
4704 struct hlua_txn *htxn;
4705
4706 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4707 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4708
4709 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4710}
4711
4712__LJMP static int hlua_http_res_get_headers(lua_State *L)
4713{
4714 struct hlua_txn *htxn;
4715
4716 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4717 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4718
4719 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4720}
4721
4722/* This function replace full header, or just a value in
4723 * the request or in the response. It is a wrapper fir the
4724 * 4 following functions.
4725 */
4726__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4727 struct http_msg *msg, int action)
4728{
4729 size_t name_len;
4730 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4731 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4732 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4733 struct my_regex re;
4734
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004735 /* Check if a valid response is parsed */
4736 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4737 return 0;
4738
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004739 if (!regex_comp(reg, &re, 1, 1, NULL))
4740 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4741
4742 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4743 regex_free(&re);
4744 return 0;
4745}
4746
4747__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4748{
4749 struct hlua_txn *htxn;
4750
4751 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4752 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4753
4754 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4755}
4756
4757__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4758{
4759 struct hlua_txn *htxn;
4760
4761 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4762 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4763
4764 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4765}
4766
4767__LJMP static int hlua_http_req_rep_val(lua_State *L)
4768{
4769 struct hlua_txn *htxn;
4770
4771 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4772 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4773
4774 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4775}
4776
4777__LJMP static int hlua_http_res_rep_val(lua_State *L)
4778{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004779 struct hlua_txn *htxn;
4780
4781 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4782 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4783
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004784 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004785}
4786
4787/* This function deletes all the occurences of an header.
4788 * It is a wrapper for the 2 following functions.
4789 */
4790__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4791{
4792 size_t len;
4793 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4794 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004795 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004796
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004797 /* Check if a valid response is parsed */
4798 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4799 return 0;
4800
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004801 ctx.idx = 0;
4802 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4803 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4804 return 0;
4805}
4806
4807__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4808{
4809 struct hlua_txn *htxn;
4810
4811 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4812 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4813
Willy Tarreaueee5b512015-04-03 23:46:31 +02004814 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004815}
4816
4817__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4818{
4819 struct hlua_txn *htxn;
4820
4821 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4822 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4823
Willy Tarreaueee5b512015-04-03 23:46:31 +02004824 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004825}
4826
4827/* This function adds an header. It is a wrapper used by
4828 * the 2 following functions.
4829 */
4830__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4831{
4832 size_t name_len;
4833 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4834 size_t value_len;
4835 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4836 char *p;
4837
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004838 /* Check if a valid message is parsed */
4839 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4840 return 0;
4841
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004842 /* Check length. */
4843 trash.len = value_len + name_len + 2;
4844 if (trash.len > trash.size)
4845 return 0;
4846
4847 /* Creates the header string. */
4848 p = trash.str;
4849 memcpy(p, name, name_len);
4850 p += name_len;
4851 *p = ':';
4852 p++;
4853 *p = ' ';
4854 p++;
4855 memcpy(p, value, value_len);
4856
Willy Tarreaueee5b512015-04-03 23:46:31 +02004857 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004858 trash.str, trash.len) != 0);
4859
4860 return 0;
4861}
4862
4863__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4864{
4865 struct hlua_txn *htxn;
4866
4867 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4868 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4869
Willy Tarreaueee5b512015-04-03 23:46:31 +02004870 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004871}
4872
4873__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4874{
4875 struct hlua_txn *htxn;
4876
4877 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4878 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4879
Willy Tarreaueee5b512015-04-03 23:46:31 +02004880 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004881}
4882
4883static int hlua_http_req_set_hdr(lua_State *L)
4884{
4885 struct hlua_txn *htxn;
4886
4887 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4888 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4889
Willy Tarreaueee5b512015-04-03 23:46:31 +02004890 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4891 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004892}
4893
4894static int hlua_http_res_set_hdr(lua_State *L)
4895{
4896 struct hlua_txn *htxn;
4897
4898 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4899 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4900
Willy Tarreaueee5b512015-04-03 23:46:31 +02004901 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4902 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004903}
4904
4905/* This function set the method. */
4906static int hlua_http_req_set_meth(lua_State *L)
4907{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004908 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004909 size_t name_len;
4910 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004911
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004912 /* Check if a valid request is parsed */
4913 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4914 lua_pushboolean(L, 0);
4915 return 1;
4916 }
4917
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004918 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004919 return 1;
4920}
4921
4922/* This function set the method. */
4923static int hlua_http_req_set_path(lua_State *L)
4924{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004925 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004926 size_t name_len;
4927 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004928
4929 /* Check if a valid request is parsed */
4930 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4931 lua_pushboolean(L, 0);
4932 return 1;
4933 }
4934
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004935 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004936 return 1;
4937}
4938
4939/* This function set the query-string. */
4940static int hlua_http_req_set_query(lua_State *L)
4941{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004942 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004943 size_t name_len;
4944 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004945
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004946 /* Check if a valid request is parsed */
4947 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4948 lua_pushboolean(L, 0);
4949 return 1;
4950 }
4951
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004952 /* Check length. */
4953 if (name_len > trash.size - 1) {
4954 lua_pushboolean(L, 0);
4955 return 1;
4956 }
4957
4958 /* Add the mark question as prefix. */
4959 chunk_reset(&trash);
4960 trash.str[trash.len++] = '?';
4961 memcpy(trash.str + trash.len, name, name_len);
4962 trash.len += name_len;
4963
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004964 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004965 return 1;
4966}
4967
4968/* This function set the uri. */
4969static int hlua_http_req_set_uri(lua_State *L)
4970{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004971 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004972 size_t name_len;
4973 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004974
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004975 /* Check if a valid request is parsed */
4976 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4977 lua_pushboolean(L, 0);
4978 return 1;
4979 }
4980
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004981 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004982 return 1;
4983}
4984
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004985/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004986static int hlua_http_res_set_status(lua_State *L)
4987{
4988 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4989 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004990 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004991
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004992 /* Check if a valid response is parsed */
4993 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4994 return 0;
4995
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004996 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004997 return 0;
4998}
4999
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005000/*
5001 *
5002 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005003 * Class TXN
5004 *
5005 *
5006 */
5007
5008/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005009 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005010 */
5011__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5012{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005013 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005014}
5015
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005016__LJMP static int hlua_set_var(lua_State *L)
5017{
5018 struct hlua_txn *htxn;
5019 const char *name;
5020 size_t len;
5021 struct sample smp;
5022
5023 MAY_LJMP(check_args(L, 3, "set_var"));
5024
5025 /* It is useles to retrieve the stream, but this function
5026 * runs only in a stream context.
5027 */
5028 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5029 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5030
5031 /* Converts the third argument in a sample. */
5032 hlua_lua2smp(L, 3, &smp);
5033
5034 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005035 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005036 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005037 return 0;
5038}
5039
Christopher Faulet85d79c92016-11-09 16:54:56 +01005040__LJMP static int hlua_unset_var(lua_State *L)
5041{
5042 struct hlua_txn *htxn;
5043 const char *name;
5044 size_t len;
5045 struct sample smp;
5046
5047 MAY_LJMP(check_args(L, 2, "unset_var"));
5048
5049 /* It is useles to retrieve the stream, but this function
5050 * runs only in a stream context.
5051 */
5052 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5053 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5054
5055 /* Unset the variable. */
5056 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5057 vars_unset_by_name(name, len, &smp);
5058 return 0;
5059}
5060
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005061__LJMP static int hlua_get_var(lua_State *L)
5062{
5063 struct hlua_txn *htxn;
5064 const char *name;
5065 size_t len;
5066 struct sample smp;
5067
5068 MAY_LJMP(check_args(L, 2, "get_var"));
5069
5070 /* It is useles to retrieve the stream, but this function
5071 * runs only in a stream context.
5072 */
5073 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5074 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5075
Willy Tarreau7560dd42016-03-10 16:28:58 +01005076 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005077 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005078 lua_pushnil(L);
5079 return 1;
5080 }
5081
5082 return hlua_smp2lua(L, &smp);
5083}
5084
Willy Tarreau59551662015-03-10 14:23:13 +01005085__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005086{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005087 struct hlua *hlua;
5088
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005089 MAY_LJMP(check_args(L, 2, "set_priv"));
5090
Willy Tarreau87b09662015-04-03 00:22:06 +02005091 /* It is useles to retrieve the stream, but this function
5092 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005093 */
5094 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005095 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005096
5097 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005098 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005099
5100 /* Get and store new value. */
5101 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5102 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5103
5104 return 0;
5105}
5106
Willy Tarreau59551662015-03-10 14:23:13 +01005107__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005108{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005109 struct hlua *hlua;
5110
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005111 MAY_LJMP(check_args(L, 1, "get_priv"));
5112
Willy Tarreau87b09662015-04-03 00:22:06 +02005113 /* It is useles to retrieve the stream, but this function
5114 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005115 */
5116 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005117 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005118
5119 /* Push configuration index in the stack. */
5120 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5121
5122 return 1;
5123}
5124
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005125/* Create stack entry containing a class TXN. This function
5126 * return 0 if the stack does not contains free slots,
5127 * otherwise it returns 1.
5128 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005129static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005130{
Willy Tarreaude491382015-04-06 11:04:28 +02005131 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005132
5133 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005134 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005135 return 0;
5136
5137 /* NOTE: The allocation never fails. The failure
5138 * throw an error, and the function never returns.
5139 * if the throw is not avalaible, the process is aborted.
5140 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005141 /* Create the object: obj[0] = userdata. */
5142 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005143 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005144 lua_rawseti(L, -2, 0);
5145
Willy Tarreaude491382015-04-06 11:04:28 +02005146 htxn->s = s;
5147 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005148 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005149 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005150
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005151 /* Create the "f" field that contains a list of fetches. */
5152 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005153 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005154 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005155 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005156
5157 /* Create the "sf" field that contains a list of stringsafe fetches. */
5158 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005159 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005160 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005161 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005162
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005163 /* Create the "c" field that contains a list of converters. */
5164 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005165 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005166 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005167 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005168
5169 /* Create the "sc" field that contains a list of stringsafe converters. */
5170 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005171 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005172 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005173 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005174
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005175 /* Create the "req" field that contains the request channel object. */
5176 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005177 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005178 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005179 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005180
5181 /* Create the "res" field that contains the response channel object. */
5182 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005183 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005184 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005185 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005186
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005187 /* Creates the HTTP object is the current proxy allows http. */
5188 lua_pushstring(L, "http");
5189 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005190 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005191 return 0;
5192 }
5193 else
5194 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005195 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005196
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005197 /* Pop a class sesison metatable and affect it to the userdata. */
5198 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5199 lua_setmetatable(L, -2);
5200
5201 return 1;
5202}
5203
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005204__LJMP static int hlua_txn_deflog(lua_State *L)
5205{
5206 const char *msg;
5207 struct hlua_txn *htxn;
5208
5209 MAY_LJMP(check_args(L, 2, "deflog"));
5210 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5211 msg = MAY_LJMP(luaL_checkstring(L, 2));
5212
5213 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5214 return 0;
5215}
5216
5217__LJMP static int hlua_txn_log(lua_State *L)
5218{
5219 int level;
5220 const char *msg;
5221 struct hlua_txn *htxn;
5222
5223 MAY_LJMP(check_args(L, 3, "log"));
5224 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5225 level = MAY_LJMP(luaL_checkinteger(L, 2));
5226 msg = MAY_LJMP(luaL_checkstring(L, 3));
5227
5228 if (level < 0 || level >= NB_LOG_LEVELS)
5229 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5230
5231 hlua_sendlog(htxn->s->be, level, msg);
5232 return 0;
5233}
5234
5235__LJMP static int hlua_txn_log_debug(lua_State *L)
5236{
5237 const char *msg;
5238 struct hlua_txn *htxn;
5239
5240 MAY_LJMP(check_args(L, 2, "Debug"));
5241 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5242 msg = MAY_LJMP(luaL_checkstring(L, 2));
5243 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5244 return 0;
5245}
5246
5247__LJMP static int hlua_txn_log_info(lua_State *L)
5248{
5249 const char *msg;
5250 struct hlua_txn *htxn;
5251
5252 MAY_LJMP(check_args(L, 2, "Info"));
5253 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5254 msg = MAY_LJMP(luaL_checkstring(L, 2));
5255 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5256 return 0;
5257}
5258
5259__LJMP static int hlua_txn_log_warning(lua_State *L)
5260{
5261 const char *msg;
5262 struct hlua_txn *htxn;
5263
5264 MAY_LJMP(check_args(L, 2, "Warning"));
5265 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5266 msg = MAY_LJMP(luaL_checkstring(L, 2));
5267 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5268 return 0;
5269}
5270
5271__LJMP static int hlua_txn_log_alert(lua_State *L)
5272{
5273 const char *msg;
5274 struct hlua_txn *htxn;
5275
5276 MAY_LJMP(check_args(L, 2, "Alert"));
5277 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5278 msg = MAY_LJMP(luaL_checkstring(L, 2));
5279 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5280 return 0;
5281}
5282
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005283__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5284{
5285 struct hlua_txn *htxn;
5286 int ll;
5287
5288 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5289 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5290 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5291
5292 if (ll < 0 || ll > 7)
5293 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5294
5295 htxn->s->logs.level = ll;
5296 return 0;
5297}
5298
5299__LJMP static int hlua_txn_set_tos(lua_State *L)
5300{
5301 struct hlua_txn *htxn;
5302 struct connection *cli_conn;
5303 int tos;
5304
5305 MAY_LJMP(check_args(L, 2, "set_tos"));
5306 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5307 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5308
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005309 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005310 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005311
5312 return 0;
5313}
5314
5315__LJMP static int hlua_txn_set_mark(lua_State *L)
5316{
5317#ifdef SO_MARK
5318 struct hlua_txn *htxn;
5319 struct connection *cli_conn;
5320 int mark;
5321
5322 MAY_LJMP(check_args(L, 2, "set_mark"));
5323 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5324 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5325
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005326 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005327 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005328#endif
5329 return 0;
5330}
5331
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005332/* This function is an Lua binding that send pending data
5333 * to the client, and close the stream interface.
5334 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005335__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005336{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005337 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005338 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005339 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005340
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005341 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005342 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005343 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005344
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005345 /* If the flags NOTERM is set, we cannot terminate the http
5346 * session, so we just end the execution of the current
5347 * lua code.
5348 */
5349 if (htxn->flags & HLUA_TXN_NOTERM) {
5350 WILL_LJMP(hlua_done(L));
5351 return 0;
5352 }
5353
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005354 ic = &htxn->s->req;
5355 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005356
Willy Tarreau630ef452015-08-28 10:06:15 +02005357 if (htxn->s->txn) {
5358 /* HTTP mode, let's stay in sync with the stream */
5359 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
5360 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5361 htxn->s->txn->req.sov = 0;
5362 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5363 oc->analysers = AN_RES_HTTP_XFER_BODY;
5364 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5365 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5366
Willy Tarreau630ef452015-08-28 10:06:15 +02005367 /* Note that if we want to support keep-alive, we need
5368 * to bypass the close/shutr_now calls below, but that
5369 * may only be done if the HTTP request was already
5370 * processed and the connection header is known (ie
5371 * not during TCP rules).
5372 */
5373 }
5374
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005375 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005376 channel_abort(ic);
5377 channel_auto_close(ic);
5378 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005379
5380 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005381 channel_auto_read(oc);
5382 channel_auto_close(oc);
5383 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005384
Willy Tarreau0458b082015-08-28 09:40:04 +02005385 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005386
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005387 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005388 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005389 return 0;
5390}
5391
5392__LJMP static int hlua_log(lua_State *L)
5393{
5394 int level;
5395 const char *msg;
5396
5397 MAY_LJMP(check_args(L, 2, "log"));
5398 level = MAY_LJMP(luaL_checkinteger(L, 1));
5399 msg = MAY_LJMP(luaL_checkstring(L, 2));
5400
5401 if (level < 0 || level >= NB_LOG_LEVELS)
5402 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5403
5404 hlua_sendlog(NULL, level, msg);
5405 return 0;
5406}
5407
5408__LJMP static int hlua_log_debug(lua_State *L)
5409{
5410 const char *msg;
5411
5412 MAY_LJMP(check_args(L, 1, "debug"));
5413 msg = MAY_LJMP(luaL_checkstring(L, 1));
5414 hlua_sendlog(NULL, LOG_DEBUG, msg);
5415 return 0;
5416}
5417
5418__LJMP static int hlua_log_info(lua_State *L)
5419{
5420 const char *msg;
5421
5422 MAY_LJMP(check_args(L, 1, "info"));
5423 msg = MAY_LJMP(luaL_checkstring(L, 1));
5424 hlua_sendlog(NULL, LOG_INFO, msg);
5425 return 0;
5426}
5427
5428__LJMP static int hlua_log_warning(lua_State *L)
5429{
5430 const char *msg;
5431
5432 MAY_LJMP(check_args(L, 1, "warning"));
5433 msg = MAY_LJMP(luaL_checkstring(L, 1));
5434 hlua_sendlog(NULL, LOG_WARNING, msg);
5435 return 0;
5436}
5437
5438__LJMP static int hlua_log_alert(lua_State *L)
5439{
5440 const char *msg;
5441
5442 MAY_LJMP(check_args(L, 1, "alert"));
5443 msg = MAY_LJMP(luaL_checkstring(L, 1));
5444 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005445 return 0;
5446}
5447
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005448__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005449{
5450 int wakeup_ms = lua_tointeger(L, -1);
5451 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005452 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005453 return 0;
5454}
5455
5456__LJMP static int hlua_sleep(lua_State *L)
5457{
5458 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005459 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005460
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005461 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005462
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005463 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005464 wakeup_ms = tick_add(now_ms, delay);
5465 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005466
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005467 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5468 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005469}
5470
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005471__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005472{
5473 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005474 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005475
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005476 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005477
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005478 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005479 wakeup_ms = tick_add(now_ms, delay);
5480 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005481
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005482 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5483 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005484}
5485
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005486/* This functionis an LUA binding. it permits to give back
5487 * the hand at the HAProxy scheduler. It is used when the
5488 * LUA processing consumes a lot of time.
5489 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005490__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005491{
5492 return 0;
5493}
5494
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005495__LJMP static int hlua_yield(lua_State *L)
5496{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005497 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5498 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005499}
5500
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005501/* This function change the nice of the currently executed
5502 * task. It is used set low or high priority at the current
5503 * task.
5504 */
Willy Tarreau59551662015-03-10 14:23:13 +01005505__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005506{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005507 struct hlua *hlua;
5508 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005509
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005510 MAY_LJMP(check_args(L, 1, "set_nice"));
5511 hlua = hlua_gethlua(L);
5512 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005513
5514 /* If he task is not set, I'm in a start mode. */
5515 if (!hlua || !hlua->task)
5516 return 0;
5517
5518 if (nice < -1024)
5519 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005520 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005521 nice = 1024;
5522
5523 hlua->task->nice = nice;
5524 return 0;
5525}
5526
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005527/* This function is used as a calback of a task. It is called by the
5528 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5529 * return an E_AGAIN signal, the emmiter of this signal must set a
5530 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005531 *
5532 * Task wrapper are longjmp safe because the only one Lua code
5533 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005534 */
5535static struct task *hlua_process_task(struct task *task)
5536{
5537 struct hlua *hlua = task->context;
5538 enum hlua_exec status;
5539
Christopher Faulet5bc99722018-04-25 10:34:45 +02005540 if (task->thread_mask == MAX_THREADS_MASK)
5541 task_set_affinity(task, tid_bit);
5542
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005543 /* If it is the first call to the task, we must initialize the
5544 * execution timeouts.
5545 */
5546 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005547 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005548
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005549 /* Execute the Lua code. */
5550 status = hlua_ctx_resume(hlua, 1);
5551
5552 switch (status) {
5553 /* finished or yield */
5554 case HLUA_E_OK:
5555 hlua_ctx_destroy(hlua);
5556 task_delete(task);
5557 task_free(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02005558 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005559 break;
5560
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005561 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01005562 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02005563 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005564 break;
5565
5566 /* finished with error. */
5567 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005568 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005569 hlua_ctx_destroy(hlua);
5570 task_delete(task);
5571 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005572 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005573 break;
5574
5575 case HLUA_E_ERR:
5576 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005577 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005578 hlua_ctx_destroy(hlua);
5579 task_delete(task);
5580 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005581 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005582 break;
5583 }
Emeric Brun253e53e2017-10-17 18:58:40 +02005584 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005585}
5586
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005587/* This function is an LUA binding that register LUA function to be
5588 * executed after the HAProxy configuration parsing and before the
5589 * HAProxy scheduler starts. This function expect only one LUA
5590 * argument that is a function. This function returns nothing, but
5591 * throws if an error is encountered.
5592 */
5593__LJMP static int hlua_register_init(lua_State *L)
5594{
5595 struct hlua_init_function *init;
5596 int ref;
5597
5598 MAY_LJMP(check_args(L, 1, "register_init"));
5599
5600 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5601
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005602 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005603 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005604 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005605
5606 init->function_ref = ref;
5607 LIST_ADDQ(&hlua_init_functions, &init->l);
5608 return 0;
5609}
5610
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005611/* This functio is an LUA binding. It permits to register a task
5612 * executed in parallel of the main HAroxy activity. The task is
5613 * created and it is set in the HAProxy scheduler. It can be called
5614 * from the "init" section, "post init" or during the runtime.
5615 *
5616 * Lua prototype:
5617 *
5618 * <none> core.register_task(<function>)
5619 */
5620static int hlua_register_task(lua_State *L)
5621{
5622 struct hlua *hlua;
5623 struct task *task;
5624 int ref;
5625
5626 MAY_LJMP(check_args(L, 1, "register_task"));
5627
5628 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5629
Willy Tarreaubafbe012017-11-24 17:34:44 +01005630 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005631 if (!hlua)
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
Emeric Brunc60def82017-09-27 14:59:38 +02005634 task = task_new(MAX_THREADS_MASK);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005635 task->context = hlua;
5636 task->process = hlua_process_task;
5637
5638 if (!hlua_ctx_init(hlua, task))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005639 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005640
5641 /* Restore the function in the stack. */
5642 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5643 hlua->nargs = 0;
5644
5645 /* Schedule task. */
5646 task_schedule(task, now_ms);
5647
5648 return 0;
5649}
5650
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005651/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5652 * doesn't allow "yield" functions because the HAProxy engine cannot
5653 * resume converters.
5654 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005655static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005656{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005657 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005658 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005659 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005660
Willy Tarreaube508f12016-03-10 11:47:01 +01005661 if (!stream)
5662 return 0;
5663
Willy Tarreau87b09662015-04-03 00:22:06 +02005664 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005665 * Lua context can be not initialized. This behavior
5666 * permits to save performances because a systematic
5667 * Lua initialization cause 5% performances loss.
5668 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005669 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005670 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005671 if (!stream->hlua) {
5672 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5673 return 0;
5674 }
5675 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5676 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5677 return 0;
5678 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005679 }
5680
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005681 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005682 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005683
5684 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005685 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5686 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5687 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005688 else
5689 error = "critical error";
5690 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005691 return 0;
5692 }
5693
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005694 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005695 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005696 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005697 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005698 return 0;
5699 }
5700
5701 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005702 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005703
5704 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005705 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005706 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005707 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005708 return 0;
5709 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005710 hlua_smp2lua(stream->hlua->T, smp);
5711 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005712
5713 /* push keywords in the stack. */
5714 if (arg_p) {
5715 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005716 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005717 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005718 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005719 return 0;
5720 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005721 hlua_arg2lua(stream->hlua->T, arg_p);
5722 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005723 }
5724 }
5725
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005726 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005727 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005728
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005729 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005730 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005731 }
5732
5733 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005734 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005735 /* finished. */
5736 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005737 /* If the stack is empty, the function fails. */
5738 if (lua_gettop(stream->hlua->T) <= 0)
5739 return 0;
5740
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005741 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005742 hlua_lua2smp(stream->hlua->T, -1, smp);
5743 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005744 return 1;
5745
5746 /* yield. */
5747 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005748 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005749 return 0;
5750
5751 /* finished with error. */
5752 case HLUA_E_ERRMSG:
5753 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005754 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005755 fcn->name, lua_tostring(stream->hlua->T, -1));
5756 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005757 return 0;
5758
5759 case HLUA_E_ERR:
5760 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005761 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005762
5763 default:
5764 return 0;
5765 }
5766}
5767
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005768/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5769 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005770 * resume sample-fetches. This function will be called by the sample
5771 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005772 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005773static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5774 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005775{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005776 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005777 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005778 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005779 const struct chunk msg = { .len = 0 };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005780
Willy Tarreaube508f12016-03-10 11:47:01 +01005781 if (!stream)
5782 return 0;
5783
Willy Tarreau87b09662015-04-03 00:22:06 +02005784 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005785 * Lua context can be not initialized. This behavior
5786 * permits to save performances because a systematic
5787 * Lua initialization cause 5% performances loss.
5788 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005789 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005790 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005791 if (!stream->hlua) {
5792 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5793 return 0;
5794 }
5795 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5796 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5797 return 0;
5798 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005799 }
5800
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005801 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005802
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005803 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005804 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005805
5806 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005807 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5808 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5809 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005810 else
5811 error = "critical error";
5812 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005813 return 0;
5814 }
5815
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005816 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005817 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005818 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005819 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005820 return 0;
5821 }
5822
5823 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005824 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005825
5826 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005827 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005828 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005829 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005830 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005831 return 0;
5832 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005833 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005834
5835 /* push keywords in the stack. */
5836 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5837 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005838 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005839 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005840 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005841 return 0;
5842 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005843 hlua_arg2lua(stream->hlua->T, arg_p);
5844 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005845 }
5846
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005847 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005848 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005849
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005850 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005851 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005852 }
5853
5854 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005855 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005856 /* finished. */
5857 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005858 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005859 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005860 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005861 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005862 /* If the stack is empty, the function fails. */
5863 if (lua_gettop(stream->hlua->T) <= 0)
5864 return 0;
5865
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005866 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005867 hlua_lua2smp(stream->hlua->T, -1, smp);
5868 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005869
5870 /* Set the end of execution flag. */
5871 smp->flags &= ~SMP_F_MAY_CHANGE;
5872 return 1;
5873
5874 /* yield. */
5875 case HLUA_E_AGAIN:
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 FOURNIER23bc3752015-09-11 19:15:43 +02005878 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005879 return 0;
5880
5881 /* finished with error. */
5882 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005883 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005884 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005885 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005886 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005887 fcn->name, lua_tostring(stream->hlua->T, -1));
5888 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005889 return 0;
5890
5891 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005892 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005893 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005894 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005895 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005896
5897 default:
5898 return 0;
5899 }
5900}
5901
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005902/* This function is an LUA binding used for registering
5903 * "sample-conv" functions. It expects a converter name used
5904 * in the haproxy configuration file, and an LUA function.
5905 */
5906__LJMP static int hlua_register_converters(lua_State *L)
5907{
5908 struct sample_conv_kw_list *sck;
5909 const char *name;
5910 int ref;
5911 int len;
5912 struct hlua_function *fcn;
5913
5914 MAY_LJMP(check_args(L, 2, "register_converters"));
5915
5916 /* First argument : converter name. */
5917 name = MAY_LJMP(luaL_checkstring(L, 1));
5918
5919 /* Second argument : lua function. */
5920 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5921
5922 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005923 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005924 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005925 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005926 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005927 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005928 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005929
5930 /* Fill fcn. */
5931 fcn->name = strdup(name);
5932 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005933 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005934 fcn->function_ref = ref;
5935
5936 /* List head */
5937 sck->list.n = sck->list.p = NULL;
5938
5939 /* converter keyword. */
5940 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005941 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005942 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005943 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005944
5945 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5946 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005947 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 +01005948 sck->kw[0].val_args = NULL;
5949 sck->kw[0].in_type = SMP_T_STR;
5950 sck->kw[0].out_type = SMP_T_STR;
5951 sck->kw[0].private = fcn;
5952
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005953 /* Register this new converter */
5954 sample_register_convs(sck);
5955
5956 return 0;
5957}
5958
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005959/* This fucntion is an LUA binding used for registering
5960 * "sample-fetch" functions. It expects a converter name used
5961 * in the haproxy configuration file, and an LUA function.
5962 */
5963__LJMP static int hlua_register_fetches(lua_State *L)
5964{
5965 const char *name;
5966 int ref;
5967 int len;
5968 struct sample_fetch_kw_list *sfk;
5969 struct hlua_function *fcn;
5970
5971 MAY_LJMP(check_args(L, 2, "register_fetches"));
5972
5973 /* First argument : sample-fetch name. */
5974 name = MAY_LJMP(luaL_checkstring(L, 1));
5975
5976 /* Second argument : lua function. */
5977 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5978
5979 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005980 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005981 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005982 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005983 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005984 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005985 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005986
5987 /* Fill fcn. */
5988 fcn->name = strdup(name);
5989 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005990 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005991 fcn->function_ref = ref;
5992
5993 /* List head */
5994 sfk->list.n = sfk->list.p = NULL;
5995
5996 /* sample-fetch keyword. */
5997 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005998 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005999 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006000 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006001
6002 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6003 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006004 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 +01006005 sfk->kw[0].val_args = NULL;
6006 sfk->kw[0].out_type = SMP_T_STR;
6007 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6008 sfk->kw[0].val = 0;
6009 sfk->kw[0].private = fcn;
6010
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006011 /* Register this new fetch. */
6012 sample_register_fetches(sfk);
6013
6014 return 0;
6015}
6016
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006017/* This function is a wrapper to execute each LUA function declared
6018 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006019 * return ACT_RET_CONT if the processing is finished (with or without
6020 * error) and return ACT_RET_YIELD if the function must be called again
6021 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006022 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006023static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006024 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006025{
6026 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006027 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006028 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006029 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006030 const struct chunk msg = { .len = 0 };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006031
6032 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01006033 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
6034 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
6035 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
6036 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006037 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006038 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006039 return ACT_RET_CONT;
6040 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006041
Willy Tarreau87b09662015-04-03 00:22:06 +02006042 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006043 * Lua context can be not initialized. This behavior
6044 * permits to save performances because a systematic
6045 * Lua initialization cause 5% performances loss.
6046 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006047 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006048 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006049 if (!s->hlua) {
6050 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6051 rule->arg.hlua_rule->fcn.name);
6052 return ACT_RET_CONT;
6053 }
6054 if (!hlua_ctx_init(s->hlua, s->task)) {
6055 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6056 rule->arg.hlua_rule->fcn.name);
6057 return ACT_RET_CONT;
6058 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006059 }
6060
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006061 consistency_set(s, dir, &s->hlua->cons);
6062
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006063 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006064 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006065
6066 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006067 if (!SET_SAFE_LJMP(s->hlua->T)) {
6068 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6069 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006070 else
6071 error = "critical error";
6072 SEND_ERR(px, "Lua function '%s': %s.\n",
6073 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006074 return ACT_RET_CONT;
6075 }
6076
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006077 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006078 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006079 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006080 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006081 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006082 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006083 }
6084
6085 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006086 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006087
Willy Tarreau87b09662015-04-03 00:22:06 +02006088 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006089 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006090 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006091 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006092 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006093 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006094 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006095 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006096
6097 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006098 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006099 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006100 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006101 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006102 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006103 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006104 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006105 lua_pushstring(s->hlua->T, *arg);
6106 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006107 }
6108
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006109 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006110 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006111
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006112 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006113 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006114 }
6115
6116 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006117 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006118 /* finished. */
6119 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006120 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006121 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006122 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006123 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006124 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006125 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006126 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006127
6128 /* yield. */
6129 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006130 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006131 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006132 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006133 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006134 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006135 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006136 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006137 /* Some actions can be wake up when a "write" event
6138 * is detected on a response channel. This is useful
6139 * only for actions targetted on the requests.
6140 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006141 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006142 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01006143 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006144 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006145 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006146 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006147 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006148 /* We can quit the fcuntion without consistency check
6149 * because HAProxy is not able to manipulate data, it
6150 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006151 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006152
6153 /* finished with error. */
6154 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006155 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006156 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006157 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006158 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006159 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006160 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006161 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6162 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006163 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006164
6165 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006166 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006167 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006168 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006169 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006170 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006171 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006172 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006173
6174 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006175 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006176 }
6177}
6178
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006179struct task *hlua_applet_wakeup(struct task *t)
6180{
6181 struct appctx *ctx = t->context;
6182 struct stream_interface *si = ctx->owner;
6183
6184 /* If the applet is wake up without any expected work, the sheduler
6185 * remove it from the run queue. This flag indicate that the applet
6186 * is waiting for write. If the buffer is full, the main processing
6187 * will send some data and after call the applet, otherwise it call
6188 * the applet ASAP.
6189 */
6190 si_applet_cant_put(si);
6191 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006192 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006193 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006194}
6195
6196static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6197{
6198 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006199 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006200 struct task *task;
6201 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006202 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006203
Willy Tarreaubafbe012017-11-24 17:34:44 +01006204 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006205 if (!hlua) {
6206 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6207 ctx->rule->arg.hlua_rule->fcn.name);
6208 return 0;
6209 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006210 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006211 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006212 ctx->ctx.hlua_apptcp.flags = 0;
6213
6214 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006215 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006216 if (!task) {
6217 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6218 ctx->rule->arg.hlua_rule->fcn.name);
6219 return 0;
6220 }
6221 task->nice = 0;
6222 task->context = ctx;
6223 task->process = hlua_applet_wakeup;
6224 ctx->ctx.hlua_apptcp.task = task;
6225
6226 /* In the execution wrappers linked with a stream, the
6227 * Lua context can be not initialized. This behavior
6228 * permits to save performances because a systematic
6229 * Lua initialization cause 5% performances loss.
6230 */
6231 if (!hlua_ctx_init(hlua, task)) {
6232 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6233 ctx->rule->arg.hlua_rule->fcn.name);
6234 return 0;
6235 }
6236
6237 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006238 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006239
6240 /* The following Lua calls can fail. */
6241 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006242 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6243 error = lua_tostring(hlua->T, -1);
6244 else
6245 error = "critical error";
6246 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6247 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006248 RESET_SAFE_LJMP(hlua->T);
6249 return 0;
6250 }
6251
6252 /* Check stack available size. */
6253 if (!lua_checkstack(hlua->T, 1)) {
6254 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6255 ctx->rule->arg.hlua_rule->fcn.name);
6256 RESET_SAFE_LJMP(hlua->T);
6257 return 0;
6258 }
6259
6260 /* Restore the function in the stack. */
6261 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6262
6263 /* Create and and push object stream in the stack. */
6264 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6265 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6266 ctx->rule->arg.hlua_rule->fcn.name);
6267 RESET_SAFE_LJMP(hlua->T);
6268 return 0;
6269 }
6270 hlua->nargs = 1;
6271
6272 /* push keywords in the stack. */
6273 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6274 if (!lua_checkstack(hlua->T, 1)) {
6275 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6276 ctx->rule->arg.hlua_rule->fcn.name);
6277 RESET_SAFE_LJMP(hlua->T);
6278 return 0;
6279 }
6280 lua_pushstring(hlua->T, *arg);
6281 hlua->nargs++;
6282 }
6283
6284 RESET_SAFE_LJMP(hlua->T);
6285
6286 /* Wakeup the applet ASAP. */
6287 si_applet_cant_get(si);
6288 si_applet_cant_put(si);
6289
6290 return 1;
6291}
6292
6293static void hlua_applet_tcp_fct(struct appctx *ctx)
6294{
6295 struct stream_interface *si = ctx->owner;
6296 struct stream *strm = si_strm(si);
6297 struct channel *res = si_ic(si);
6298 struct act_rule *rule = ctx->rule;
6299 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006300 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006301
6302 /* The applet execution is already done. */
6303 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
6304 return;
6305
6306 /* If the stream is disconnect or closed, ldo nothing. */
6307 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6308 return;
6309
6310 /* Execute the function. */
6311 switch (hlua_ctx_resume(hlua, 1)) {
6312 /* finished. */
6313 case HLUA_E_OK:
6314 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6315
6316 /* log time */
6317 strm->logs.tv_request = now;
6318
6319 /* eat the whole request */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006320 co_skip(si_oc(si), si_ob(si)->o);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006321 res->flags |= CF_READ_NULL;
6322 si_shutr(si);
6323 return;
6324
6325 /* yield. */
6326 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006327 if (hlua->wake_time != TICK_ETERNITY)
6328 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006329 return;
6330
6331 /* finished with error. */
6332 case HLUA_E_ERRMSG:
6333 /* Display log. */
6334 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6335 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6336 lua_pop(hlua->T, 1);
6337 goto error;
6338
6339 case HLUA_E_ERR:
6340 /* Display log. */
6341 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6342 rule->arg.hlua_rule->fcn.name);
6343 goto error;
6344
6345 default:
6346 goto error;
6347 }
6348
6349error:
6350
6351 /* For all other cases, just close the stream. */
6352 si_shutw(si);
6353 si_shutr(si);
6354 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6355}
6356
6357static void hlua_applet_tcp_release(struct appctx *ctx)
6358{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006359 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006360 task_free(ctx->ctx.hlua_apptcp.task);
6361 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006362 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006363 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006364}
6365
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006366/* The function returns 1 if the initialisation is complete, 0 if
6367 * an errors occurs and -1 if more data are required for initializing
6368 * the applet.
6369 */
6370static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6371{
6372 struct stream_interface *si = ctx->owner;
6373 struct channel *req = si_oc(si);
6374 struct http_msg *msg;
6375 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006376 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006377 char **arg;
6378 struct hdr_ctx hdr;
6379 struct task *task;
6380 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006381 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006382
6383 /* Wait for a full HTTP request. */
6384 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6385 if (smp.flags & SMP_F_MAY_CHANGE)
6386 return -1;
6387 return 0;
6388 }
6389 txn = strm->txn;
6390 msg = &txn->req;
6391
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006392 /* We want two things in HTTP mode :
6393 * - enforce server-close mode if we were in keep-alive, so that the
6394 * applet is released after each response ;
6395 * - enable request body transfer to the applet in order to resync
6396 * with the response body.
6397 */
6398 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6399 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006400
Willy Tarreaubafbe012017-11-24 17:34:44 +01006401 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006402 if (!hlua) {
6403 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6404 ctx->rule->arg.hlua_rule->fcn.name);
6405 return 0;
6406 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006407 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006408 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006409 ctx->ctx.hlua_apphttp.left_bytes = -1;
6410 ctx->ctx.hlua_apphttp.flags = 0;
6411
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006412 if (txn->req.flags & HTTP_MSGF_VER_11)
6413 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6414
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006415 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006416 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006417 if (!task) {
6418 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6419 ctx->rule->arg.hlua_rule->fcn.name);
6420 return 0;
6421 }
6422 task->nice = 0;
6423 task->context = ctx;
6424 task->process = hlua_applet_wakeup;
6425 ctx->ctx.hlua_apphttp.task = task;
6426
6427 /* In the execution wrappers linked with a stream, the
6428 * Lua context can be not initialized. This behavior
6429 * permits to save performances because a systematic
6430 * Lua initialization cause 5% performances loss.
6431 */
6432 if (!hlua_ctx_init(hlua, task)) {
6433 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6434 ctx->rule->arg.hlua_rule->fcn.name);
6435 return 0;
6436 }
6437
6438 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006439 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006440
6441 /* The following Lua calls can fail. */
6442 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006443 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6444 error = lua_tostring(hlua->T, -1);
6445 else
6446 error = "critical error";
6447 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6448 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006449 return 0;
6450 }
6451
6452 /* Check stack available size. */
6453 if (!lua_checkstack(hlua->T, 1)) {
6454 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6455 ctx->rule->arg.hlua_rule->fcn.name);
6456 RESET_SAFE_LJMP(hlua->T);
6457 return 0;
6458 }
6459
6460 /* Restore the function in the stack. */
6461 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6462
6463 /* Create and and push object stream in the stack. */
6464 if (!hlua_applet_http_new(hlua->T, ctx)) {
6465 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6466 ctx->rule->arg.hlua_rule->fcn.name);
6467 RESET_SAFE_LJMP(hlua->T);
6468 return 0;
6469 }
6470 hlua->nargs = 1;
6471
6472 /* Look for a 100-continue expected. */
6473 if (msg->flags & HTTP_MSGF_VER_11) {
6474 hdr.idx = 0;
6475 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
6476 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6477 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6478 }
6479
6480 /* push keywords in the stack. */
6481 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6482 if (!lua_checkstack(hlua->T, 1)) {
6483 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6484 ctx->rule->arg.hlua_rule->fcn.name);
6485 RESET_SAFE_LJMP(hlua->T);
6486 return 0;
6487 }
6488 lua_pushstring(hlua->T, *arg);
6489 hlua->nargs++;
6490 }
6491
6492 RESET_SAFE_LJMP(hlua->T);
6493
6494 /* Wakeup the applet when data is ready for read. */
6495 si_applet_cant_get(si);
6496
6497 return 1;
6498}
6499
6500static void hlua_applet_http_fct(struct appctx *ctx)
6501{
6502 struct stream_interface *si = ctx->owner;
6503 struct stream *strm = si_strm(si);
6504 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006505 struct act_rule *rule = ctx->rule;
6506 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006507 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006508 char *blk1;
6509 int len1;
6510 char *blk2;
6511 int len2;
6512 int ret;
6513
6514 /* If the stream is disconnect or closed, ldo nothing. */
6515 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6516 return;
6517
6518 /* Set the currently running flag. */
6519 if (!HLUA_IS_RUNNING(hlua) &&
6520 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6521
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006522 /* Wait for full HTTP analysys. */
6523 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6524 si_applet_cant_get(si);
6525 return;
6526 }
6527
6528 /* Store the max amount of bytes that we can read. */
6529 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6530
6531 /* We need to flush the request header. This left the body
6532 * for the Lua.
6533 */
6534
6535 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006536 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006537 if (ret == -1)
6538 return;
6539
6540 /* No data available, ask for more data. */
6541 if (ret == 1)
6542 len2 = 0;
6543 if (ret == 0)
6544 len1 = 0;
6545 if (len1 + len2 < strm->txn->req.eoh + 2) {
6546 si_applet_cant_get(si);
6547 return;
6548 }
6549
6550 /* skip the requests bytes. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006551 co_skip(si_oc(si), strm->txn->req.eoh + 2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006552 }
6553
6554 /* Executes The applet if it is not done. */
6555 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6556
6557 /* Execute the function. */
6558 switch (hlua_ctx_resume(hlua, 1)) {
6559 /* finished. */
6560 case HLUA_E_OK:
6561 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6562 break;
6563
6564 /* yield. */
6565 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006566 if (hlua->wake_time != TICK_ETERNITY)
6567 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006568 return;
6569
6570 /* finished with error. */
6571 case HLUA_E_ERRMSG:
6572 /* Display log. */
6573 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6574 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6575 lua_pop(hlua->T, 1);
6576 goto error;
6577
6578 case HLUA_E_ERR:
6579 /* Display log. */
6580 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6581 rule->arg.hlua_rule->fcn.name);
6582 goto error;
6583
6584 default:
6585 goto error;
6586 }
6587 }
6588
6589 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6590
6591 /* We must send the final chunk. */
6592 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6593 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6594
6595 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006596 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006597
6598 /* critical error. */
6599 if (ret == -2 || ret == -3) {
6600 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6601 rule->arg.hlua_rule->fcn.name);
6602 goto error;
6603 }
6604
6605 /* no enough space error. */
6606 if (ret == -1) {
6607 si_applet_cant_put(si);
6608 return;
6609 }
6610
6611 /* set the last chunk sent. */
6612 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6613 }
6614
6615 /* close the connection. */
6616
6617 /* status / log */
6618 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6619 strm->logs.tv_request = now;
6620
6621 /* eat the whole request */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006622 co_skip(si_oc(si), si_ob(si)->o);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006623 res->flags |= CF_READ_NULL;
6624 si_shutr(si);
6625
6626 return;
6627 }
6628
6629error:
6630
6631 /* If we are in HTTP mode, and we are not send any
6632 * data, return a 500 server error in best effort:
6633 * if there are no room avalaible in the buffer,
6634 * just close the connection.
6635 */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006636 ci_putblk(res, error_500, strlen(error_500));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006637 if (!(strm->flags & SF_ERR_MASK))
6638 strm->flags |= SF_ERR_RESOURCE;
6639 si_shutw(si);
6640 si_shutr(si);
6641 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6642}
6643
6644static void hlua_applet_http_release(struct appctx *ctx)
6645{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006646 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006647 task_free(ctx->ctx.hlua_apphttp.task);
6648 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006649 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006650 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006651}
6652
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006653/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6654 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006655 *
6656 * This function can fail with an abort() due to an Lua critical error.
6657 * We are in the configuration parsing process of HAProxy, this abort() is
6658 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006659 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006660static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6661 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006662{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006663 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006664 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006665
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006666 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006667 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006668 if (!rule->arg.hlua_rule) {
6669 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006670 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006671 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006672
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006673 /* Memory for arguments. */
6674 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6675 if (!rule->arg.hlua_rule->args) {
6676 memprintf(err, "out of memory error");
6677 return ACT_RET_PRS_ERR;
6678 }
6679
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006680 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006681 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006682
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006683 /* Expect some arguments */
6684 for (i = 0; i < fcn->nargs; i++) {
6685 if (*args[i+1] == '\0') {
6686 memprintf(err, "expect %d arguments", fcn->nargs);
6687 return ACT_RET_PRS_ERR;
6688 }
6689 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6690 if (!rule->arg.hlua_rule->args[i]) {
6691 memprintf(err, "out of memory error");
6692 return ACT_RET_PRS_ERR;
6693 }
6694 (*cur_arg)++;
6695 }
6696 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006697
Thierry FOURNIER42148732015-09-02 17:17:33 +02006698 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006699 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006700 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006701}
6702
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006703static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6704 struct act_rule *rule, char **err)
6705{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006706 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006707
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006708 /* HTTP applets are forbidden in tcp-request rules.
6709 * HTTP applet request requires everything initilized by
6710 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6711 * The applet will be immediately initilized, but its before
6712 * the call of this analyzer.
6713 */
6714 if (rule->from != ACT_F_HTTP_REQ) {
6715 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6716 return ACT_RET_PRS_ERR;
6717 }
6718
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006719 /* Memory for the rule. */
6720 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6721 if (!rule->arg.hlua_rule) {
6722 memprintf(err, "out of memory error");
6723 return ACT_RET_PRS_ERR;
6724 }
6725
6726 /* Reference the Lua function and store the reference. */
6727 rule->arg.hlua_rule->fcn = *fcn;
6728
6729 /* TODO: later accept arguments. */
6730 rule->arg.hlua_rule->args = NULL;
6731
6732 /* Add applet pointer in the rule. */
6733 rule->applet.obj_type = OBJ_TYPE_APPLET;
6734 rule->applet.name = fcn->name;
6735 rule->applet.init = hlua_applet_http_init;
6736 rule->applet.fct = hlua_applet_http_fct;
6737 rule->applet.release = hlua_applet_http_release;
6738 rule->applet.timeout = hlua_timeout_applet;
6739
6740 return ACT_RET_PRS_OK;
6741}
6742
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006743/* This function is an LUA binding used for registering
6744 * "sample-conv" functions. It expects a converter name used
6745 * in the haproxy configuration file, and an LUA function.
6746 */
6747__LJMP static int hlua_register_action(lua_State *L)
6748{
6749 struct action_kw_list *akl;
6750 const char *name;
6751 int ref;
6752 int len;
6753 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006754 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006755
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006756 /* Initialise the number of expected arguments at 0. */
6757 nargs = 0;
6758
6759 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6760 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006761
6762 /* First argument : converter name. */
6763 name = MAY_LJMP(luaL_checkstring(L, 1));
6764
6765 /* Second argument : environment. */
6766 if (lua_type(L, 2) != LUA_TTABLE)
6767 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6768
6769 /* Third argument : lua function. */
6770 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6771
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006772 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6773 if (lua_gettop(L) >= 4)
6774 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6775
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006776 /* browse the second argulent as an array. */
6777 lua_pushnil(L);
6778 while (lua_next(L, 2) != 0) {
6779 if (lua_type(L, -1) != LUA_TSTRING)
6780 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6781
6782 /* Check required environment. Only accepted "http" or "tcp". */
6783 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006784 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006785 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006786 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006787 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006788 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006789 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006790
6791 /* Fill fcn. */
6792 fcn->name = strdup(name);
6793 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006794 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006795 fcn->function_ref = ref;
6796
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006797 /* Set the expected number od arguments. */
6798 fcn->nargs = nargs;
6799
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006800 /* List head */
6801 akl->list.n = akl->list.p = NULL;
6802
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006803 /* action keyword. */
6804 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006805 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006806 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006807 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006808
6809 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6810
6811 akl->kw[0].match_pfx = 0;
6812 akl->kw[0].private = fcn;
6813 akl->kw[0].parse = action_register_lua;
6814
6815 /* select the action registering point. */
6816 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6817 tcp_req_cont_keywords_register(akl);
6818 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6819 tcp_res_cont_keywords_register(akl);
6820 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6821 http_req_keywords_register(akl);
6822 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6823 http_res_keywords_register(akl);
6824 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006825 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006826 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6827 "are expected.", lua_tostring(L, -1)));
6828
6829 /* pop the environment string. */
6830 lua_pop(L, 1);
6831 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006832 return ACT_RET_PRS_OK;
6833}
6834
6835static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6836 struct act_rule *rule, char **err)
6837{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006838 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006839
6840 /* Memory for the rule. */
6841 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6842 if (!rule->arg.hlua_rule) {
6843 memprintf(err, "out of memory error");
6844 return ACT_RET_PRS_ERR;
6845 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006846
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006847 /* Reference the Lua function and store the reference. */
6848 rule->arg.hlua_rule->fcn = *fcn;
6849
6850 /* TODO: later accept arguments. */
6851 rule->arg.hlua_rule->args = NULL;
6852
6853 /* Add applet pointer in the rule. */
6854 rule->applet.obj_type = OBJ_TYPE_APPLET;
6855 rule->applet.name = fcn->name;
6856 rule->applet.init = hlua_applet_tcp_init;
6857 rule->applet.fct = hlua_applet_tcp_fct;
6858 rule->applet.release = hlua_applet_tcp_release;
6859 rule->applet.timeout = hlua_timeout_applet;
6860
6861 return 0;
6862}
6863
6864/* This function is an LUA binding used for registering
6865 * "sample-conv" functions. It expects a converter name used
6866 * in the haproxy configuration file, and an LUA function.
6867 */
6868__LJMP static int hlua_register_service(lua_State *L)
6869{
6870 struct action_kw_list *akl;
6871 const char *name;
6872 const char *env;
6873 int ref;
6874 int len;
6875 struct hlua_function *fcn;
6876
6877 MAY_LJMP(check_args(L, 3, "register_service"));
6878
6879 /* First argument : converter name. */
6880 name = MAY_LJMP(luaL_checkstring(L, 1));
6881
6882 /* Second argument : environment. */
6883 env = MAY_LJMP(luaL_checkstring(L, 2));
6884
6885 /* Third argument : lua function. */
6886 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6887
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006888 /* Allocate and fill the sample fetch keyword struct. */
6889 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6890 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006891 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006892 fcn = calloc(1, sizeof(*fcn));
6893 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006894 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006895
6896 /* Fill fcn. */
6897 len = strlen("<lua.>") + strlen(name) + 1;
6898 fcn->name = calloc(1, len);
6899 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006900 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006901 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6902 fcn->function_ref = ref;
6903
6904 /* List head */
6905 akl->list.n = akl->list.p = NULL;
6906
6907 /* converter keyword. */
6908 len = strlen("lua.") + strlen(name) + 1;
6909 akl->kw[0].kw = calloc(1, len);
6910 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006911 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006912
6913 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6914
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01006915 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006916 if (strcmp(env, "tcp") == 0)
6917 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006918 else if (strcmp(env, "http") == 0)
6919 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006920 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006921 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01006922 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006923
6924 akl->kw[0].match_pfx = 0;
6925 akl->kw[0].private = fcn;
6926
6927 /* End of array. */
6928 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6929
6930 /* Register this new converter */
6931 service_keywords_register(akl);
6932
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006933 return 0;
6934}
6935
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006936/* This function initialises Lua cli handler. It copies the
6937 * arguments in the Lua stack and create channel IO objects.
6938 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02006939static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006940{
6941 struct hlua *hlua;
6942 struct hlua_function *fcn;
6943 int i;
6944 const char *error;
6945
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006946 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006947 appctx->ctx.hlua_cli.fcn = private;
6948
Willy Tarreaubafbe012017-11-24 17:34:44 +01006949 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006950 if (!hlua) {
6951 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006952 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006953 }
6954 HLUA_INIT(hlua);
6955 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006956
6957 /* Create task used by signal to wakeup applets.
6958 * We use the same wakeup fonction than the Lua applet_tcp and
6959 * applet_http. It is absolutely compatible.
6960 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006961 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006962 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01006963 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006964 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006965 }
6966 appctx->ctx.hlua_cli.task->nice = 0;
6967 appctx->ctx.hlua_cli.task->context = appctx;
6968 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
6969
6970 /* Initialises the Lua context */
6971 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
6972 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006973 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006974 }
6975
6976 /* The following Lua calls can fail. */
6977 if (!SET_SAFE_LJMP(hlua->T)) {
6978 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6979 error = lua_tostring(hlua->T, -1);
6980 else
6981 error = "critical error";
6982 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
6983 goto error;
6984 }
6985
6986 /* Check stack available size. */
6987 if (!lua_checkstack(hlua->T, 2)) {
6988 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6989 goto error;
6990 }
6991
6992 /* Restore the function in the stack. */
6993 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
6994
6995 /* Once the arguments parsed, the CLI is like an AppletTCP,
6996 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006997 */
6998 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
6999 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7000 goto error;
7001 }
7002 hlua->nargs = 1;
7003
7004 /* push keywords in the stack. */
7005 for (i = 0; *args[i]; i++) {
7006 /* Check stack available size. */
7007 if (!lua_checkstack(hlua->T, 1)) {
7008 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7009 goto error;
7010 }
7011 lua_pushstring(hlua->T, args[i]);
7012 hlua->nargs++;
7013 }
7014
7015 /* We must initialize the execution timeouts. */
7016 hlua->max_time = hlua_timeout_session;
7017
7018 /* At this point the execution is safe. */
7019 RESET_SAFE_LJMP(hlua->T);
7020
7021 /* It's ok */
7022 return 0;
7023
7024 /* It's not ok. */
7025error:
7026 RESET_SAFE_LJMP(hlua->T);
7027 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007028 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007029 return 1;
7030}
7031
7032static int hlua_cli_io_handler_fct(struct appctx *appctx)
7033{
7034 struct hlua *hlua;
7035 struct stream_interface *si;
7036 struct hlua_function *fcn;
7037
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007038 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007039 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007040 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007041
7042 /* If the stream is disconnect or closed, ldo nothing. */
7043 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7044 return 1;
7045
7046 /* Execute the function. */
7047 switch (hlua_ctx_resume(hlua, 1)) {
7048
7049 /* finished. */
7050 case HLUA_E_OK:
7051 return 1;
7052
7053 /* yield. */
7054 case HLUA_E_AGAIN:
7055 /* We want write. */
7056 if (HLUA_IS_WAKERESWR(hlua))
7057 si_applet_cant_put(si);
7058 /* Set the timeout. */
7059 if (hlua->wake_time != TICK_ETERNITY)
7060 task_schedule(hlua->task, hlua->wake_time);
7061 return 0;
7062
7063 /* finished with error. */
7064 case HLUA_E_ERRMSG:
7065 /* Display log. */
7066 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
7067 fcn->name, lua_tostring(hlua->T, -1));
7068 lua_pop(hlua->T, 1);
7069 return 1;
7070
7071 case HLUA_E_ERR:
7072 /* Display log. */
7073 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
7074 fcn->name);
7075 return 1;
7076
7077 default:
7078 return 1;
7079 }
7080
7081 return 1;
7082}
7083
7084static void hlua_cli_io_release_fct(struct appctx *appctx)
7085{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007086 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007087 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007088}
7089
7090/* This function is an LUA binding used for registering
7091 * new keywords in the cli. It expects a list of keywords
7092 * which are the "path". It is limited to 5 keywords. A
7093 * description of the command, a function to be executed
7094 * for the parsing and a function for io handlers.
7095 */
7096__LJMP static int hlua_register_cli(lua_State *L)
7097{
7098 struct cli_kw_list *cli_kws;
7099 const char *message;
7100 int ref_io;
7101 int len;
7102 struct hlua_function *fcn;
7103 int index;
7104 int i;
7105
7106 MAY_LJMP(check_args(L, 3, "register_cli"));
7107
7108 /* First argument : an array of maximum 5 keywords. */
7109 if (!lua_istable(L, 1))
7110 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
7111
7112 /* Second argument : string with contextual message. */
7113 message = MAY_LJMP(luaL_checkstring(L, 2));
7114
7115 /* Third and fourth argument : lua function. */
7116 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
7117
7118 /* Allocate and fill the sample fetch keyword struct. */
7119 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
7120 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007121 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007122 fcn = calloc(1, sizeof(*fcn));
7123 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007124 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007125
7126 /* Fill path. */
7127 index = 0;
7128 lua_pushnil(L);
7129 while(lua_next(L, 1) != 0) {
7130 if (index >= 5)
7131 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
7132 if (lua_type(L, -1) != LUA_TSTRING)
7133 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
7134 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
7135 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007136 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007137 index++;
7138 lua_pop(L, 1);
7139 }
7140
7141 /* Copy help message. */
7142 cli_kws->kw[0].usage = strdup(message);
7143 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007144 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007145
7146 /* Fill fcn io handler. */
7147 len = strlen("<lua.cli>") + 1;
7148 for (i = 0; i < index; i++)
7149 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
7150 fcn->name = calloc(1, len);
7151 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007152 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007153 strncat((char *)fcn->name, "<lua.cli", len);
7154 for (i = 0; i < index; i++) {
7155 strncat((char *)fcn->name, ".", len);
7156 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
7157 }
7158 strncat((char *)fcn->name, ">", len);
7159 fcn->function_ref = ref_io;
7160
7161 /* Fill last entries. */
7162 cli_kws->kw[0].private = fcn;
7163 cli_kws->kw[0].parse = hlua_cli_parse_fct;
7164 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
7165 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
7166
7167 /* Register this new converter */
7168 cli_register_kw(cli_kws);
7169
7170 return 0;
7171}
7172
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007173static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7174 struct proxy *defpx, const char *file, int line,
7175 char **err, unsigned int *timeout)
7176{
7177 const char *error;
7178
7179 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
7180 if (error && *error != '\0') {
7181 memprintf(err, "%s: invalid timeout", args[0]);
7182 return -1;
7183 }
7184 return 0;
7185}
7186
7187static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7188 struct proxy *defpx, const char *file, int line,
7189 char **err)
7190{
7191 return hlua_read_timeout(args, section_type, curpx, defpx,
7192 file, line, err, &hlua_timeout_session);
7193}
7194
7195static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7196 struct proxy *defpx, const char *file, int line,
7197 char **err)
7198{
7199 return hlua_read_timeout(args, section_type, curpx, defpx,
7200 file, line, err, &hlua_timeout_task);
7201}
7202
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007203static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7204 struct proxy *defpx, const char *file, int line,
7205 char **err)
7206{
7207 return hlua_read_timeout(args, section_type, curpx, defpx,
7208 file, line, err, &hlua_timeout_applet);
7209}
7210
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007211static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7212 struct proxy *defpx, const char *file, int line,
7213 char **err)
7214{
7215 char *error;
7216
7217 hlua_nb_instruction = strtoll(args[1], &error, 10);
7218 if (*error != '\0') {
7219 memprintf(err, "%s: invalid number", args[0]);
7220 return -1;
7221 }
7222 return 0;
7223}
7224
Willy Tarreau32f61e22015-03-18 17:54:59 +01007225static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7226 struct proxy *defpx, const char *file, int line,
7227 char **err)
7228{
7229 char *error;
7230
7231 if (*(args[1]) == 0) {
7232 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7233 return -1;
7234 }
7235 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7236 if (*error != '\0') {
7237 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7238 return -1;
7239 }
7240 return 0;
7241}
7242
7243
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007244/* This function is called by the main configuration key "lua-load". It loads and
7245 * execute an lua file during the parsing of the HAProxy configuration file. It is
7246 * the main lua entry point.
7247 *
7248 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7249 * occured, otherwise it returns 0.
7250 *
7251 * In some error case, LUA set an error message in top of the stack. This function
7252 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007253 *
7254 * This function can fail with an abort() due to an Lua critical error.
7255 * We are in the configuration parsing process of HAProxy, this abort() is
7256 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007257 */
7258static int hlua_load(char **args, int section_type, struct proxy *curpx,
7259 struct proxy *defpx, const char *file, int line,
7260 char **err)
7261{
7262 int error;
7263
7264 /* Just load and compile the file. */
7265 error = luaL_loadfile(gL.T, args[1]);
7266 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007267 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007268 lua_pop(gL.T, 1);
7269 return -1;
7270 }
7271
7272 /* If no syntax error where detected, execute the code. */
7273 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7274 switch (error) {
7275 case LUA_OK:
7276 break;
7277 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007278 memprintf(err, "Lua runtime 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_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007282 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007283 return -1;
7284 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007285 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007286 lua_pop(gL.T, 1);
7287 return -1;
7288 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007289 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007290 lua_pop(gL.T, 1);
7291 return -1;
7292 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007293 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007294 lua_pop(gL.T, 1);
7295 return -1;
7296 }
7297
7298 return 0;
7299}
7300
7301/* configuration keywords declaration */
7302static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007303 { CFG_GLOBAL, "lua-load", hlua_load },
7304 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7305 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007306 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007307 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007308 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007309 { 0, NULL, NULL },
7310}};
7311
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007312/* This function can fail with an abort() due to an Lua critical error.
7313 * We are in the initialisation process of HAProxy, this abort() is
7314 * tolerated.
7315 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007316int hlua_post_init()
7317{
7318 struct hlua_init_function *init;
7319 const char *msg;
7320 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007321 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007322
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007323 /* Call post initialisation function in safe environement. */
7324 if (!SET_SAFE_LJMP(gL.T)) {
7325 if (lua_type(gL.T, -1) == LUA_TSTRING)
7326 error = lua_tostring(gL.T, -1);
7327 else
7328 error = "critical error";
7329 fprintf(stderr, "Lua post-init: %s.\n", error);
7330 exit(1);
7331 }
7332 hlua_fcn_post_init(gL.T);
7333 RESET_SAFE_LJMP(gL.T);
7334
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007335 list_for_each_entry(init, &hlua_init_functions, l) {
7336 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7337 ret = hlua_ctx_resume(&gL, 0);
7338 switch (ret) {
7339 case HLUA_E_OK:
7340 lua_pop(gL.T, -1);
7341 return 1;
7342 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007343 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007344 return 0;
7345 case HLUA_E_ERRMSG:
7346 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01007347 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007348 return 0;
7349 case HLUA_E_ERR:
7350 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007351 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007352 return 0;
7353 }
7354 }
7355 return 1;
7356}
7357
Willy Tarreau32f61e22015-03-18 17:54:59 +01007358/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7359 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7360 * is the previously allocated size or the kind of object in case of a new
7361 * allocation. <nsize> is the requested new size.
7362 */
7363static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7364{
7365 struct hlua_mem_allocator *zone = ud;
7366
7367 if (nsize == 0) {
7368 /* it's a free */
7369 if (ptr)
7370 zone->allocated -= osize;
7371 free(ptr);
7372 return NULL;
7373 }
7374
7375 if (!ptr) {
7376 /* it's a new allocation */
7377 if (zone->limit && zone->allocated + nsize > zone->limit)
7378 return NULL;
7379
7380 ptr = malloc(nsize);
7381 if (ptr)
7382 zone->allocated += nsize;
7383 return ptr;
7384 }
7385
7386 /* it's a realloc */
7387 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7388 return NULL;
7389
7390 ptr = realloc(ptr, nsize);
7391 if (ptr)
7392 zone->allocated += nsize - osize;
7393 return ptr;
7394}
7395
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007396/* Ithis function can fail with an abort() due to an Lua critical error.
7397 * We are in the initialisation process of HAProxy, this abort() is
7398 * tolerated.
7399 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007400void hlua_init(void)
7401{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007402 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007403 int idx;
7404 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007405 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007406 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007407 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007408#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007409 struct srv_kw *kw;
7410 int tmp_error;
7411 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007412 char *args[] = { /* SSL client configuration. */
7413 "ssl",
7414 "verify",
7415 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007416 NULL
7417 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007418#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007419
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007420 HA_SPIN_INIT(&hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02007421
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007422 /* Initialise struct hlua and com signals pool */
Willy Tarreaubafbe012017-11-24 17:34:44 +01007423 pool_head_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007424
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007425 /* Register configuration keywords. */
7426 cfg_register_keywords(&cfg_kws);
7427
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007428 /* Init main lua stack. */
7429 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007430 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007431 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007432 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007433 hlua_sethlua(&gL);
7434 gL.Tref = LUA_REFNIL;
7435 gL.task = NULL;
7436
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007437 /* From this point, until the end of the initialisation fucntion,
7438 * the Lua function can fail with an abort. We are in the initialisation
7439 * process of HAProxy, this abort() is tolerated.
7440 */
7441
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007442 /* Initialise lua. */
7443 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007444
Thierry Fournier75933d42016-01-21 09:30:18 +01007445 /* Set safe environment for the initialisation. */
7446 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007447 if (lua_type(gL.T, -1) == LUA_TSTRING)
7448 error_msg = lua_tostring(gL.T, -1);
7449 else
7450 error_msg = "critical error";
7451 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007452 exit(1);
7453 }
7454
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007455 /*
7456 *
7457 * Create "core" object.
7458 *
7459 */
7460
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007461 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007462 lua_newtable(gL.T);
7463
7464 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007465 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007466 hlua_class_const_int(gL.T, log_levels[i], i);
7467
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007468 /* Register special functions. */
7469 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007470 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007471 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007472 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007473 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007474 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007475 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007476 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007477 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007478 hlua_class_function(gL.T, "sleep", hlua_sleep);
7479 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007480 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7481 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7482 hlua_class_function(gL.T, "set_map", hlua_set_map);
7483 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007484 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007485 hlua_class_function(gL.T, "log", hlua_log);
7486 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7487 hlua_class_function(gL.T, "Info", hlua_log_info);
7488 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7489 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007490 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007491 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007492
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007493 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007494
7495 /*
7496 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007497 * Register class Map
7498 *
7499 */
7500
7501 /* This table entry is the object "Map" base. */
7502 lua_newtable(gL.T);
7503
7504 /* register pattern types. */
7505 for (i=0; i<PAT_MATCH_NUM; i++)
7506 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007507 for (i=0; i<PAT_MATCH_NUM; i++) {
7508 snprintf(trash.str, trash.size, "_%s", pat_match_names[i]);
7509 hlua_class_const_int(gL.T, trash.str, i);
7510 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007511
7512 /* register constructor. */
7513 hlua_class_function(gL.T, "new", hlua_map_new);
7514
7515 /* Create and fill the metatable. */
7516 lua_newtable(gL.T);
7517
7518 /* Create and fille the __index entry. */
7519 lua_pushstring(gL.T, "__index");
7520 lua_newtable(gL.T);
7521
7522 /* Register . */
7523 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7524 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7525
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007526 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007527
Thierry Fournier45e78d72016-02-19 18:34:46 +01007528 /* Register previous table in the registry with reference and named entry.
7529 * The function hlua_register_metatable() pops the stack, so we
7530 * previously create a copy of the table.
7531 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007532 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007533 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007534
7535 /* Assign the metatable to the mai Map object. */
7536 lua_setmetatable(gL.T, -2);
7537
7538 /* Set a name to the table. */
7539 lua_setglobal(gL.T, "Map");
7540
7541 /*
7542 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007543 * Register class Channel
7544 *
7545 */
7546
7547 /* Create and fill the metatable. */
7548 lua_newtable(gL.T);
7549
7550 /* Create and fille the __index entry. */
7551 lua_pushstring(gL.T, "__index");
7552 lua_newtable(gL.T);
7553
7554 /* Register . */
7555 hlua_class_function(gL.T, "get", hlua_channel_get);
7556 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7557 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7558 hlua_class_function(gL.T, "set", hlua_channel_set);
7559 hlua_class_function(gL.T, "append", hlua_channel_append);
7560 hlua_class_function(gL.T, "send", hlua_channel_send);
7561 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7562 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7563 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007564 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007565
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007566 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007567
7568 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007569 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007570
7571 /*
7572 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007573 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007574 *
7575 */
7576
7577 /* Create and fill the metatable. */
7578 lua_newtable(gL.T);
7579
7580 /* Create and fille the __index entry. */
7581 lua_pushstring(gL.T, "__index");
7582 lua_newtable(gL.T);
7583
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007584 /* Browse existing fetches and create the associated
7585 * object method.
7586 */
7587 sf = NULL;
7588 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7589
7590 /* Dont register the keywork if the arguments check function are
7591 * not safe during the runtime.
7592 */
7593 if ((sf->val_args != NULL) &&
7594 (sf->val_args != val_payload_lv) &&
7595 (sf->val_args != val_hdr))
7596 continue;
7597
7598 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7599 * by an underscore.
7600 */
7601 strncpy(trash.str, sf->kw, trash.size);
7602 trash.str[trash.size - 1] = '\0';
7603 for (p = trash.str; *p; p++)
7604 if (*p == '.' || *p == '-' || *p == '+')
7605 *p = '_';
7606
7607 /* Register the function. */
7608 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007609 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007610 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007611 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007612 }
7613
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007614 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007615
7616 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007617 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007618
7619 /*
7620 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007621 * Register class Converters
7622 *
7623 */
7624
7625 /* Create and fill the metatable. */
7626 lua_newtable(gL.T);
7627
7628 /* Create and fill the __index entry. */
7629 lua_pushstring(gL.T, "__index");
7630 lua_newtable(gL.T);
7631
7632 /* Browse existing converters and create the associated
7633 * object method.
7634 */
7635 sc = NULL;
7636 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7637 /* Dont register the keywork if the arguments check function are
7638 * not safe during the runtime.
7639 */
7640 if (sc->val_args != NULL)
7641 continue;
7642
7643 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7644 * by an underscore.
7645 */
7646 strncpy(trash.str, sc->kw, trash.size);
7647 trash.str[trash.size - 1] = '\0';
7648 for (p = trash.str; *p; p++)
7649 if (*p == '.' || *p == '-' || *p == '+')
7650 *p = '_';
7651
7652 /* Register the function. */
7653 lua_pushstring(gL.T, trash.str);
7654 lua_pushlightuserdata(gL.T, sc);
7655 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007656 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007657 }
7658
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007659 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007660
7661 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007662 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007663
7664 /*
7665 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007666 * Register class HTTP
7667 *
7668 */
7669
7670 /* Create and fill the metatable. */
7671 lua_newtable(gL.T);
7672
7673 /* Create and fille the __index entry. */
7674 lua_pushstring(gL.T, "__index");
7675 lua_newtable(gL.T);
7676
7677 /* Register Lua functions. */
7678 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7679 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7680 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7681 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7682 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7683 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7684 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7685 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7686 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7687 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7688
7689 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7690 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7691 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7692 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7693 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7694 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007695 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007696
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007697 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007698
7699 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007700 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007701
7702 /*
7703 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007704 * Register class AppletTCP
7705 *
7706 */
7707
7708 /* Create and fill the metatable. */
7709 lua_newtable(gL.T);
7710
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007711 /* Create and fille the __index entry. */
7712 lua_pushstring(gL.T, "__index");
7713 lua_newtable(gL.T);
7714
7715 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007716 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7717 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7718 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7719 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7720 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007721 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7722 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7723 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007724
7725 lua_settable(gL.T, -3);
7726
7727 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007728 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007729
7730 /*
7731 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007732 * Register class AppletHTTP
7733 *
7734 */
7735
7736 /* Create and fill the metatable. */
7737 lua_newtable(gL.T);
7738
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007739 /* Create and fille the __index entry. */
7740 lua_pushstring(gL.T, "__index");
7741 lua_newtable(gL.T);
7742
7743 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007744 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7745 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007746 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7747 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7748 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007749 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7750 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7751 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7752 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7753 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7754 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7755
7756 lua_settable(gL.T, -3);
7757
7758 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007759 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007760
7761 /*
7762 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007763 * Register class TXN
7764 *
7765 */
7766
7767 /* Create and fill the metatable. */
7768 lua_newtable(gL.T);
7769
7770 /* Create and fille the __index entry. */
7771 lua_pushstring(gL.T, "__index");
7772 lua_newtable(gL.T);
7773
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007774 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007775 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7776 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007777 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007778 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007779 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007780 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007781 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7782 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7783 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007784 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7785 hlua_class_function(gL.T, "log", hlua_txn_log);
7786 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7787 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7788 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7789 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007790
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007791 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007792
7793 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007794 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007795
7796 /*
7797 *
7798 * Register class Socket
7799 *
7800 */
7801
7802 /* Create and fill the metatable. */
7803 lua_newtable(gL.T);
7804
7805 /* Create and fille the __index entry. */
7806 lua_pushstring(gL.T, "__index");
7807 lua_newtable(gL.T);
7808
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007809#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007810 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007811#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007812 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7813 hlua_class_function(gL.T, "send", hlua_socket_send);
7814 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7815 hlua_class_function(gL.T, "close", hlua_socket_close);
7816 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7817 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7818 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7819 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7820
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007821 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007822
7823 /* Register the garbage collector entry. */
7824 lua_pushstring(gL.T, "__gc");
7825 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007826 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007827
7828 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007829 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007830
7831 /* Proxy and server configuration initialisation. */
7832 memset(&socket_proxy, 0, sizeof(socket_proxy));
7833 init_new_proxy(&socket_proxy);
7834 socket_proxy.parent = NULL;
7835 socket_proxy.last_change = now.tv_sec;
7836 socket_proxy.id = "LUA-SOCKET";
7837 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7838 socket_proxy.maxconn = 0;
7839 socket_proxy.accept = NULL;
7840 socket_proxy.options2 |= PR_O2_INDEPSTR;
7841 socket_proxy.srv = NULL;
7842 socket_proxy.conn_retries = 0;
7843 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7844
7845 /* Init TCP server: unchanged parameters */
7846 memset(&socket_tcp, 0, sizeof(socket_tcp));
7847 socket_tcp.next = NULL;
7848 socket_tcp.proxy = &socket_proxy;
7849 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7850 LIST_INIT(&socket_tcp.actconns);
7851 LIST_INIT(&socket_tcp.pendconns);
Christopher Faulet40a007c2017-07-03 15:41:01 +02007852 socket_tcp.priv_conns = NULL;
7853 socket_tcp.idle_conns = NULL;
7854 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02007855 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007856 socket_tcp.last_change = 0;
7857 socket_tcp.id = "LUA-TCP-CONN";
7858 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7859 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7860 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7861
7862 /* XXX: Copy default parameter from default server,
7863 * but the default server is not initialized.
7864 */
7865 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7866 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7867 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7868 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7869 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7870 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7871 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7872 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7873 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7874 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7875
7876 socket_tcp.check.status = HCHK_STATUS_INI;
7877 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7878 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7879 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7880 socket_tcp.check.server = &socket_tcp;
7881
7882 socket_tcp.agent.status = HCHK_STATUS_INI;
7883 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7884 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7885 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7886 socket_tcp.agent.server = &socket_tcp;
7887
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007888 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007889
7890#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007891 /* Init TCP server: unchanged parameters */
7892 memset(&socket_ssl, 0, sizeof(socket_ssl));
7893 socket_ssl.next = NULL;
7894 socket_ssl.proxy = &socket_proxy;
7895 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7896 LIST_INIT(&socket_ssl.actconns);
7897 LIST_INIT(&socket_ssl.pendconns);
Christopher Faulet40a007c2017-07-03 15:41:01 +02007898 socket_tcp.priv_conns = NULL;
7899 socket_tcp.idle_conns = NULL;
7900 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02007901 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007902 socket_ssl.last_change = 0;
7903 socket_ssl.id = "LUA-SSL-CONN";
7904 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7905 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7906 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7907
7908 /* XXX: Copy default parameter from default server,
7909 * but the default server is not initialized.
7910 */
7911 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7912 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7913 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7914 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7915 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7916 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7917 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7918 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7919 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7920 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7921
7922 socket_ssl.check.status = HCHK_STATUS_INI;
7923 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7924 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7925 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7926 socket_ssl.check.server = &socket_ssl;
7927
7928 socket_ssl.agent.status = HCHK_STATUS_INI;
7929 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7930 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7931 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7932 socket_ssl.agent.server = &socket_ssl;
7933
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007934 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007935 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007936
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007937 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007938 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7939 /*
7940 *
7941 * If the keyword is not known, we can search in the registered
7942 * server keywords. This is usefull to configure special SSL
7943 * features like client certificates and ssl_verify.
7944 *
7945 */
7946 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7947 if (tmp_error != 0) {
7948 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7949 abort(); /* This must be never arrives because the command line
7950 not editable by the user. */
7951 }
7952 idx += kw->skip;
7953 }
7954 }
7955
7956 /* Initialize SSL server. */
Willy Tarreaucbe6da52018-05-18 17:08:28 +02007957 if (socket_ssl.xprt->prepare_srv) {
7958 int saved_used_backed = global.ssl_used_backend;
7959 // don't affect maxconn automatic computation
Willy Tarreau17d45382016-12-22 21:16:08 +01007960 socket_ssl.xprt->prepare_srv(&socket_ssl);
Willy Tarreaucbe6da52018-05-18 17:08:28 +02007961 global.ssl_used_backend = saved_used_backed;
7962 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007963#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007964
7965 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007966}
Willy Tarreaubb57d942016-12-21 19:04:56 +01007967
7968__attribute__((constructor))
7969static void __hlua_init(void)
7970{
7971 char *ptr = NULL;
7972 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
7973 hap_register_build_opts(ptr, 1);
7974}