blob: 727d664843c22695c5bc51fe17677f1dabe6f3ac [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. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001037 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001038 break;
1039 }
1040 /* Process the forced yield. if the general yield is not allowed or
1041 * if no task were associated this the current Lua execution
1042 * coroutine, we resume the execution. Else we want to return in the
1043 * scheduler and we want to be waked up again, to continue the
1044 * current Lua execution. So we schedule our own task.
1045 */
1046 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001047 if (!yield_allowed || !lua->task)
1048 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001049 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001050 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001051 if (!yield_allowed) {
1052 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001053 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001054 break;
1055 }
1056 ret = HLUA_E_AGAIN;
1057 break;
1058
1059 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001060
1061 /* Special exit case. The traditionnal exit is returned as an error
1062 * because the errors ares the only one mean to return immediately
1063 * from and lua execution.
1064 */
1065 if (lua->flags & HLUA_EXIT) {
1066 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001067 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001068 break;
1069 }
1070
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001071 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001072 if (!lua_checkstack(lua->T, 1)) {
1073 ret = HLUA_E_ERR;
1074 break;
1075 }
1076 msg = lua_tostring(lua->T, -1);
1077 lua_settop(lua->T, 0); /* Empty the stack. */
1078 lua_pop(lua->T, 1);
1079 if (msg)
1080 lua_pushfstring(lua->T, "runtime error: %s", msg);
1081 else
1082 lua_pushfstring(lua->T, "unknown runtime error");
1083 ret = HLUA_E_ERRMSG;
1084 break;
1085
1086 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001087 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001088 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001089 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001090 break;
1091
1092 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001093 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001094 if (!lua_checkstack(lua->T, 1)) {
1095 ret = HLUA_E_ERR;
1096 break;
1097 }
1098 msg = lua_tostring(lua->T, -1);
1099 lua_settop(lua->T, 0); /* Empty the stack. */
1100 lua_pop(lua->T, 1);
1101 if (msg)
1102 lua_pushfstring(lua->T, "message handler error: %s", msg);
1103 else
1104 lua_pushfstring(lua->T, "message handler error");
1105 ret = HLUA_E_ERRMSG;
1106 break;
1107
1108 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001109 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001110 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001111 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001112 break;
1113 }
1114
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001115 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001116 if (lua->flags & HLUA_MUST_GC &&
1117 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001118 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1119
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001120 switch (ret) {
1121 case HLUA_E_AGAIN:
1122 break;
1123
1124 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001125 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001126 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001127 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001128 break;
1129
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001130 case HLUA_E_ETMOUT:
1131 case HLUA_E_NOMEM:
1132 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001133 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001134 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001135 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001136 hlua_ctx_renew(lua, 0);
1137 break;
1138
1139 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001140 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001141 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001142 break;
1143 }
1144
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001145 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001146 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001147
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001148 return ret;
1149}
1150
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001151/* This function exit the current code. */
1152__LJMP static int hlua_done(lua_State *L)
1153{
1154 struct hlua *hlua = hlua_gethlua(L);
1155
1156 hlua->flags |= HLUA_EXIT;
1157 WILL_LJMP(lua_error(L));
1158
1159 return 0;
1160}
1161
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001162/* This function is an LUA binding. It provides a function
1163 * for deleting ACL from a referenced ACL file.
1164 */
1165__LJMP static int hlua_del_acl(lua_State *L)
1166{
1167 const char *name;
1168 const char *key;
1169 struct pat_ref *ref;
1170
1171 MAY_LJMP(check_args(L, 2, "del_acl"));
1172
1173 name = MAY_LJMP(luaL_checkstring(L, 1));
1174 key = MAY_LJMP(luaL_checkstring(L, 2));
1175
1176 ref = pat_ref_lookup(name);
1177 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001178 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001179
1180 pat_ref_delete(ref, key);
1181 return 0;
1182}
1183
1184/* This function is an LUA binding. It provides a function
1185 * for deleting map entry from a referenced map file.
1186 */
1187static int hlua_del_map(lua_State *L)
1188{
1189 const char *name;
1190 const char *key;
1191 struct pat_ref *ref;
1192
1193 MAY_LJMP(check_args(L, 2, "del_map"));
1194
1195 name = MAY_LJMP(luaL_checkstring(L, 1));
1196 key = MAY_LJMP(luaL_checkstring(L, 2));
1197
1198 ref = pat_ref_lookup(name);
1199 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001200 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001201
1202 pat_ref_delete(ref, key);
1203 return 0;
1204}
1205
1206/* This function is an LUA binding. It provides a function
1207 * for adding ACL pattern from a referenced ACL file.
1208 */
1209static int hlua_add_acl(lua_State *L)
1210{
1211 const char *name;
1212 const char *key;
1213 struct pat_ref *ref;
1214
1215 MAY_LJMP(check_args(L, 2, "add_acl"));
1216
1217 name = MAY_LJMP(luaL_checkstring(L, 1));
1218 key = MAY_LJMP(luaL_checkstring(L, 2));
1219
1220 ref = pat_ref_lookup(name);
1221 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001222 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001223
1224 if (pat_ref_find_elt(ref, key) == NULL)
1225 pat_ref_add(ref, key, NULL, NULL);
1226 return 0;
1227}
1228
1229/* This function is an LUA binding. It provides a function
1230 * for setting map pattern and sample from a referenced map
1231 * file.
1232 */
1233static int hlua_set_map(lua_State *L)
1234{
1235 const char *name;
1236 const char *key;
1237 const char *value;
1238 struct pat_ref *ref;
1239
1240 MAY_LJMP(check_args(L, 3, "set_map"));
1241
1242 name = MAY_LJMP(luaL_checkstring(L, 1));
1243 key = MAY_LJMP(luaL_checkstring(L, 2));
1244 value = MAY_LJMP(luaL_checkstring(L, 3));
1245
1246 ref = pat_ref_lookup(name);
1247 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001248 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001249
1250 if (pat_ref_find_elt(ref, key) != NULL)
1251 pat_ref_set(ref, key, value, NULL);
1252 else
1253 pat_ref_add(ref, key, value, NULL);
1254 return 0;
1255}
1256
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001257/* A class is a lot of memory that contain data. This data can be a table,
1258 * an integer or user data. This data is associated with a metatable. This
1259 * metatable have an original version registred in the global context with
1260 * the name of the object (_G[<name>] = <metable> ).
1261 *
1262 * A metable is a table that modify the standard behavior of a standard
1263 * access to the associated data. The entries of this new metatable are
1264 * defined as is:
1265 *
1266 * http://lua-users.org/wiki/MetatableEvents
1267 *
1268 * __index
1269 *
1270 * we access an absent field in a table, the result is nil. This is
1271 * true, but it is not the whole truth. Actually, such access triggers
1272 * the interpreter to look for an __index metamethod: If there is no
1273 * such method, as usually happens, then the access results in nil;
1274 * otherwise, the metamethod will provide the result.
1275 *
1276 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1277 * the key does not appear in the table, but the metatable has an __index
1278 * property:
1279 *
1280 * - if the value is a function, the function is called, passing in the
1281 * table and the key; the return value of that function is returned as
1282 * the result.
1283 *
1284 * - if the value is another table, the value of the key in that table is
1285 * asked for and returned (and if it doesn't exist in that table, but that
1286 * table's metatable has an __index property, then it continues on up)
1287 *
1288 * - Use "rawget(myTable,key)" to skip this metamethod.
1289 *
1290 * http://www.lua.org/pil/13.4.1.html
1291 *
1292 * __newindex
1293 *
1294 * Like __index, but control property assignment.
1295 *
1296 * __mode - Control weak references. A string value with one or both
1297 * of the characters 'k' and 'v' which specifies that the the
1298 * keys and/or values in the table are weak references.
1299 *
1300 * __call - Treat a table like a function. When a table is followed by
1301 * parenthesis such as "myTable( 'foo' )" and the metatable has
1302 * a __call key pointing to a function, that function is invoked
1303 * (passing any specified arguments) and the return value is
1304 * returned.
1305 *
1306 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1307 * called, if the metatable for myTable has a __metatable
1308 * key, the value of that key is returned instead of the
1309 * actual metatable.
1310 *
1311 * __tostring - Control string representation. When the builtin
1312 * "tostring( myTable )" function is called, if the metatable
1313 * for myTable has a __tostring property set to a function,
1314 * that function is invoked (passing myTable to it) and the
1315 * return value is used as the string representation.
1316 *
1317 * __len - Control table length. When the table length is requested using
1318 * the length operator ( '#' ), if the metatable for myTable has
1319 * a __len key pointing to a function, that function is invoked
1320 * (passing myTable to it) and the return value used as the value
1321 * of "#myTable".
1322 *
1323 * __gc - Userdata finalizer code. When userdata is set to be garbage
1324 * collected, if the metatable has a __gc field pointing to a
1325 * function, that function is first invoked, passing the userdata
1326 * to it. The __gc metamethod is not called for tables.
1327 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1328 *
1329 * Special metamethods for redefining standard operators:
1330 * http://www.lua.org/pil/13.1.html
1331 *
1332 * __add "+"
1333 * __sub "-"
1334 * __mul "*"
1335 * __div "/"
1336 * __unm "!"
1337 * __pow "^"
1338 * __concat ".."
1339 *
1340 * Special methods for redfining standar relations
1341 * http://www.lua.org/pil/13.2.html
1342 *
1343 * __eq "=="
1344 * __lt "<"
1345 * __le "<="
1346 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001347
1348/*
1349 *
1350 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001351 * Class Map
1352 *
1353 *
1354 */
1355
1356/* Returns a struct hlua_map if the stack entry "ud" is
1357 * a class session, otherwise it throws an error.
1358 */
1359__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1360{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001361 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001362}
1363
1364/* This function is the map constructor. It don't need
1365 * the class Map object. It creates and return a new Map
1366 * object. It must be called only during "body" or "init"
1367 * context because it process some filesystem accesses.
1368 */
1369__LJMP static int hlua_map_new(struct lua_State *L)
1370{
1371 const char *fn;
1372 int match = PAT_MATCH_STR;
1373 struct sample_conv conv;
1374 const char *file = "";
1375 int line = 0;
1376 lua_Debug ar;
1377 char *err = NULL;
1378 struct arg args[2];
1379
1380 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1381 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1382
1383 fn = MAY_LJMP(luaL_checkstring(L, 1));
1384
1385 if (lua_gettop(L) >= 2) {
1386 match = MAY_LJMP(luaL_checkinteger(L, 2));
1387 if (match < 0 || match >= PAT_MATCH_NUM)
1388 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1389 }
1390
1391 /* Get Lua filename and line number. */
1392 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1393 lua_getinfo(L, "Sl", &ar); /* get info about it */
1394 if (ar.currentline > 0) { /* is there info? */
1395 file = ar.short_src;
1396 line = ar.currentline;
1397 }
1398 }
1399
1400 /* fill fake sample_conv struct. */
1401 conv.kw = ""; /* unused. */
1402 conv.process = NULL; /* unused. */
1403 conv.arg_mask = 0; /* unused. */
1404 conv.val_args = NULL; /* unused. */
1405 conv.out_type = SMP_T_STR;
1406 conv.private = (void *)(long)match;
1407 switch (match) {
1408 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1409 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1410 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1411 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1412 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1413 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1414 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001415 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001416 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1417 default:
1418 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1419 }
1420
1421 /* fill fake args. */
1422 args[0].type = ARGT_STR;
1423 args[0].data.str.str = (char *)fn;
1424 args[1].type = ARGT_STOP;
1425
1426 /* load the map. */
1427 if (!sample_load_map(args, &conv, file, line, &err)) {
1428 /* error case: we cant use luaL_error because we must
1429 * free the err variable.
1430 */
1431 luaL_where(L, 1);
1432 lua_pushfstring(L, "'new': %s.", err);
1433 lua_concat(L, 2);
1434 free(err);
1435 WILL_LJMP(lua_error(L));
1436 }
1437
1438 /* create the lua object. */
1439 lua_newtable(L);
1440 lua_pushlightuserdata(L, args[0].data.map);
1441 lua_rawseti(L, -2, 0);
1442
1443 /* Pop a class Map metatable and affect it to the userdata. */
1444 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1445 lua_setmetatable(L, -2);
1446
1447
1448 return 1;
1449}
1450
1451__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1452{
1453 struct map_descriptor *desc;
1454 struct pattern *pat;
1455 struct sample smp;
1456
1457 MAY_LJMP(check_args(L, 2, "lookup"));
1458 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001459 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001460 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001461 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001462 }
1463 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001464 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001465 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001466 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 +02001467 }
1468
1469 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001470 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001471 if (str)
1472 lua_pushstring(L, "");
1473 else
1474 lua_pushnil(L);
1475 return 1;
1476 }
1477
1478 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001479 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001480 return 1;
1481}
1482
1483__LJMP static int hlua_map_lookup(struct lua_State *L)
1484{
1485 return _hlua_map_lookup(L, 0);
1486}
1487
1488__LJMP static int hlua_map_slookup(struct lua_State *L)
1489{
1490 return _hlua_map_lookup(L, 1);
1491}
1492
1493/*
1494 *
1495 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001496 * Class Socket
1497 *
1498 *
1499 */
1500
1501__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1502{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001503 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001504}
1505
1506/* This function is the handler called for each I/O on the established
1507 * connection. It is used for notify space avalaible to send or data
1508 * received.
1509 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001510static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001511{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001512 struct stream_interface *si = appctx->owner;
Olivier Houchard9aaf7782017-09-13 18:30:23 +02001513 struct connection *c = cs_conn(objt_cs(si_opposite(si)->end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001514
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001515 if (appctx->ctx.hlua_cosocket.die) {
1516 si_shutw(si);
1517 si_shutr(si);
1518 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001519 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1520 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001521 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1522 }
1523
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001524 /* If the connection object is not avalaible, close all the
1525 * streams and wakeup everithing waiting for.
1526 */
1527 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001528 si_shutw(si);
1529 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001530 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001531 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1532 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001533 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001534 }
1535
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001536 /* If we cant write, wakeup the pending write signals. */
1537 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001538 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001539
1540 /* If we cant read, wakeup the pending read signals. */
1541 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001542 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001543
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001544 /* if the connection is not estabkished, inform the stream that we want
1545 * to be notified whenever the connection completes.
1546 */
1547 if (!(c->flags & CO_FL_CONNECTED)) {
1548 si_applet_cant_get(si);
1549 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001550 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001551 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001552
1553 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001554 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001555
1556 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001557 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001558 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001559
1560 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001561 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001562 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001563}
1564
Willy Tarreau87b09662015-04-03 00:22:06 +02001565/* This function is called when the "struct stream" is destroyed.
1566 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001567 * Wake all the pending signals.
1568 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001569static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001570{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001571 struct xref *peer;
1572
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001573 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001574 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1575 if (peer)
1576 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001577
1578 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001579 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1580 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001581}
1582
1583/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001584 * uses this object. If the stream does not exists, just quit.
1585 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001586 * pending signal can rest in the read and write lists. destroy
1587 * it.
1588 */
1589__LJMP static int hlua_socket_gc(lua_State *L)
1590{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001591 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001592 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001593 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001594
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001595 MAY_LJMP(check_args(L, 1, "__gc"));
1596
1597 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001598 peer = xref_get_peer_and_lock(&socket->xref);
1599 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001600 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001601 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001602
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001603 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001604 appctx->ctx.hlua_cosocket.die = 1;
1605 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001606
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001607 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001608 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001609 return 0;
1610}
1611
1612/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001613 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001614 */
sada05ed3302018-05-11 11:48:18 -07001615__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001616{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001617 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001618 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001619 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001620
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001621 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001622
1623 /* Check if we run on the same thread than the xreator thread.
1624 * We cannot access to the socket if the thread is different.
1625 */
1626 if (socket->tid != tid)
1627 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1628
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001629 peer = xref_get_peer_and_lock(&socket->xref);
1630 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001631 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001632 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001633
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001634 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001635 appctx->ctx.hlua_cosocket.die = 1;
1636 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001637
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001638 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001639 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001640 return 0;
1641}
1642
sada05ed3302018-05-11 11:48:18 -07001643/* The close function calls close_helper.
1644 */
1645__LJMP static int hlua_socket_close(lua_State *L)
1646{
1647 MAY_LJMP(check_args(L, 1, "close"));
1648 return hlua_socket_close_helper(L);
1649}
1650
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001651/* This Lua function assumes that the stack contain three parameters.
1652 * 1 - USERDATA containing a struct socket
1653 * 2 - INTEGER with values of the macro defined below
1654 * If the integer is -1, we must read at most one line.
1655 * If the integer is -2, we ust read all the data until the
1656 * end of the stream.
1657 * If the integer is positive value, we must read a number of
1658 * bytes corresponding to this value.
1659 */
1660#define HLSR_READ_LINE (-1)
1661#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001662__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001663{
1664 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1665 int wanted = lua_tointeger(L, 2);
1666 struct hlua *hlua = hlua_gethlua(L);
1667 struct appctx *appctx;
1668 int len;
1669 int nblk;
1670 char *blk1;
1671 int len1;
1672 char *blk2;
1673 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001674 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001675 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001676 struct stream_interface *si;
1677 struct stream *s;
1678 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001679
1680 /* Check if this lua stack is schedulable. */
1681 if (!hlua || !hlua->task)
1682 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1683 "'frontend', 'backend' or 'task'"));
1684
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001685 /* Check if we run on the same thread than the xreator thread.
1686 * We cannot access to the socket if the thread is different.
1687 */
1688 if (socket->tid != tid)
1689 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1690
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001691 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001692 peer = xref_get_peer_and_lock(&socket->xref);
1693 if (!peer)
1694 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001695 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1696 si = appctx->owner;
1697 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001698
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001699 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001700 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001701 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001702 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001703 if (nblk < 0) /* Connection close. */
1704 goto connection_closed;
1705 if (nblk == 0) /* No data avalaible. */
1706 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001707
1708 /* remove final \r\n. */
1709 if (nblk == 1) {
1710 if (blk1[len1-1] == '\n') {
1711 len1--;
1712 skip_at_end++;
1713 if (blk1[len1-1] == '\r') {
1714 len1--;
1715 skip_at_end++;
1716 }
1717 }
1718 }
1719 else {
1720 if (blk2[len2-1] == '\n') {
1721 len2--;
1722 skip_at_end++;
1723 if (blk2[len2-1] == '\r') {
1724 len2--;
1725 skip_at_end++;
1726 }
1727 }
1728 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001729 }
1730
1731 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001732 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001733 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001734 if (nblk < 0) /* Connection close. */
1735 goto connection_closed;
1736 if (nblk == 0) /* No data avalaible. */
1737 goto connection_empty;
1738 }
1739
1740 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001741 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001742 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001743 if (nblk < 0) /* Connection close. */
1744 goto connection_closed;
1745 if (nblk == 0) /* No data avalaible. */
1746 goto connection_empty;
1747
1748 if (len1 > wanted) {
1749 nblk = 1;
1750 len1 = wanted;
1751 } if (nblk == 2 && len1 + len2 > wanted)
1752 len2 = wanted - len1;
1753 }
1754
1755 len = len1;
1756
1757 luaL_addlstring(&socket->b, blk1, len1);
1758 if (nblk == 2) {
1759 len += len2;
1760 luaL_addlstring(&socket->b, blk2, len2);
1761 }
1762
1763 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001764 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001765
1766 /* Don't wait anything. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001767 stream_int_notify(&s->si[0]);
1768 stream_int_update_applet(&s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001769
1770 /* If the pattern reclaim to read all the data
1771 * in the connection, got out.
1772 */
1773 if (wanted == HLSR_READ_ALL)
1774 goto connection_empty;
1775 else if (wanted >= 0 && len < wanted)
1776 goto connection_empty;
1777
1778 /* Return result. */
1779 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001780 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001781 return 1;
1782
1783connection_closed:
1784
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001785 xref_unlock(&socket->xref, peer);
1786
1787no_peer:
1788
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001789 /* If the buffer containds data. */
1790 if (socket->b.n > 0) {
1791 luaL_pushresult(&socket->b);
1792 return 1;
1793 }
1794 lua_pushnil(L);
1795 lua_pushstring(L, "connection closed.");
1796 return 2;
1797
1798connection_empty:
1799
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001800 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001801 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1802 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001803 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001804 }
1805 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001806 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001807 return 0;
1808}
1809
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001810/* This Lua function gets two parameters. The first one can be string
1811 * or a number. If the string is "*l", the user requires one line. If
1812 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001813 * If the value is a number, the user require a number of bytes equal
1814 * to the value. The default value is "*l" (a line).
1815 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001816 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001817 * integer takes this values:
1818 * -1 : read a line
1819 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001820 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001821 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001822 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001823 * concatenated with the read data.
1824 */
1825__LJMP static int hlua_socket_receive(struct lua_State *L)
1826{
1827 int wanted = HLSR_READ_LINE;
1828 const char *pattern;
1829 int type;
1830 char *error;
1831 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001832 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001833
1834 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1835 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1836
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001837 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001838
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001839 /* Check if we run on the same thread than the xreator thread.
1840 * We cannot access to the socket if the thread is different.
1841 */
1842 if (socket->tid != tid)
1843 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1844
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001845 /* check for pattern. */
1846 if (lua_gettop(L) >= 2) {
1847 type = lua_type(L, 2);
1848 if (type == LUA_TSTRING) {
1849 pattern = lua_tostring(L, 2);
1850 if (strcmp(pattern, "*a") == 0)
1851 wanted = HLSR_READ_ALL;
1852 else if (strcmp(pattern, "*l") == 0)
1853 wanted = HLSR_READ_LINE;
1854 else {
1855 wanted = strtoll(pattern, &error, 10);
1856 if (*error != '\0')
1857 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1858 }
1859 }
1860 else if (type == LUA_TNUMBER) {
1861 wanted = lua_tointeger(L, 2);
1862 if (wanted < 0)
1863 WILL_LJMP(luaL_error(L, "Unsupported size."));
1864 }
1865 }
1866
1867 /* Set pattern. */
1868 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01001869
1870 /* Check if we would replace the top by itself. */
1871 if (lua_gettop(L) != 2)
1872 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001873
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001874 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001875 luaL_buffinit(L, &socket->b);
1876
1877 /* Check prefix. */
1878 if (lua_gettop(L) >= 3) {
1879 if (lua_type(L, 3) != LUA_TSTRING)
1880 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1881 pattern = lua_tolstring(L, 3, &len);
1882 luaL_addlstring(&socket->b, pattern, len);
1883 }
1884
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001885 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001886}
1887
1888/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08001889 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001890 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001891static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001892{
1893 struct hlua_socket *socket;
1894 struct hlua *hlua = hlua_gethlua(L);
1895 struct appctx *appctx;
1896 size_t buf_len;
1897 const char *buf;
1898 int len;
1899 int send_len;
1900 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001901 struct xref *peer;
1902 struct stream_interface *si;
1903 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001904
1905 /* Check if this lua stack is schedulable. */
1906 if (!hlua || !hlua->task)
1907 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1908 "'frontend', 'backend' or 'task'"));
1909
1910 /* Get object */
1911 socket = MAY_LJMP(hlua_checksocket(L, 1));
1912 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001913 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001914
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001915 /* Check if we run on the same thread than the xreator thread.
1916 * We cannot access to the socket if the thread is different.
1917 */
1918 if (socket->tid != tid)
1919 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1920
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001921 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001922 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001923 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001924 lua_pushinteger(L, -1);
1925 return 1;
1926 }
1927 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1928 si = appctx->owner;
1929 s = si_strm(si);
1930
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001931 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001932 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001933 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001934 lua_pushinteger(L, -1);
1935 return 1;
1936 }
1937
1938 /* Update the input buffer data. */
1939 buf += sent;
1940 send_len = buf_len - sent;
1941
1942 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001943 if (sent >= buf_len) {
1944 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001945 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001946 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001947
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001948 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1949 * the request buffer if its not required.
1950 */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001951 if (s->req.buf->size == 0) {
Christopher Faulet33834b12016-12-19 09:29:06 +01001952 appctx = hlua->task->context;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001953 if (!channel_alloc_buffer(&s->req, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01001954 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001955 }
1956
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001957 /* Check for avalaible space. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001958 len = buffer_total_space(s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01001959 if (len <= 0) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001960 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001961 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
1962 xref_unlock(&socket->xref, peer);
Christopher Faulet33834b12016-12-19 09:29:06 +01001963 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001964 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001965 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01001966 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001967
1968 /* send data */
1969 if (len < send_len)
1970 send_len = len;
Willy Tarreau06d80a92017-10-19 14:32:15 +02001971 len = ci_putblk(&s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001972
1973 /* "Not enough space" (-1), "Buffer too little to contain
1974 * the data" (-2) are not expected because the available length
1975 * is tested.
1976 * Other unknown error are also not expected.
1977 */
1978 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001979 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001980 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001981
sada05ed3302018-05-11 11:48:18 -07001982 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001983 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001984 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001985 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001986 return 1;
1987 }
1988
1989 /* update buffers. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001990 stream_int_notify(&s->si[0]);
1991 stream_int_update_applet(&s->si[0]);
Willy Tarreaude70fa12015-09-26 11:25:05 +02001992
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001993 s->req.rex = TICK_ETERNITY;
1994 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001995
1996 /* Update length sent. */
1997 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001998 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001999
2000 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002001 if (sent + len >= buf_len) {
2002 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002003 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002004 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002005
2006hlua_socket_write_yield_return:
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002007 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002008 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002009 return 0;
2010}
2011
2012/* This function initiate the send of data. It just check the input
2013 * parameters and push an integer in the Lua stack that contain the
2014 * amount of data writed in the buffer. This is used by the function
2015 * "hlua_socket_write_yield" that can yield.
2016 *
2017 * The Lua function gets between 3 and 4 parameters. The first one is
2018 * the associated object. The second is a string buffer. The third is
2019 * a facultative integer that represents where is the buffer position
2020 * of the start of the data that can send. The first byte is the
2021 * position "1". The default value is "1". The fourth argument is a
2022 * facultative integer that represents where is the buffer position
2023 * of the end of the data that can send. The default is the last byte.
2024 */
2025static int hlua_socket_send(struct lua_State *L)
2026{
2027 int i;
2028 int j;
2029 const char *buf;
2030 size_t buf_len;
2031
2032 /* Check number of arguments. */
2033 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2034 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2035
2036 /* Get the string. */
2037 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2038
2039 /* Get and check j. */
2040 if (lua_gettop(L) == 4) {
2041 j = MAY_LJMP(luaL_checkinteger(L, 4));
2042 if (j < 0)
2043 j = buf_len + j + 1;
2044 if (j > buf_len)
2045 j = buf_len + 1;
2046 lua_pop(L, 1);
2047 }
2048 else
2049 j = buf_len;
2050
2051 /* Get and check i. */
2052 if (lua_gettop(L) == 3) {
2053 i = MAY_LJMP(luaL_checkinteger(L, 3));
2054 if (i < 0)
2055 i = buf_len + i + 1;
2056 if (i > buf_len)
2057 i = buf_len + 1;
2058 lua_pop(L, 1);
2059 } else
2060 i = 1;
2061
2062 /* Check bth i and j. */
2063 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002064 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002065 return 1;
2066 }
2067 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002068 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002069 return 1;
2070 }
2071 if (i == 0)
2072 i = 1;
2073 if (j == 0)
2074 j = 1;
2075
2076 /* Pop the string. */
2077 lua_pop(L, 1);
2078
2079 /* Update the buffer length. */
2080 buf += i - 1;
2081 buf_len = j - i + 1;
2082 lua_pushlstring(L, buf, buf_len);
2083
2084 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002085 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002086
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002087 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002088}
2089
Willy Tarreau22b0a682015-06-17 19:43:49 +02002090#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002091__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2092{
2093 static char buffer[SOCKET_INFO_MAX_LEN];
2094 int ret;
2095 int len;
2096 char *p;
2097
2098 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2099 if (ret <= 0) {
2100 lua_pushnil(L);
2101 return 1;
2102 }
2103
2104 if (ret == AF_UNIX) {
2105 lua_pushstring(L, buffer+1);
2106 return 1;
2107 }
2108 else if (ret == AF_INET6) {
2109 buffer[0] = '[';
2110 len = strlen(buffer);
2111 buffer[len] = ']';
2112 len++;
2113 buffer[len] = ':';
2114 len++;
2115 p = buffer;
2116 }
2117 else if (ret == AF_INET) {
2118 p = buffer + 1;
2119 len = strlen(p);
2120 p[len] = ':';
2121 len++;
2122 }
2123 else {
2124 lua_pushnil(L);
2125 return 1;
2126 }
2127
2128 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2129 lua_pushnil(L);
2130 return 1;
2131 }
2132
2133 lua_pushstring(L, p);
2134 return 1;
2135}
2136
2137/* Returns information about the peer of the connection. */
2138__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2139{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002140 struct hlua_socket *socket;
2141 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002142 struct xref *peer;
2143 struct appctx *appctx;
2144 struct stream_interface *si;
2145 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002146 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002147
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002148 MAY_LJMP(check_args(L, 1, "getpeername"));
2149
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002150 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002151
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002152 /* Check if we run on the same thread than the xreator thread.
2153 * We cannot access to the socket if the thread is different.
2154 */
2155 if (socket->tid != tid)
2156 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2157
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002158 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002159 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002160 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002161 lua_pushnil(L);
2162 return 1;
2163 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002164 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2165 si = appctx->owner;
2166 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002167
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002168 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002169 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002170 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002171 lua_pushnil(L);
2172 return 1;
2173 }
2174
Willy Tarreaua71f6422016-11-16 17:00:14 +01002175 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002176 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002177 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002178 lua_pushnil(L);
2179 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002180 }
2181
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002182 ret = MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2183 xref_unlock(&socket->xref, peer);
2184 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002185}
2186
2187/* Returns information about my connection side. */
2188static int hlua_socket_getsockname(struct lua_State *L)
2189{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002190 struct hlua_socket *socket;
2191 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002192 struct appctx *appctx;
2193 struct xref *peer;
2194 struct stream_interface *si;
2195 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002196 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002197
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002198 MAY_LJMP(check_args(L, 1, "getsockname"));
2199
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002200 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002201
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002202 /* Check if we run on the same thread than the xreator thread.
2203 * We cannot access to the socket if the thread is different.
2204 */
2205 if (socket->tid != tid)
2206 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2207
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002208 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002209 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002210 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002211 lua_pushnil(L);
2212 return 1;
2213 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002214 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2215 si = appctx->owner;
2216 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002217
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002218 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002219 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002220 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002221 lua_pushnil(L);
2222 return 1;
2223 }
2224
Willy Tarreaua71f6422016-11-16 17:00:14 +01002225 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002227 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002228 lua_pushnil(L);
2229 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002230 }
2231
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002232 ret = hlua_socket_info(L, &conn->addr.from);
2233 xref_unlock(&socket->xref, peer);
2234 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002235}
2236
2237/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002238static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002239 .obj_type = OBJ_TYPE_APPLET,
2240 .name = "<LUA_TCP>",
2241 .fct = hlua_socket_handler,
2242 .release = hlua_socket_release,
2243};
2244
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002245__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002246{
2247 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2248 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002249 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002250 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002251 struct stream_interface *si;
2252 struct stream *s;
2253
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002254 /* Check if we run on the same thread than the xreator thread.
2255 * We cannot access to the socket if the thread is different.
2256 */
2257 if (socket->tid != tid)
2258 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2259
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002260 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002261 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002262 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002263 lua_pushnil(L);
2264 lua_pushstring(L, "Can't connect");
2265 return 2;
2266 }
2267 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2268 si = appctx->owner;
2269 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002270
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 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002274 if (socket->tid != tid) {
2275 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002276 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002277 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002278
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002279 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002280 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002281 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002282 lua_pushnil(L);
2283 lua_pushstring(L, "Can't connect");
2284 return 2;
2285 }
2286
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002287 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002288
2289 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002290 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002291 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002292 lua_pushinteger(L, 1);
2293 return 1;
2294 }
2295
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002296 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2297 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002298 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002299 }
2300 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002301 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002302 return 0;
2303}
2304
2305/* This function fail or initite the connection. */
2306__LJMP static int hlua_socket_connect(struct lua_State *L)
2307{
2308 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002309 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002310 const char *ip;
2311 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002312 struct hlua *hlua;
2313 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002314 int low, high;
2315 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002316 struct xref *peer;
2317 struct stream_interface *si;
2318 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002319
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002320 if (lua_gettop(L) < 2)
2321 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002322
2323 /* Get args. */
2324 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002325
2326 /* Check if we run on the same thread than the xreator thread.
2327 * We cannot access to the socket if the thread is different.
2328 */
2329 if (socket->tid != tid)
2330 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2331
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002332 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002333 if (lua_gettop(L) >= 3) {
2334 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002335 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002336
Tim Duesterhus6edab862018-01-06 19:04:45 +01002337 /* Force the ip to end with a colon, to support IPv6 addresses
2338 * that are not enclosed within square brackets.
2339 */
2340 if (port > 0) {
2341 luaL_buffinit(L, &b);
2342 luaL_addstring(&b, ip);
2343 luaL_addchar(&b, ':');
2344 luaL_pushresult(&b);
2345 ip = lua_tolstring(L, lua_gettop(L), NULL);
2346 }
2347 }
2348
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002349 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002350 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002351 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002352 lua_pushnil(L);
2353 return 1;
2354 }
2355 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2356 si = appctx->owner;
2357 s = si_strm(si);
2358
2359 /* Initialise connection. */
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002360 conn = cs_conn(si_alloc_cs(&s->si[1], NULL));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002361 if (!conn) {
2362 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002363 WILL_LJMP(luaL_error(L, "connect: internal error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002364 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002365
Willy Tarreau3adac082015-09-26 17:51:09 +02002366 /* needed for the connection not to be closed */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002367 conn->target = s->target;
Willy Tarreau3adac082015-09-26 17:51:09 +02002368
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002369 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002370 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002371 if (!addr) {
2372 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002373 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002374 }
2375 if (low != high) {
2376 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002377 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002378 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002379 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002380
2381 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002382 if (low == 0) {
2383 if (conn->addr.to.ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002384 if (port == -1) {
2385 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002386 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002387 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002388 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2389 } else if (conn->addr.to.ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002390 if (port == -1) {
2391 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002392 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002393 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002394 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2395 }
2396 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002397
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002398 hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002399 appctx = objt_appctx(s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002400
2401 /* inform the stream that we want to be notified whenever the
2402 * connection completes.
2403 */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002404 si_applet_cant_get(&s->si[0]);
2405 si_applet_cant_put(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002406 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002407
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002408 hlua->flags |= HLUA_MUST_GC;
2409
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002410 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2411 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002412 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002413 }
2414 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002415
2416 task_wakeup(s->task, TASK_WOKEN_INIT);
2417 /* Return yield waiting for connection. */
2418
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002419 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002420
2421 return 0;
2422}
2423
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002424#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002425__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2426{
2427 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002428 struct xref *peer;
2429 struct appctx *appctx;
2430 struct stream_interface *si;
2431 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002432
2433 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2434 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002435
2436 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002437 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002438 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002439 lua_pushnil(L);
2440 return 1;
2441 }
2442 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2443 si = appctx->owner;
2444 s = si_strm(si);
2445
2446 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002447 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002448 return MAY_LJMP(hlua_socket_connect(L));
2449}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002450#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002451
2452__LJMP static int hlua_socket_setoption(struct lua_State *L)
2453{
2454 return 0;
2455}
2456
2457__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2458{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002459 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002460 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002461 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002462 struct xref *peer;
2463 struct appctx *appctx;
2464 struct stream_interface *si;
2465 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002466
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002467 MAY_LJMP(check_args(L, 2, "settimeout"));
2468
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002469 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002470
2471 /* round up for inputs that are fractions and convert to millis */
2472 dtmout = (0.5 + MAY_LJMP(luaL_checknumber(L, 2))) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002473
Thierry Fournier17a921b2018-03-08 09:59:02 +01002474 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002475 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002476 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2477
Mark Lakes56cc1252018-03-27 09:48:06 +02002478 if (dtmout > INT_MAX) /* overflow check */
2479 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d", INT_MAX));
2480
2481 tmout = MS_TO_TICKS((int)dtmout);
2482
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002483 /* Check if we run on the same thread than the xreator thread.
2484 * We cannot access to the socket if the thread is different.
2485 */
2486 if (socket->tid != tid)
2487 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2488
Mark Lakes56cc1252018-03-27 09:48:06 +02002489 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002490 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002491 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002492 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2493 WILL_LJMP(lua_error(L));
2494 return 0;
2495 }
2496 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2497 si = appctx->owner;
2498 s = si_strm(si);
2499
2500 s->req.rto = tmout;
2501 s->req.wto = tmout;
2502 s->res.rto = tmout;
2503 s->res.wto = tmout;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002504 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002505
Thierry Fourniere9636f12018-03-08 09:54:32 +01002506 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002507 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002508}
2509
2510__LJMP static int hlua_socket_new(lua_State *L)
2511{
2512 struct hlua_socket *socket;
2513 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002514 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002515 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002516
2517 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002518 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002519 hlua_pusherror(L, "socket: full stack");
2520 goto out_fail_conf;
2521 }
2522
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002523 /* Create the object: obj[0] = userdata. */
2524 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002525 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002526 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002527 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002528 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002529
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002530 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002531 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002532 hlua_pusherror(L, "socket: uninitialized pools.");
2533 goto out_fail_conf;
2534 }
2535
Willy Tarreau87b09662015-04-03 00:22:06 +02002536 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002537 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2538 lua_setmetatable(L, -2);
2539
Willy Tarreaud420a972015-04-06 00:39:18 +02002540 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002541 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002542 if (!appctx) {
2543 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002544 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002545 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002546
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002547 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002548 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002549 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2550 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002551
Willy Tarreaud420a972015-04-06 00:39:18 +02002552 /* Now create a session, task and stream for this applet */
2553 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2554 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002555 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002556 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002557 }
2558
Willy Tarreau87787ac2017-08-28 16:22:54 +02002559 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002560 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002561 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002562 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002563 }
2564
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002565 /* Initialise cross reference between stream and Lua socket object. */
2566 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002567
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002568 /* Configure "right" stream interface. this "si" is used to connect
2569 * and retrieve data from the server. The connection is initialized
2570 * with the "struct server".
2571 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002572 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002573
2574 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002575 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2576 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002577
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002578 return 1;
2579
Willy Tarreaud420a972015-04-06 00:39:18 +02002580 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002581 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002582 out_fail_sess:
2583 appctx_free(appctx);
2584 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002585 WILL_LJMP(lua_error(L));
2586 return 0;
2587}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002588
2589/*
2590 *
2591 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002592 * Class Channel
2593 *
2594 *
2595 */
2596
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002597/* The state between the channel data and the HTTP parser state can be
2598 * unconsistent, so reset the parser and call it again. Warning, this
2599 * action not revalidate the request and not send a 400 if the modified
2600 * resuest is not valid.
2601 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002602 * This function never fails. The direction is set using dir, which equals
2603 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002604 */
2605static void hlua_resynchonize_proto(struct stream *stream, int dir)
2606{
2607 /* Protocol HTTP. */
2608 if (stream->be->mode == PR_MODE_HTTP) {
2609
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002610 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002611 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002612 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002613 http_txn_reset_res(stream->txn);
2614
2615 if (stream->txn->hdr_idx.v)
2616 hdr_idx_init(&stream->txn->hdr_idx);
2617
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002618 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002619 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002620 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002621 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2622 }
2623}
2624
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002625/* This function is called before the Lua execution. It stores
2626 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002627 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002628static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002629{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002630 c->mode = stream->be->mode;
2631 switch (c->mode) {
2632 case PR_MODE_HTTP:
2633 c->data.http.dir = opt & SMP_OPT_DIR;
2634 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2635 c->data.http.state = stream->txn->req.msg_state;
2636 else
2637 c->data.http.state = stream->txn->rsp.msg_state;
2638 break;
2639 default:
2640 break;
2641 }
2642}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002643
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002644/* This function is called after the Lua execution. it
2645 * returns true if the parser state is consistent, otherwise,
2646 * it return false.
2647 *
2648 * In HTTP mode, the parser state must be in the same state
2649 * or greater when we exit the function. Even if we do a
2650 * control yield. This prevent to break the HTTP message
2651 * from the Lua code.
2652 */
2653static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2654{
2655 if (c->mode != stream->be->mode)
2656 return 0;
2657
2658 switch (c->mode) {
2659 case PR_MODE_HTTP:
2660 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002661 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002662 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2663 return stream->txn->req.msg_state >= c->data.http.state;
2664 else
2665 return stream->txn->rsp.msg_state >= c->data.http.state;
2666 default:
2667 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002668 }
2669 return 1;
2670}
2671
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002672/* Returns the struct hlua_channel join to the class channel in the
2673 * stack entry "ud" or throws an argument error.
2674 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002675__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002676{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002677 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002678}
2679
Willy Tarreau47860ed2015-03-10 14:07:50 +01002680/* Pushes the channel onto the top of the stack. If the stask does not have a
2681 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002682 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002683static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002684{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002685 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002686 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002687 return 0;
2688
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002689 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002690 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002691 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002692
2693 /* Pop a class sesison metatable and affect it to the userdata. */
2694 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2695 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002696 return 1;
2697}
2698
2699/* Duplicate all the data present in the input channel and put it
2700 * in a string LUA variables. Returns -1 and push a nil value in
2701 * the stack if the channel is closed and all the data are consumed,
2702 * returns 0 if no data are available, otherwise it returns the length
2703 * of the builded string.
2704 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002705static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002706{
2707 char *blk1;
2708 char *blk2;
2709 int len1;
2710 int len2;
2711 int ret;
2712 luaL_Buffer b;
2713
Willy Tarreau06d80a92017-10-19 14:32:15 +02002714 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002715 if (unlikely(ret == 0))
2716 return 0;
2717
2718 if (unlikely(ret < 0)) {
2719 lua_pushnil(L);
2720 return -1;
2721 }
2722
2723 luaL_buffinit(L, &b);
2724 luaL_addlstring(&b, blk1, len1);
2725 if (unlikely(ret == 2))
2726 luaL_addlstring(&b, blk2, len2);
2727 luaL_pushresult(&b);
2728
2729 if (unlikely(ret == 2))
2730 return len1 + len2;
2731 return len1;
2732}
2733
2734/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2735 * a yield. This function keep the data in the buffer.
2736 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002737__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002738{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002739 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002740
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002741 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2742
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002743 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002744 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002745 return 1;
2746}
2747
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002748/* Check arguments for the function "hlua_channel_dup_yield". */
2749__LJMP static int hlua_channel_dup(lua_State *L)
2750{
2751 MAY_LJMP(check_args(L, 1, "dup"));
2752 MAY_LJMP(hlua_checkchannel(L, 1));
2753 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2754}
2755
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002756/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2757 * a yield. This function consumes the data in the buffer. It returns
2758 * a string containing the data or a nil pointer if no data are available
2759 * and the channel is closed.
2760 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002761__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002762{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002763 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002764 int ret;
2765
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002766 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002767
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002768 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002769 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002770 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002771
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002772 if (unlikely(ret == -1))
2773 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002774
Willy Tarreau47860ed2015-03-10 14:07:50 +01002775 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002776 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002777 return 1;
2778}
2779
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002780/* Check arguments for the fucntion "hlua_channel_get_yield". */
2781__LJMP static int hlua_channel_get(lua_State *L)
2782{
2783 MAY_LJMP(check_args(L, 1, "get"));
2784 MAY_LJMP(hlua_checkchannel(L, 1));
2785 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2786}
2787
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002788/* This functions consumes and returns one line. If the channel is closed,
2789 * and the last data does not contains a final '\n', the data are returned
2790 * without the final '\n'. When no more data are avalaible, it returns nil
2791 * value.
2792 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002793__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002794{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002795 char *blk1;
2796 char *blk2;
2797 int len1;
2798 int len2;
2799 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002800 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002801 int ret;
2802 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002803
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002804 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2805
Willy Tarreau06d80a92017-10-19 14:32:15 +02002806 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002807 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002808 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002809
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002810 if (ret == -1) {
2811 lua_pushnil(L);
2812 return 1;
2813 }
2814
2815 luaL_buffinit(L, &b);
2816 luaL_addlstring(&b, blk1, len1);
2817 len = len1;
2818 if (unlikely(ret == 2)) {
2819 luaL_addlstring(&b, blk2, len2);
2820 len += len2;
2821 }
2822 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002823 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002824 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002825 return 1;
2826}
2827
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002828/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2829__LJMP static int hlua_channel_getline(lua_State *L)
2830{
2831 MAY_LJMP(check_args(L, 1, "getline"));
2832 MAY_LJMP(hlua_checkchannel(L, 1));
2833 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2834}
2835
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002836/* This function takes a string as input, and append it at the
2837 * input side of channel. If the data is too big, but a space
2838 * is probably available after sending some data, the function
2839 * yield. If the data is bigger than the buffer, or if the
2840 * channel is closed, it returns -1. otherwise, it returns the
2841 * amount of data writed.
2842 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002843__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002844{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002845 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002846 size_t len;
2847 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2848 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2849 int ret;
2850 int max;
2851
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002852 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2853 * the request buffer if its not required.
2854 */
2855 if (chn->buf->size == 0) {
2856 si_applet_cant_put(chn_prod(chn));
2857 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2858 }
2859
Willy Tarreau47860ed2015-03-10 14:07:50 +01002860 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002861 if (max > len - l)
2862 max = len - l;
2863
Willy Tarreau06d80a92017-10-19 14:32:15 +02002864 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002865 if (ret == -2 || ret == -3) {
2866 lua_pushinteger(L, -1);
2867 return 1;
2868 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002869 if (ret == -1) {
2870 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002871 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002872 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002873 l += ret;
2874 lua_pop(L, 1);
2875 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002876 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002877
Willy Tarreau47860ed2015-03-10 14:07:50 +01002878 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2879 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002880 /* There are no space avalaible, and the output buffer is empty.
2881 * in this case, we cannot add more data, so we cannot yield,
2882 * we return the amount of copyied data.
2883 */
2884 return 1;
2885 }
2886 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002887 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002888 return 1;
2889}
2890
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002891/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002892 * of the writed string, or -1 if the channel is closed or if the
2893 * buffer size is too little for the data.
2894 */
2895__LJMP static int hlua_channel_append(lua_State *L)
2896{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002897 size_t len;
2898
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002899 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002900 MAY_LJMP(hlua_checkchannel(L, 1));
2901 MAY_LJMP(luaL_checklstring(L, 2, &len));
2902 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002903 lua_pushinteger(L, 0);
2904
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002905 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002906}
2907
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002908/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002909 * his process by cleaning the buffer. The result is a replacement
2910 * of the current data. It returns the length of the writed string,
2911 * or -1 if the channel is closed or if the buffer size is too
2912 * little for the data.
2913 */
2914__LJMP static int hlua_channel_set(lua_State *L)
2915{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002916 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002917
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002918 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002919 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002920 lua_pushinteger(L, 0);
2921
Willy Tarreau47860ed2015-03-10 14:07:50 +01002922 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002923
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002924 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002925}
2926
2927/* Append data in the output side of the buffer. This data is immediatly
2928 * sent. The fcuntion returns the ammount of data writed. If the buffer
2929 * cannot contains the data, the function yield. The function returns -1
2930 * if the channel is closed.
2931 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002932__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002933{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002934 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002935 size_t len;
2936 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2937 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2938 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002939 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002940
Willy Tarreau47860ed2015-03-10 14:07:50 +01002941 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002942 lua_pushinteger(L, -1);
2943 return 1;
2944 }
2945
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002946 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2947 * the request buffer if its not required.
2948 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002949 if (chn->buf->size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002950 si_applet_cant_put(chn_prod(chn));
2951 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002952 }
2953
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002954 /* the writed data will be immediatly sent, so we can check
2955 * the avalaible space without taking in account the reserve.
2956 * The reserve is guaranted for the processing of incoming
2957 * data, because the buffer will be flushed.
2958 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002959 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002960
2961 /* If there are no space avalaible, and the output buffer is empty.
2962 * in this case, we cannot add more data, so we cannot yield,
2963 * we return the amount of copyied data.
2964 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002965 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002966 return 1;
2967
2968 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002969 if (max > len - l)
2970 max = len - l;
2971
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002972 /* The buffer avalaible size may be not contiguous. This test
2973 * detects a non contiguous buffer and realign it.
2974 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002975 if (bi_space_for_replace(chn->buf) < max)
2976 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002977
2978 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002979 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002980
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002981 /* buffer replace considers that the input part is filled.
2982 * so, I must forward these new data in the output part.
2983 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002984 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002985
2986 l += max;
2987 lua_pop(L, 1);
2988 lua_pushinteger(L, l);
2989
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002990 /* If there are no space avalaible, and the output buffer is empty.
2991 * in this case, we cannot add more data, so we cannot yield,
2992 * we return the amount of copyied data.
2993 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002994 max = chn->buf->size - buffer_len(chn->buf);
2995 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002996 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002997
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002998 if (l < len) {
2999 /* If we are waiting for space in the response buffer, we
3000 * must set the flag WAKERESWR. This flag required the task
3001 * wake up if any activity is detected on the response buffer.
3002 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003003 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003004 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003005 else
3006 HLUA_SET_WAKEREQWR(hlua);
3007 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003008 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003009
3010 return 1;
3011}
3012
3013/* Just a wraper of "_hlua_channel_send". This wrapper permits
3014 * yield the LUA process, and resume it without checking the
3015 * input arguments.
3016 */
3017__LJMP static int hlua_channel_send(lua_State *L)
3018{
3019 MAY_LJMP(check_args(L, 2, "send"));
3020 lua_pushinteger(L, 0);
3021
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003022 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003023}
3024
3025/* This function forward and amount of butes. The data pass from
3026 * the input side of the buffer to the output side, and can be
3027 * forwarded. This function never fails.
3028 *
3029 * The Lua function takes an amount of bytes to be forwarded in
3030 * imput. It returns the number of bytes forwarded.
3031 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003032__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003033{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003034 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003035 int len;
3036 int l;
3037 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003038 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003039
3040 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3041 len = MAY_LJMP(luaL_checkinteger(L, 2));
3042 l = MAY_LJMP(luaL_checkinteger(L, -1));
3043
3044 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01003045 if (max > chn->buf->i)
3046 max = chn->buf->i;
3047 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003048 l += max;
3049
3050 lua_pop(L, 1);
3051 lua_pushinteger(L, l);
3052
3053 /* Check if it miss bytes to forward. */
3054 if (l < len) {
3055 /* The the input channel or the output channel are closed, we
3056 * must return the amount of data forwarded.
3057 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003058 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003059 return 1;
3060
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003061 /* If we are waiting for space data in the response buffer, we
3062 * must set the flag WAKERESWR. This flag required the task
3063 * wake up if any activity is detected on the response buffer.
3064 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003065 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003066 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003067 else
3068 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003069
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003070 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01003071 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003072 }
3073
3074 return 1;
3075}
3076
3077/* Just check the input and prepare the stack for the previous
3078 * function "hlua_channel_forward_yield"
3079 */
3080__LJMP static int hlua_channel_forward(lua_State *L)
3081{
3082 MAY_LJMP(check_args(L, 2, "forward"));
3083 MAY_LJMP(hlua_checkchannel(L, 1));
3084 MAY_LJMP(luaL_checkinteger(L, 2));
3085
3086 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003087 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003088}
3089
3090/* Just returns the number of bytes available in the input
3091 * side of the buffer. This function never fails.
3092 */
3093__LJMP static int hlua_channel_get_in_len(lua_State *L)
3094{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003095 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003096
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003097 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003098 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01003099 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003100 return 1;
3101}
3102
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003103/* Returns true if the channel is full. */
3104__LJMP static int hlua_channel_is_full(lua_State *L)
3105{
3106 struct channel *chn;
3107 int rem;
3108
3109 MAY_LJMP(check_args(L, 1, "is_full"));
3110 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3111
3112 rem = chn->buf->size;
3113 rem -= chn->buf->o; /* Output size */
3114 rem -= chn->buf->i; /* Input size */
3115 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
3116
3117 lua_pushboolean(L, rem <= 0);
3118 return 1;
3119}
3120
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003121/* Just returns the number of bytes available in the output
3122 * side of the buffer. This function never fails.
3123 */
3124__LJMP static int hlua_channel_get_out_len(lua_State *L)
3125{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003126 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003127
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003128 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003129 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01003130 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003131 return 1;
3132}
3133
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003134/*
3135 *
3136 *
3137 * Class Fetches
3138 *
3139 *
3140 */
3141
3142/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003143 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003144 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003145__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003146{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003147 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003148}
3149
3150/* This function creates and push in the stack a fetch object according
3151 * with a current TXN.
3152 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003153static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003154{
Willy Tarreau7073c472015-04-06 11:15:40 +02003155 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003156
3157 /* Check stack size. */
3158 if (!lua_checkstack(L, 3))
3159 return 0;
3160
3161 /* Create the object: obj[0] = userdata.
3162 * Note that the base of the Fetches object is the
3163 * transaction object.
3164 */
3165 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003166 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003167 lua_rawseti(L, -2, 0);
3168
Willy Tarreau7073c472015-04-06 11:15:40 +02003169 hsmp->s = txn->s;
3170 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003171 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003172 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003173
3174 /* Pop a class sesison metatable and affect it to the userdata. */
3175 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3176 lua_setmetatable(L, -2);
3177
3178 return 1;
3179}
3180
3181/* This function is an LUA binding. It is called with each sample-fetch.
3182 * It uses closure argument to store the associated sample-fetch. It
3183 * returns only one argument or throws an error. An error is thrown
3184 * only if an error is encountered during the argument parsing. If
3185 * the "sample-fetch" function fails, nil is returned.
3186 */
3187__LJMP static int hlua_run_sample_fetch(lua_State *L)
3188{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003189 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003190 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003191 struct arg args[ARGM_NBARGS + 1];
3192 int i;
3193 struct sample smp;
3194
3195 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003196 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003197
3198 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003199 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003200
Thierry FOURNIERca988662015-12-20 18:43:03 +01003201 /* Check execution authorization. */
3202 if (f->use & SMP_USE_HTTP_ANY &&
3203 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3204 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3205 "is not available in Lua services", f->kw);
3206 WILL_LJMP(lua_error(L));
3207 }
3208
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003209 /* Get extra arguments. */
3210 for (i = 0; i < lua_gettop(L) - 1; i++) {
3211 if (i >= ARGM_NBARGS)
3212 break;
3213 hlua_lua2arg(L, i + 2, &args[i]);
3214 }
3215 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003216 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003217
3218 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003219 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003220
3221 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003222 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003223 lua_pushfstring(L, "error in arguments");
3224 WILL_LJMP(lua_error(L));
3225 }
3226
3227 /* Initialise the sample. */
3228 memset(&smp, 0, sizeof(smp));
3229
3230 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003231 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003232 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003233 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003234 lua_pushstring(L, "");
3235 else
3236 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003237 return 1;
3238 }
3239
3240 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003241 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003242 hlua_smp2lua_str(L, &smp);
3243 else
3244 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003245 return 1;
3246}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003247
3248/*
3249 *
3250 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003251 * Class Converters
3252 *
3253 *
3254 */
3255
3256/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003257 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003258 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003259__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003260{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003261 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003262}
3263
3264/* This function creates and push in the stack a Converters object
3265 * according with a current TXN.
3266 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003267static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003268{
Willy Tarreau7073c472015-04-06 11:15:40 +02003269 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003270
3271 /* Check stack size. */
3272 if (!lua_checkstack(L, 3))
3273 return 0;
3274
3275 /* Create the object: obj[0] = userdata.
3276 * Note that the base of the Converters object is the
3277 * same than the TXN object.
3278 */
3279 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003280 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003281 lua_rawseti(L, -2, 0);
3282
Willy Tarreau7073c472015-04-06 11:15:40 +02003283 hsmp->s = txn->s;
3284 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003285 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003286 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003287
Willy Tarreau87b09662015-04-03 00:22:06 +02003288 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003289 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3290 lua_setmetatable(L, -2);
3291
3292 return 1;
3293}
3294
3295/* This function is an LUA binding. It is called with each converter.
3296 * It uses closure argument to store the associated converter. It
3297 * returns only one argument or throws an error. An error is thrown
3298 * only if an error is encountered during the argument parsing. If
3299 * the converter function function fails, nil is returned.
3300 */
3301__LJMP static int hlua_run_sample_conv(lua_State *L)
3302{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003303 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003304 struct sample_conv *conv;
3305 struct arg args[ARGM_NBARGS + 1];
3306 int i;
3307 struct sample smp;
3308
3309 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003310 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003311
3312 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003313 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003314
3315 /* Get extra arguments. */
3316 for (i = 0; i < lua_gettop(L) - 2; i++) {
3317 if (i >= ARGM_NBARGS)
3318 break;
3319 hlua_lua2arg(L, i + 3, &args[i]);
3320 }
3321 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003322 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003323
3324 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003325 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003326
3327 /* Run the special args checker. */
3328 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3329 hlua_pusherror(L, "error in arguments");
3330 WILL_LJMP(lua_error(L));
3331 }
3332
3333 /* Initialise the sample. */
3334 if (!hlua_lua2smp(L, 2, &smp)) {
3335 hlua_pusherror(L, "error in the input argument");
3336 WILL_LJMP(lua_error(L));
3337 }
3338
Willy Tarreau1777ea62016-03-10 16:15:46 +01003339 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3340
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003341 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003342 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003343 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003344 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003345 WILL_LJMP(lua_error(L));
3346 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003347 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3348 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003349 hlua_pusherror(L, "error during the input argument casting");
3350 WILL_LJMP(lua_error(L));
3351 }
3352
3353 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003354 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003355 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003356 lua_pushstring(L, "");
3357 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003358 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003359 return 1;
3360 }
3361
3362 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003363 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003364 hlua_smp2lua_str(L, &smp);
3365 else
3366 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003367 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003368}
3369
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003370/*
3371 *
3372 *
3373 * Class AppletTCP
3374 *
3375 *
3376 */
3377
3378/* Returns a struct hlua_txn if the stack entry "ud" is
3379 * a class stream, otherwise it throws an error.
3380 */
3381__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3382{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003383 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003384}
3385
3386/* This function creates and push in the stack an Applet object
3387 * according with a current TXN.
3388 */
3389static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3390{
3391 struct hlua_appctx *appctx;
3392 struct stream_interface *si = ctx->owner;
3393 struct stream *s = si_strm(si);
3394 struct proxy *p = s->be;
3395
3396 /* Check stack size. */
3397 if (!lua_checkstack(L, 3))
3398 return 0;
3399
3400 /* Create the object: obj[0] = userdata.
3401 * Note that the base of the Converters object is the
3402 * same than the TXN object.
3403 */
3404 lua_newtable(L);
3405 appctx = lua_newuserdata(L, sizeof(*appctx));
3406 lua_rawseti(L, -2, 0);
3407 appctx->appctx = ctx;
3408 appctx->htxn.s = s;
3409 appctx->htxn.p = p;
3410
3411 /* Create the "f" field that contains a list of fetches. */
3412 lua_pushstring(L, "f");
3413 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3414 return 0;
3415 lua_settable(L, -3);
3416
3417 /* Create the "sf" field that contains a list of stringsafe fetches. */
3418 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003419 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003420 return 0;
3421 lua_settable(L, -3);
3422
3423 /* Create the "c" field that contains a list of converters. */
3424 lua_pushstring(L, "c");
3425 if (!hlua_converters_new(L, &appctx->htxn, 0))
3426 return 0;
3427 lua_settable(L, -3);
3428
3429 /* Create the "sc" field that contains a list of stringsafe converters. */
3430 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003431 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003432 return 0;
3433 lua_settable(L, -3);
3434
3435 /* Pop a class stream metatable and affect it to the table. */
3436 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3437 lua_setmetatable(L, -2);
3438
3439 return 1;
3440}
3441
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003442__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3443{
3444 struct hlua_appctx *appctx;
3445 struct stream *s;
3446 const char *name;
3447 size_t len;
3448 struct sample smp;
3449
3450 MAY_LJMP(check_args(L, 3, "set_var"));
3451
3452 /* It is useles to retrieve the stream, but this function
3453 * runs only in a stream context.
3454 */
3455 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3456 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3457 s = appctx->htxn.s;
3458
3459 /* Converts the third argument in a sample. */
3460 hlua_lua2smp(L, 3, &smp);
3461
3462 /* Store the sample in a variable. */
3463 smp_set_owner(&smp, s->be, s->sess, s, 0);
3464 vars_set_by_name(name, len, &smp);
3465 return 0;
3466}
3467
3468__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3469{
3470 struct hlua_appctx *appctx;
3471 struct stream *s;
3472 const char *name;
3473 size_t len;
3474 struct sample smp;
3475
3476 MAY_LJMP(check_args(L, 2, "unset_var"));
3477
3478 /* It is useles to retrieve the stream, but this function
3479 * runs only in a stream context.
3480 */
3481 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3482 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3483 s = appctx->htxn.s;
3484
3485 /* Unset the variable. */
3486 smp_set_owner(&smp, s->be, s->sess, s, 0);
3487 vars_unset_by_name(name, len, &smp);
3488 return 0;
3489}
3490
3491__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3492{
3493 struct hlua_appctx *appctx;
3494 struct stream *s;
3495 const char *name;
3496 size_t len;
3497 struct sample smp;
3498
3499 MAY_LJMP(check_args(L, 2, "get_var"));
3500
3501 /* It is useles to retrieve the stream, but this function
3502 * runs only in a stream context.
3503 */
3504 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3505 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3506 s = appctx->htxn.s;
3507
3508 smp_set_owner(&smp, s->be, s->sess, s, 0);
3509 if (!vars_get_by_name(name, len, &smp)) {
3510 lua_pushnil(L);
3511 return 1;
3512 }
3513
3514 return hlua_smp2lua(L, &smp);
3515}
3516
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003517__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3518{
3519 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3520 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003521 struct hlua *hlua;
3522
3523 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003524 if (!s->hlua)
3525 return 0;
3526 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003527
3528 MAY_LJMP(check_args(L, 2, "set_priv"));
3529
3530 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003531 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003532
3533 /* Get and store new value. */
3534 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3535 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3536
3537 return 0;
3538}
3539
3540__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3541{
3542 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3543 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003544 struct hlua *hlua;
3545
3546 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003547 if (!s->hlua) {
3548 lua_pushnil(L);
3549 return 1;
3550 }
3551 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003552
3553 /* Push configuration index in the stack. */
3554 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3555
3556 return 1;
3557}
3558
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003559/* If expected data not yet available, it returns a yield. This function
3560 * consumes the data in the buffer. It returns a string containing the
3561 * data. This string can be empty.
3562 */
3563__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3564{
3565 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3566 struct stream_interface *si = appctx->appctx->owner;
3567 int ret;
3568 char *blk1;
3569 int len1;
3570 char *blk2;
3571 int len2;
3572
3573 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003574 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003575
3576 /* Data not yet avalaible. return yield. */
3577 if (ret == 0) {
3578 si_applet_cant_get(si);
3579 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3580 }
3581
3582 /* End of data: commit the total strings and return. */
3583 if (ret < 0) {
3584 luaL_pushresult(&appctx->b);
3585 return 1;
3586 }
3587
3588 /* Ensure that the block 2 length is usable. */
3589 if (ret == 1)
3590 len2 = 0;
3591
3592 /* dont check the max length read and dont check. */
3593 luaL_addlstring(&appctx->b, blk1, len1);
3594 luaL_addlstring(&appctx->b, blk2, len2);
3595
3596 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003597 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003598 luaL_pushresult(&appctx->b);
3599 return 1;
3600}
3601
3602/* Check arguments for the fucntion "hlua_channel_get_yield". */
3603__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3604{
3605 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3606
3607 /* Initialise the string catenation. */
3608 luaL_buffinit(L, &appctx->b);
3609
3610 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3611}
3612
3613/* If expected data not yet available, it returns a yield. This function
3614 * consumes the data in the buffer. It returns a string containing the
3615 * data. This string can be empty.
3616 */
3617__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3618{
3619 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3620 struct stream_interface *si = appctx->appctx->owner;
3621 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3622 int ret;
3623 char *blk1;
3624 int len1;
3625 char *blk2;
3626 int len2;
3627
3628 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003629 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003630
3631 /* Data not yet avalaible. return yield. */
3632 if (ret == 0) {
3633 si_applet_cant_get(si);
3634 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3635 }
3636
3637 /* End of data: commit the total strings and return. */
3638 if (ret < 0) {
3639 luaL_pushresult(&appctx->b);
3640 return 1;
3641 }
3642
3643 /* Ensure that the block 2 length is usable. */
3644 if (ret == 1)
3645 len2 = 0;
3646
3647 if (len == -1) {
3648
3649 /* If len == -1, catenate all the data avalaile and
3650 * yield because we want to get all the data until
3651 * the end of data stream.
3652 */
3653 luaL_addlstring(&appctx->b, blk1, len1);
3654 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003655 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003656 si_applet_cant_get(si);
3657 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3658
3659 } else {
3660
3661 /* Copy the fisrt block caping to the length required. */
3662 if (len1 > len)
3663 len1 = len;
3664 luaL_addlstring(&appctx->b, blk1, len1);
3665 len -= len1;
3666
3667 /* Copy the second block. */
3668 if (len2 > len)
3669 len2 = len;
3670 luaL_addlstring(&appctx->b, blk2, len2);
3671 len -= len2;
3672
3673 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003674 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003675
3676 /* If we are no other data avalaible, yield waiting for new data. */
3677 if (len > 0) {
3678 lua_pushinteger(L, len);
3679 lua_replace(L, 2);
3680 si_applet_cant_get(si);
3681 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3682 }
3683
3684 /* return the result. */
3685 luaL_pushresult(&appctx->b);
3686 return 1;
3687 }
3688
3689 /* we never executes this */
3690 hlua_pusherror(L, "Lua: internal error");
3691 WILL_LJMP(lua_error(L));
3692 return 0;
3693}
3694
3695/* Check arguments for the fucntion "hlua_channel_get_yield". */
3696__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3697{
3698 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3699 int len = -1;
3700
3701 if (lua_gettop(L) > 2)
3702 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3703 if (lua_gettop(L) >= 2) {
3704 len = MAY_LJMP(luaL_checkinteger(L, 2));
3705 lua_pop(L, 1);
3706 }
3707
3708 /* Confirm or set the required length */
3709 lua_pushinteger(L, len);
3710
3711 /* Initialise the string catenation. */
3712 luaL_buffinit(L, &appctx->b);
3713
3714 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3715}
3716
3717/* Append data in the output side of the buffer. This data is immediatly
3718 * sent. The fcuntion returns the ammount of data writed. If the buffer
3719 * cannot contains the data, the function yield. The function returns -1
3720 * if the channel is closed.
3721 */
3722__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3723{
3724 size_t len;
3725 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3726 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3727 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3728 struct stream_interface *si = appctx->appctx->owner;
3729 struct channel *chn = si_ic(si);
3730 int max;
3731
3732 /* Get the max amount of data which can write as input in the channel. */
3733 max = channel_recv_max(chn);
3734 if (max > (len - l))
3735 max = len - l;
3736
3737 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003738 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003739
3740 /* update counters. */
3741 l += max;
3742 lua_pop(L, 1);
3743 lua_pushinteger(L, l);
3744
3745 /* If some data is not send, declares the situation to the
3746 * applet, and returns a yield.
3747 */
3748 if (l < len) {
3749 si_applet_cant_put(si);
3750 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3751 }
3752
3753 return 1;
3754}
3755
3756/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3757 * yield the LUA process, and resume it without checking the
3758 * input arguments.
3759 */
3760__LJMP static int hlua_applet_tcp_send(lua_State *L)
3761{
3762 MAY_LJMP(check_args(L, 2, "send"));
3763 lua_pushinteger(L, 0);
3764
3765 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3766}
3767
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003768/*
3769 *
3770 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003771 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003772 *
3773 *
3774 */
3775
3776/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003777 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003778 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003779__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003780{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003781 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003782}
3783
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003784/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003785 * according with a current TXN.
3786 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003787static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003788{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003789 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003790 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003791 struct stream_interface *si = ctx->owner;
3792 struct stream *s = si_strm(si);
3793 struct proxy *px = s->be;
3794 struct http_txn *txn = s->txn;
3795 const char *path;
3796 const char *end;
3797 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003798
3799 /* Check stack size. */
3800 if (!lua_checkstack(L, 3))
3801 return 0;
3802
3803 /* Create the object: obj[0] = userdata.
3804 * Note that the base of the Converters object is the
3805 * same than the TXN object.
3806 */
3807 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003808 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003809 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003810 appctx->appctx = ctx;
3811 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003812 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003813 appctx->htxn.s = s;
3814 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003815
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003816 /* Create the "f" field that contains a list of fetches. */
3817 lua_pushstring(L, "f");
3818 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3819 return 0;
3820 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003821
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003822 /* Create the "sf" field that contains a list of stringsafe fetches. */
3823 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003824 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003825 return 0;
3826 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003827
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003828 /* Create the "c" field that contains a list of converters. */
3829 lua_pushstring(L, "c");
3830 if (!hlua_converters_new(L, &appctx->htxn, 0))
3831 return 0;
3832 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003833
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003834 /* Create the "sc" field that contains a list of stringsafe converters. */
3835 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003836 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003837 return 0;
3838 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003839
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003840 /* Stores the request method. */
3841 lua_pushstring(L, "method");
3842 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3843 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003844
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003845 /* Stores the http version. */
3846 lua_pushstring(L, "version");
3847 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3848 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003849
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003850 /* creates an array of headers. hlua_http_get_headers() crates and push
3851 * the array on the top of the stack.
3852 */
3853 lua_pushstring(L, "headers");
3854 htxn.s = s;
3855 htxn.p = px;
3856 htxn.dir = SMP_OPT_DIR_REQ;
3857 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3858 return 0;
3859 lua_settable(L, -3);
3860
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003861 /* Get path and qs */
3862 path = http_get_path(txn);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003863 if (path) {
3864 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3865 p = path;
3866 while (p < end && *p != '?')
3867 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003868
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003869 /* Stores the request path. */
3870 lua_pushstring(L, "path");
3871 lua_pushlstring(L, path, p - path);
3872 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003873
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003874 /* Stores the query string. */
3875 lua_pushstring(L, "qs");
3876 if (*p == '?')
3877 p++;
3878 lua_pushlstring(L, p, end - p);
3879 lua_settable(L, -3);
3880 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003881
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003882 /* Stores the request path. */
3883 lua_pushstring(L, "length");
3884 lua_pushinteger(L, txn->req.body_len);
3885 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003886
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003887 /* Create an array of HTTP request headers. */
3888 lua_pushstring(L, "headers");
3889 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3890 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003891
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003892 /* Create an empty array of HTTP request headers. */
3893 lua_pushstring(L, "response");
3894 lua_newtable(L);
3895 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003896
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003897 /* Pop a class stream metatable and affect it to the table. */
3898 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3899 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003900
3901 return 1;
3902}
3903
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003904__LJMP static int hlua_applet_http_set_var(lua_State *L)
3905{
3906 struct hlua_appctx *appctx;
3907 struct stream *s;
3908 const char *name;
3909 size_t len;
3910 struct sample smp;
3911
3912 MAY_LJMP(check_args(L, 3, "set_var"));
3913
3914 /* It is useles to retrieve the stream, but this function
3915 * runs only in a stream context.
3916 */
3917 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3918 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3919 s = appctx->htxn.s;
3920
3921 /* Converts the third argument in a sample. */
3922 hlua_lua2smp(L, 3, &smp);
3923
3924 /* Store the sample in a variable. */
3925 smp_set_owner(&smp, s->be, s->sess, s, 0);
3926 vars_set_by_name(name, len, &smp);
3927 return 0;
3928}
3929
3930__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3931{
3932 struct hlua_appctx *appctx;
3933 struct stream *s;
3934 const char *name;
3935 size_t len;
3936 struct sample smp;
3937
3938 MAY_LJMP(check_args(L, 2, "unset_var"));
3939
3940 /* It is useles to retrieve the stream, but this function
3941 * runs only in a stream context.
3942 */
3943 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3944 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3945 s = appctx->htxn.s;
3946
3947 /* Unset the variable. */
3948 smp_set_owner(&smp, s->be, s->sess, s, 0);
3949 vars_unset_by_name(name, len, &smp);
3950 return 0;
3951}
3952
3953__LJMP static int hlua_applet_http_get_var(lua_State *L)
3954{
3955 struct hlua_appctx *appctx;
3956 struct stream *s;
3957 const char *name;
3958 size_t len;
3959 struct sample smp;
3960
3961 MAY_LJMP(check_args(L, 2, "get_var"));
3962
3963 /* It is useles to retrieve the stream, but this function
3964 * runs only in a stream context.
3965 */
3966 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3967 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3968 s = appctx->htxn.s;
3969
3970 smp_set_owner(&smp, s->be, s->sess, s, 0);
3971 if (!vars_get_by_name(name, len, &smp)) {
3972 lua_pushnil(L);
3973 return 1;
3974 }
3975
3976 return hlua_smp2lua(L, &smp);
3977}
3978
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003979__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3980{
3981 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3982 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003983 struct hlua *hlua;
3984
3985 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003986 if (!s->hlua)
3987 return 0;
3988 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003989
3990 MAY_LJMP(check_args(L, 2, "set_priv"));
3991
3992 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003993 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003994
3995 /* Get and store new value. */
3996 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3997 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3998
3999 return 0;
4000}
4001
4002__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4003{
4004 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4005 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004006 struct hlua *hlua;
4007
4008 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004009 if (!s->hlua) {
4010 lua_pushnil(L);
4011 return 1;
4012 }
4013 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004014
4015 /* Push configuration index in the stack. */
4016 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4017
4018 return 1;
4019}
4020
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004021/* If expected data not yet available, it returns a yield. This function
4022 * consumes the data in the buffer. It returns a string containing the
4023 * data. This string can be empty.
4024 */
4025__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004026{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004027 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4028 struct stream_interface *si = appctx->appctx->owner;
4029 struct channel *chn = si_ic(si);
4030 int ret;
4031 char *blk1;
4032 int len1;
4033 char *blk2;
4034 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004035
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004036 /* Maybe we cant send a 100-continue ? */
4037 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau06d80a92017-10-19 14:32:15 +02004038 ret = ci_putblk(chn, HTTP_100C, strlen(HTTP_100C));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004039 /* if ret == -2 or -3 the channel closed or the message si too
4040 * big for the buffers. We cant send anything. So, we ignoring
4041 * the error, considers that the 100-continue is sent, and try
4042 * to receive.
4043 * If ret is -1, we dont have room in the buffer, so we yield.
4044 */
4045 if (ret == -1) {
4046 si_applet_cant_put(si);
4047 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4048 }
4049 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4050 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004051
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004052 /* Check for the end of the data. */
4053 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4054 luaL_pushresult(&appctx->b);
4055 return 1;
4056 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004057
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004058 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004059 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004060
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004061 /* Data not yet avalaible. return yield. */
4062 if (ret == 0) {
4063 si_applet_cant_get(si);
4064 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4065 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004066
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004067 /* End of data: commit the total strings and return. */
4068 if (ret < 0) {
4069 luaL_pushresult(&appctx->b);
4070 return 1;
4071 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004072
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004073 /* Ensure that the block 2 length is usable. */
4074 if (ret == 1)
4075 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004076
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004077 /* Copy the fisrt block caping to the length required. */
4078 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4079 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4080 luaL_addlstring(&appctx->b, blk1, len1);
4081 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004082
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004083 /* Copy the second block. */
4084 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4085 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4086 luaL_addlstring(&appctx->b, blk2, len2);
4087 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004088
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004089 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004090 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004091 luaL_pushresult(&appctx->b);
4092 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004093}
4094
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004095/* Check arguments for the fucntion "hlua_channel_get_yield". */
4096__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004097{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004098 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004099
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004100 /* Initialise the string catenation. */
4101 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004102
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004103 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004104}
4105
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004106/* If expected data not yet available, it returns a yield. This function
4107 * consumes the data in the buffer. It returns a string containing the
4108 * data. This string can be empty.
4109 */
4110__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004111{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004112 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4113 struct stream_interface *si = appctx->appctx->owner;
4114 int len = MAY_LJMP(luaL_checkinteger(L, 2));
4115 struct channel *chn = si_ic(si);
4116 int ret;
4117 char *blk1;
4118 int len1;
4119 char *blk2;
4120 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004121
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004122 /* Maybe we cant send a 100-continue ? */
4123 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau06d80a92017-10-19 14:32:15 +02004124 ret = ci_putblk(chn, HTTP_100C, strlen(HTTP_100C));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004125 /* if ret == -2 or -3 the channel closed or the message si too
4126 * big for the buffers. We cant send anything. So, we ignoring
4127 * the error, considers that the 100-continue is sent, and try
4128 * to receive.
4129 * If ret is -1, we dont have room in the buffer, so we yield.
4130 */
4131 if (ret == -1) {
4132 si_applet_cant_put(si);
4133 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4134 }
4135 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4136 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004137
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004138 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004139 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004140
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004141 /* Data not yet avalaible. return yield. */
4142 if (ret == 0) {
4143 si_applet_cant_get(si);
4144 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4145 }
4146
4147 /* End of data: commit the total strings and return. */
4148 if (ret < 0) {
4149 luaL_pushresult(&appctx->b);
4150 return 1;
4151 }
4152
4153 /* Ensure that the block 2 length is usable. */
4154 if (ret == 1)
4155 len2 = 0;
4156
4157 /* Copy the fisrt block caping to the length required. */
4158 if (len1 > len)
4159 len1 = len;
4160 luaL_addlstring(&appctx->b, blk1, len1);
4161 len -= len1;
4162
4163 /* Copy the second block. */
4164 if (len2 > len)
4165 len2 = len;
4166 luaL_addlstring(&appctx->b, blk2, len2);
4167 len -= len2;
4168
4169 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004170 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004171 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4172 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4173
4174 /* If we are no other data avalaible, yield waiting for new data. */
4175 if (len > 0) {
4176 lua_pushinteger(L, len);
4177 lua_replace(L, 2);
4178 si_applet_cant_get(si);
4179 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4180 }
4181
4182 /* return the result. */
4183 luaL_pushresult(&appctx->b);
4184 return 1;
4185}
4186
4187/* Check arguments for the fucntion "hlua_channel_get_yield". */
4188__LJMP static int hlua_applet_http_recv(lua_State *L)
4189{
4190 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4191 int len = -1;
4192
4193 /* Check arguments. */
4194 if (lua_gettop(L) > 2)
4195 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4196 if (lua_gettop(L) >= 2) {
4197 len = MAY_LJMP(luaL_checkinteger(L, 2));
4198 lua_pop(L, 1);
4199 }
4200
4201 /* Check the required length */
4202 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4203 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4204 lua_pushinteger(L, len);
4205
4206 /* Initialise the string catenation. */
4207 luaL_buffinit(L, &appctx->b);
4208
4209 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4210}
4211
4212/* Append data in the output side of the buffer. This data is immediatly
4213 * sent. The fcuntion returns the ammount of data writed. If the buffer
4214 * cannot contains the data, the function yield. The function returns -1
4215 * if the channel is closed.
4216 */
4217__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4218{
4219 size_t len;
4220 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4221 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4222 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4223 struct stream_interface *si = appctx->appctx->owner;
4224 struct channel *chn = si_ic(si);
4225 int max;
4226
4227 /* Get the max amount of data which can write as input in the channel. */
4228 max = channel_recv_max(chn);
4229 if (max > (len - l))
4230 max = len - l;
4231
4232 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004233 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004234
4235 /* update counters. */
4236 l += max;
4237 lua_pop(L, 1);
4238 lua_pushinteger(L, l);
4239
4240 /* If some data is not send, declares the situation to the
4241 * applet, and returns a yield.
4242 */
4243 if (l < len) {
4244 si_applet_cant_put(si);
4245 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
4246 }
4247
4248 return 1;
4249}
4250
4251/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4252 * yield the LUA process, and resume it without checking the
4253 * input arguments.
4254 */
4255__LJMP static int hlua_applet_http_send(lua_State *L)
4256{
4257 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4258 size_t len;
4259 char hex[10];
4260
4261 MAY_LJMP(luaL_checklstring(L, 2, &len));
4262
4263 /* If transfer encoding chunked is selected, we surround the data
4264 * by chunk data.
4265 */
4266 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4267 snprintf(hex, 9, "%x", (unsigned int)len);
4268 lua_pushfstring(L, "%s\r\n", hex);
4269 lua_insert(L, 2); /* swap the last 2 entries. */
4270 lua_pushstring(L, "\r\n");
4271 lua_concat(L, 3);
4272 }
4273
4274 /* This interger is used for followinf the amount of data sent. */
4275 lua_pushinteger(L, 0);
4276
4277 /* We want to send some data. Headers must be sent. */
4278 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4279 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4280 WILL_LJMP(lua_error(L));
4281 }
4282
4283 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4284}
4285
4286__LJMP static int hlua_applet_http_addheader(lua_State *L)
4287{
4288 const char *name;
4289 int ret;
4290
4291 MAY_LJMP(hlua_checkapplet_http(L, 1));
4292 name = MAY_LJMP(luaL_checkstring(L, 2));
4293 MAY_LJMP(luaL_checkstring(L, 3));
4294
4295 /* Push in the stack the "response" entry. */
4296 ret = lua_getfield(L, 1, "response");
4297 if (ret != LUA_TTABLE) {
4298 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4299 "is expected as an array. %s found", lua_typename(L, ret));
4300 WILL_LJMP(lua_error(L));
4301 }
4302
4303 /* check if the header is already registered if it is not
4304 * the case, register it.
4305 */
4306 ret = lua_getfield(L, -1, name);
4307 if (ret == LUA_TNIL) {
4308
4309 /* Entry not found. */
4310 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4311
4312 /* Insert the new header name in the array in the top of the stack.
4313 * It left the new array in the top of the stack.
4314 */
4315 lua_newtable(L);
4316 lua_pushvalue(L, 2);
4317 lua_pushvalue(L, -2);
4318 lua_settable(L, -4);
4319
4320 } else if (ret != LUA_TTABLE) {
4321
4322 /* corruption error. */
4323 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4324 "is expected as an array. %s found", name, lua_typename(L, ret));
4325 WILL_LJMP(lua_error(L));
4326 }
4327
4328 /* Now the top od thestack is an array of values. We push
4329 * the header value as new entry.
4330 */
4331 lua_pushvalue(L, 3);
4332 ret = lua_rawlen(L, -2);
4333 lua_rawseti(L, -2, ret + 1);
4334 lua_pushboolean(L, 1);
4335 return 1;
4336}
4337
4338__LJMP static int hlua_applet_http_status(lua_State *L)
4339{
4340 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4341 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004342 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004343
4344 if (status < 100 || status > 599) {
4345 lua_pushboolean(L, 0);
4346 return 1;
4347 }
4348
4349 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004350 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004351 lua_pushboolean(L, 1);
4352 return 1;
4353}
4354
4355/* We will build the status line and the headers of the HTTP response.
4356 * We will try send at once if its not possible, we give back the hand
4357 * waiting for more room.
4358 */
4359__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4360{
4361 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4362 struct stream_interface *si = appctx->appctx->owner;
4363 struct channel *chn = si_ic(si);
4364 int ret;
4365 size_t len;
4366 const char *msg;
4367
4368 /* Get the message as the first argument on the stack. */
4369 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4370
4371 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004372 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004373
4374 /* if ret == -2 or -3 the channel closed or the message si too
4375 * big for the buffers.
4376 */
4377 if (ret == -2 || ret == -3) {
4378 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4379 WILL_LJMP(lua_error(L));
4380 }
4381
4382 /* If ret is -1, we dont have room in the buffer, so we yield. */
4383 if (ret == -1) {
4384 si_applet_cant_put(si);
4385 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4386 }
4387
4388 /* Headers sent, set the flag. */
4389 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4390 return 0;
4391}
4392
4393__LJMP static int hlua_applet_http_start_response(lua_State *L)
4394{
4395 struct chunk *tmp = get_trash_chunk();
4396 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004397 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02004398 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004399 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02004400 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004401 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004402 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004403 int hdr_chunked = 0;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004404 const char *reason = appctx->appctx->ctx.hlua_apphttp.reason;
4405
4406 if (reason == NULL)
4407 reason = get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004408
4409 /* Use the same http version than the request. */
4410 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004411 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004412 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004413 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004414
4415 /* Get the array associated to the field "response" in the object AppletHTTP. */
4416 lua_pushvalue(L, 0);
4417 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4418 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4419 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4420 WILL_LJMP(lua_error(L));
4421 }
4422
4423 /* Browse the list of headers. */
4424 lua_pushnil(L);
4425 while(lua_next(L, -2) != 0) {
4426
4427 /* We expect a string as -2. */
4428 if (lua_type(L, -2) != LUA_TSTRING) {
4429 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4430 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4431 lua_typename(L, lua_type(L, -2)));
4432 WILL_LJMP(lua_error(L));
4433 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004434 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004435
4436 /* We expect an array as -1. */
4437 if (lua_type(L, -1) != LUA_TTABLE) {
4438 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4439 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4440 name,
4441 lua_typename(L, lua_type(L, -1)));
4442 WILL_LJMP(lua_error(L));
4443 }
4444
4445 /* Browse the table who is on the top of the stack. */
4446 lua_pushnil(L);
4447 while(lua_next(L, -2) != 0) {
4448
4449 /* We expect a number as -2. */
4450 if (lua_type(L, -2) != LUA_TNUMBER) {
4451 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4452 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4453 name,
4454 lua_typename(L, lua_type(L, -2)));
4455 WILL_LJMP(lua_error(L));
4456 }
4457 id = lua_tointeger(L, -2);
4458
4459 /* We expect a string as -2. */
4460 if (lua_type(L, -1) != LUA_TSTRING) {
4461 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4462 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4463 name, id,
4464 lua_typename(L, lua_type(L, -1)));
4465 WILL_LJMP(lua_error(L));
4466 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004467 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004468
4469 /* Catenate a new header. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004470 if (tmp->len + name_len + 2 + value_len + 2 < tmp->size) {
4471 memcpy(tmp->str + tmp->len, name, name_len);
4472 tmp->len += name_len;
4473 tmp->str[tmp->len++] = ':';
4474 tmp->str[tmp->len++] = ' ';
4475
4476 memcpy(tmp->str + tmp->len, value, value_len);
4477 tmp->len += value_len;
4478 tmp->str[tmp->len++] = '\r';
4479 tmp->str[tmp->len++] = '\n';
4480 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004481
4482 /* Protocol checks. */
4483
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004484 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004485 * is done without control. If it contains a bad value,
4486 * the content-length remains negative so that we can
4487 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004488 */
Willy Tarreaua3294632017-08-23 11:24:47 +02004489 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004490 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004491
4492 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004493 if (name_len == 17 && value_len == 7 &&
4494 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004495 strcasecmp("chunked", value) == 0)
4496 hdr_chunked = 1;
4497
4498 /* Remove the array from the stack, and get next element with a remaining string. */
4499 lua_pop(L, 1);
4500 }
4501
4502 /* Remove the array from the stack, and get next element with a remaining string. */
4503 lua_pop(L, 1);
4504 }
4505
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004506 /* If we dont have a content-length set, and the HTTP version is 1.1
4507 * and the status code implies the presence of a message body, we must
4508 * announce a transfer encoding chunked. This is required by haproxy
4509 * for the keepalive compliance. If the applet annouces a transfer-encoding
4510 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004511 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004512 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004513 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
4514 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4515 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4516 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004517 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4518 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4519 }
4520
4521 /* Finalize headers. */
4522 chunk_appendf(tmp, "\r\n");
4523
4524 /* Remove the last entry and the array of headers */
4525 lua_pop(L, 2);
4526
4527 /* Push the headers block. */
4528 lua_pushlstring(L, tmp->str, tmp->len);
4529
4530 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4531}
4532
4533/*
4534 *
4535 *
4536 * Class HTTP
4537 *
4538 *
4539 */
4540
4541/* Returns a struct hlua_txn if the stack entry "ud" is
4542 * a class stream, otherwise it throws an error.
4543 */
4544__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4545{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004546 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004547}
4548
4549/* This function creates and push in the stack a HTTP object
4550 * according with a current TXN.
4551 */
4552static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4553{
4554 struct hlua_txn *htxn;
4555
4556 /* Check stack size. */
4557 if (!lua_checkstack(L, 3))
4558 return 0;
4559
4560 /* Create the object: obj[0] = userdata.
4561 * Note that the base of the Converters object is the
4562 * same than the TXN object.
4563 */
4564 lua_newtable(L);
4565 htxn = lua_newuserdata(L, sizeof(*htxn));
4566 lua_rawseti(L, -2, 0);
4567
4568 htxn->s = txn->s;
4569 htxn->p = txn->p;
4570
4571 /* Pop a class stream metatable and affect it to the table. */
4572 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4573 lua_setmetatable(L, -2);
4574
4575 return 1;
4576}
4577
4578/* This function creates ans returns an array of HTTP headers.
4579 * This function does not fails. It is used as wrapper with the
4580 * 2 following functions.
4581 */
4582__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4583{
4584 const char *cur_ptr, *cur_next, *p;
4585 int old_idx, cur_idx;
4586 struct hdr_idx_elem *cur_hdr;
4587 const char *hn, *hv;
4588 int hnl, hvl;
4589 int type;
4590 const char *in;
4591 char *out;
4592 int len;
4593
4594 /* Create the table. */
4595 lua_newtable(L);
4596
4597 if (!htxn->s->txn)
4598 return 1;
4599
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004600 /* Check if a valid response is parsed */
4601 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4602 return 1;
4603
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004604 /* Build array of headers. */
4605 old_idx = 0;
4606 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4607
4608 while (1) {
4609 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4610 if (!cur_idx)
4611 break;
4612 old_idx = cur_idx;
4613
4614 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4615 cur_ptr = cur_next;
4616 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4617
4618 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4619 * and the next header starts at cur_next. We'll check
4620 * this header in the list as well as against the default
4621 * rule.
4622 */
4623
4624 /* look for ': *'. */
4625 hn = cur_ptr;
4626 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4627 if (p >= cur_ptr+cur_hdr->len)
4628 continue;
4629 hnl = p - hn;
4630 p++;
4631 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4632 p++;
4633 if (p >= cur_ptr+cur_hdr->len)
4634 continue;
4635 hv = p;
4636 hvl = cur_ptr+cur_hdr->len-p;
4637
4638 /* Lowercase the key. Don't check the size of trash, it have
4639 * the size of one buffer and the input data contains in one
4640 * buffer.
4641 */
4642 out = trash.str;
4643 for (in=hn; in<hn+hnl; in++, out++)
4644 *out = tolower(*in);
4645 *out = '\0';
4646
4647 /* Check for existing entry:
4648 * assume that the table is on the top of the stack, and
4649 * push the key in the stack, the function lua_gettable()
4650 * perform the lookup.
4651 */
4652 lua_pushlstring(L, trash.str, hnl);
4653 lua_gettable(L, -2);
4654 type = lua_type(L, -1);
4655
4656 switch (type) {
4657 case LUA_TNIL:
4658 /* Table not found, create it. */
4659 lua_pop(L, 1); /* remove the nil value. */
4660 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4661 lua_newtable(L); /* create and push empty table. */
4662 lua_pushlstring(L, hv, hvl); /* push header value. */
4663 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4664 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4665 break;
4666
4667 case LUA_TTABLE:
4668 /* Entry found: push the value in the table. */
4669 len = lua_rawlen(L, -1);
4670 lua_pushlstring(L, hv, hvl); /* push header value. */
4671 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4672 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4673 break;
4674
4675 default:
4676 /* Other cases are errors. */
4677 hlua_pusherror(L, "internal error during the parsing of headers.");
4678 WILL_LJMP(lua_error(L));
4679 }
4680 }
4681
4682 return 1;
4683}
4684
4685__LJMP static int hlua_http_req_get_headers(lua_State *L)
4686{
4687 struct hlua_txn *htxn;
4688
4689 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4690 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4691
4692 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4693}
4694
4695__LJMP static int hlua_http_res_get_headers(lua_State *L)
4696{
4697 struct hlua_txn *htxn;
4698
4699 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4700 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4701
4702 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4703}
4704
4705/* This function replace full header, or just a value in
4706 * the request or in the response. It is a wrapper fir the
4707 * 4 following functions.
4708 */
4709__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4710 struct http_msg *msg, int action)
4711{
4712 size_t name_len;
4713 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4714 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4715 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4716 struct my_regex re;
4717
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004718 /* Check if a valid response is parsed */
4719 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4720 return 0;
4721
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004722 if (!regex_comp(reg, &re, 1, 1, NULL))
4723 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4724
4725 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4726 regex_free(&re);
4727 return 0;
4728}
4729
4730__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4731{
4732 struct hlua_txn *htxn;
4733
4734 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4735 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4736
4737 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4738}
4739
4740__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4741{
4742 struct hlua_txn *htxn;
4743
4744 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4745 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4746
4747 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4748}
4749
4750__LJMP static int hlua_http_req_rep_val(lua_State *L)
4751{
4752 struct hlua_txn *htxn;
4753
4754 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4755 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4756
4757 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4758}
4759
4760__LJMP static int hlua_http_res_rep_val(lua_State *L)
4761{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004762 struct hlua_txn *htxn;
4763
4764 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4765 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4766
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004767 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004768}
4769
4770/* This function deletes all the occurences of an header.
4771 * It is a wrapper for the 2 following functions.
4772 */
4773__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4774{
4775 size_t len;
4776 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4777 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004778 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004779
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004780 /* Check if a valid response is parsed */
4781 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4782 return 0;
4783
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004784 ctx.idx = 0;
4785 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4786 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4787 return 0;
4788}
4789
4790__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4791{
4792 struct hlua_txn *htxn;
4793
4794 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4795 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4796
Willy Tarreaueee5b512015-04-03 23:46:31 +02004797 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004798}
4799
4800__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4801{
4802 struct hlua_txn *htxn;
4803
4804 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4805 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4806
Willy Tarreaueee5b512015-04-03 23:46:31 +02004807 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004808}
4809
4810/* This function adds an header. It is a wrapper used by
4811 * the 2 following functions.
4812 */
4813__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4814{
4815 size_t name_len;
4816 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4817 size_t value_len;
4818 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4819 char *p;
4820
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004821 /* Check if a valid message is parsed */
4822 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4823 return 0;
4824
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004825 /* Check length. */
4826 trash.len = value_len + name_len + 2;
4827 if (trash.len > trash.size)
4828 return 0;
4829
4830 /* Creates the header string. */
4831 p = trash.str;
4832 memcpy(p, name, name_len);
4833 p += name_len;
4834 *p = ':';
4835 p++;
4836 *p = ' ';
4837 p++;
4838 memcpy(p, value, value_len);
4839
Willy Tarreaueee5b512015-04-03 23:46:31 +02004840 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004841 trash.str, trash.len) != 0);
4842
4843 return 0;
4844}
4845
4846__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4847{
4848 struct hlua_txn *htxn;
4849
4850 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4851 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4852
Willy Tarreaueee5b512015-04-03 23:46:31 +02004853 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004854}
4855
4856__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4857{
4858 struct hlua_txn *htxn;
4859
4860 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4861 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4862
Willy Tarreaueee5b512015-04-03 23:46:31 +02004863 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004864}
4865
4866static int hlua_http_req_set_hdr(lua_State *L)
4867{
4868 struct hlua_txn *htxn;
4869
4870 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4871 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4872
Willy Tarreaueee5b512015-04-03 23:46:31 +02004873 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4874 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004875}
4876
4877static int hlua_http_res_set_hdr(lua_State *L)
4878{
4879 struct hlua_txn *htxn;
4880
4881 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4882 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4883
Willy Tarreaueee5b512015-04-03 23:46:31 +02004884 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4885 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004886}
4887
4888/* This function set the method. */
4889static int hlua_http_req_set_meth(lua_State *L)
4890{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004891 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004892 size_t name_len;
4893 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004894
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004895 /* Check if a valid request is parsed */
4896 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4897 lua_pushboolean(L, 0);
4898 return 1;
4899 }
4900
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004901 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004902 return 1;
4903}
4904
4905/* This function set the method. */
4906static int hlua_http_req_set_path(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 FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004911
4912 /* 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(1, 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 query-string. */
4923static int hlua_http_req_set_query(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 FOURNIER08504f42015-03-16 14:17:08 +01004928
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004929 /* 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
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004935 /* Check length. */
4936 if (name_len > trash.size - 1) {
4937 lua_pushboolean(L, 0);
4938 return 1;
4939 }
4940
4941 /* Add the mark question as prefix. */
4942 chunk_reset(&trash);
4943 trash.str[trash.len++] = '?';
4944 memcpy(trash.str + trash.len, name, name_len);
4945 trash.len += name_len;
4946
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004947 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004948 return 1;
4949}
4950
4951/* This function set the uri. */
4952static int hlua_http_req_set_uri(lua_State *L)
4953{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004954 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004955 size_t name_len;
4956 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004957
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004958 /* Check if a valid request is parsed */
4959 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4960 lua_pushboolean(L, 0);
4961 return 1;
4962 }
4963
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004964 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004965 return 1;
4966}
4967
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004968/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004969static int hlua_http_res_set_status(lua_State *L)
4970{
4971 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4972 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004973 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004974
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004975 /* Check if a valid response is parsed */
4976 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4977 return 0;
4978
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004979 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004980 return 0;
4981}
4982
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004983/*
4984 *
4985 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004986 * Class TXN
4987 *
4988 *
4989 */
4990
4991/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004992 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004993 */
4994__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4995{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004996 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004997}
4998
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004999__LJMP static int hlua_set_var(lua_State *L)
5000{
5001 struct hlua_txn *htxn;
5002 const char *name;
5003 size_t len;
5004 struct sample smp;
5005
5006 MAY_LJMP(check_args(L, 3, "set_var"));
5007
5008 /* It is useles to retrieve the stream, but this function
5009 * runs only in a stream context.
5010 */
5011 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5012 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5013
5014 /* Converts the third argument in a sample. */
5015 hlua_lua2smp(L, 3, &smp);
5016
5017 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005018 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005019 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005020 return 0;
5021}
5022
Christopher Faulet85d79c92016-11-09 16:54:56 +01005023__LJMP static int hlua_unset_var(lua_State *L)
5024{
5025 struct hlua_txn *htxn;
5026 const char *name;
5027 size_t len;
5028 struct sample smp;
5029
5030 MAY_LJMP(check_args(L, 2, "unset_var"));
5031
5032 /* It is useles to retrieve the stream, but this function
5033 * runs only in a stream context.
5034 */
5035 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5036 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5037
5038 /* Unset the variable. */
5039 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5040 vars_unset_by_name(name, len, &smp);
5041 return 0;
5042}
5043
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005044__LJMP static int hlua_get_var(lua_State *L)
5045{
5046 struct hlua_txn *htxn;
5047 const char *name;
5048 size_t len;
5049 struct sample smp;
5050
5051 MAY_LJMP(check_args(L, 2, "get_var"));
5052
5053 /* It is useles to retrieve the stream, but this function
5054 * runs only in a stream context.
5055 */
5056 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5057 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5058
Willy Tarreau7560dd42016-03-10 16:28:58 +01005059 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005060 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005061 lua_pushnil(L);
5062 return 1;
5063 }
5064
5065 return hlua_smp2lua(L, &smp);
5066}
5067
Willy Tarreau59551662015-03-10 14:23:13 +01005068__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005069{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005070 struct hlua *hlua;
5071
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005072 MAY_LJMP(check_args(L, 2, "set_priv"));
5073
Willy Tarreau87b09662015-04-03 00:22:06 +02005074 /* It is useles to retrieve the stream, but this function
5075 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005076 */
5077 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005078 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005079
5080 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005081 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005082
5083 /* Get and store new value. */
5084 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5085 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5086
5087 return 0;
5088}
5089
Willy Tarreau59551662015-03-10 14:23:13 +01005090__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005091{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005092 struct hlua *hlua;
5093
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005094 MAY_LJMP(check_args(L, 1, "get_priv"));
5095
Willy Tarreau87b09662015-04-03 00:22:06 +02005096 /* It is useles to retrieve the stream, but this function
5097 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005098 */
5099 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005100 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005101
5102 /* Push configuration index in the stack. */
5103 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5104
5105 return 1;
5106}
5107
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005108/* Create stack entry containing a class TXN. This function
5109 * return 0 if the stack does not contains free slots,
5110 * otherwise it returns 1.
5111 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005112static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005113{
Willy Tarreaude491382015-04-06 11:04:28 +02005114 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005115
5116 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005117 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005118 return 0;
5119
5120 /* NOTE: The allocation never fails. The failure
5121 * throw an error, and the function never returns.
5122 * if the throw is not avalaible, the process is aborted.
5123 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005124 /* Create the object: obj[0] = userdata. */
5125 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005126 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005127 lua_rawseti(L, -2, 0);
5128
Willy Tarreaude491382015-04-06 11:04:28 +02005129 htxn->s = s;
5130 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005131 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005132 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005133
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005134 /* Create the "f" field that contains a list of fetches. */
5135 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005136 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005137 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005138 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005139
5140 /* Create the "sf" field that contains a list of stringsafe fetches. */
5141 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005142 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005143 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005144 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005145
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005146 /* Create the "c" field that contains a list of converters. */
5147 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005148 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005149 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005150 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005151
5152 /* Create the "sc" field that contains a list of stringsafe converters. */
5153 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005154 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005155 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005156 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005157
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005158 /* Create the "req" field that contains the request channel object. */
5159 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005160 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005161 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005162 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005163
5164 /* Create the "res" field that contains the response channel object. */
5165 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005166 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005167 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005168 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005169
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005170 /* Creates the HTTP object is the current proxy allows http. */
5171 lua_pushstring(L, "http");
5172 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005173 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005174 return 0;
5175 }
5176 else
5177 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005178 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005179
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005180 /* Pop a class sesison metatable and affect it to the userdata. */
5181 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5182 lua_setmetatable(L, -2);
5183
5184 return 1;
5185}
5186
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005187__LJMP static int hlua_txn_deflog(lua_State *L)
5188{
5189 const char *msg;
5190 struct hlua_txn *htxn;
5191
5192 MAY_LJMP(check_args(L, 2, "deflog"));
5193 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5194 msg = MAY_LJMP(luaL_checkstring(L, 2));
5195
5196 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5197 return 0;
5198}
5199
5200__LJMP static int hlua_txn_log(lua_State *L)
5201{
5202 int level;
5203 const char *msg;
5204 struct hlua_txn *htxn;
5205
5206 MAY_LJMP(check_args(L, 3, "log"));
5207 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5208 level = MAY_LJMP(luaL_checkinteger(L, 2));
5209 msg = MAY_LJMP(luaL_checkstring(L, 3));
5210
5211 if (level < 0 || level >= NB_LOG_LEVELS)
5212 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5213
5214 hlua_sendlog(htxn->s->be, level, msg);
5215 return 0;
5216}
5217
5218__LJMP static int hlua_txn_log_debug(lua_State *L)
5219{
5220 const char *msg;
5221 struct hlua_txn *htxn;
5222
5223 MAY_LJMP(check_args(L, 2, "Debug"));
5224 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5225 msg = MAY_LJMP(luaL_checkstring(L, 2));
5226 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5227 return 0;
5228}
5229
5230__LJMP static int hlua_txn_log_info(lua_State *L)
5231{
5232 const char *msg;
5233 struct hlua_txn *htxn;
5234
5235 MAY_LJMP(check_args(L, 2, "Info"));
5236 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5237 msg = MAY_LJMP(luaL_checkstring(L, 2));
5238 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5239 return 0;
5240}
5241
5242__LJMP static int hlua_txn_log_warning(lua_State *L)
5243{
5244 const char *msg;
5245 struct hlua_txn *htxn;
5246
5247 MAY_LJMP(check_args(L, 2, "Warning"));
5248 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5249 msg = MAY_LJMP(luaL_checkstring(L, 2));
5250 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5251 return 0;
5252}
5253
5254__LJMP static int hlua_txn_log_alert(lua_State *L)
5255{
5256 const char *msg;
5257 struct hlua_txn *htxn;
5258
5259 MAY_LJMP(check_args(L, 2, "Alert"));
5260 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5261 msg = MAY_LJMP(luaL_checkstring(L, 2));
5262 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5263 return 0;
5264}
5265
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005266__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5267{
5268 struct hlua_txn *htxn;
5269 int ll;
5270
5271 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5272 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5273 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5274
5275 if (ll < 0 || ll > 7)
5276 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5277
5278 htxn->s->logs.level = ll;
5279 return 0;
5280}
5281
5282__LJMP static int hlua_txn_set_tos(lua_State *L)
5283{
5284 struct hlua_txn *htxn;
5285 struct connection *cli_conn;
5286 int tos;
5287
5288 MAY_LJMP(check_args(L, 2, "set_tos"));
5289 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5290 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5291
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005292 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005293 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005294
5295 return 0;
5296}
5297
5298__LJMP static int hlua_txn_set_mark(lua_State *L)
5299{
5300#ifdef SO_MARK
5301 struct hlua_txn *htxn;
5302 struct connection *cli_conn;
5303 int mark;
5304
5305 MAY_LJMP(check_args(L, 2, "set_mark"));
5306 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5307 mark = 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 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005311#endif
5312 return 0;
5313}
5314
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005315/* This function is an Lua binding that send pending data
5316 * to the client, and close the stream interface.
5317 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005318__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005319{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005320 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005321 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005322 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005323
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005324 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005325 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005326 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005327
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005328 /* If the flags NOTERM is set, we cannot terminate the http
5329 * session, so we just end the execution of the current
5330 * lua code.
5331 */
5332 if (htxn->flags & HLUA_TXN_NOTERM) {
5333 WILL_LJMP(hlua_done(L));
5334 return 0;
5335 }
5336
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005337 ic = &htxn->s->req;
5338 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005339
Willy Tarreau630ef452015-08-28 10:06:15 +02005340 if (htxn->s->txn) {
5341 /* HTTP mode, let's stay in sync with the stream */
5342 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
5343 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5344 htxn->s->txn->req.sov = 0;
5345 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5346 oc->analysers = AN_RES_HTTP_XFER_BODY;
5347 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5348 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5349
Willy Tarreau630ef452015-08-28 10:06:15 +02005350 /* Note that if we want to support keep-alive, we need
5351 * to bypass the close/shutr_now calls below, but that
5352 * may only be done if the HTTP request was already
5353 * processed and the connection header is known (ie
5354 * not during TCP rules).
5355 */
5356 }
5357
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005358 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005359 channel_abort(ic);
5360 channel_auto_close(ic);
5361 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005362
5363 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005364 channel_auto_read(oc);
5365 channel_auto_close(oc);
5366 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005367
Willy Tarreau0458b082015-08-28 09:40:04 +02005368 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005369
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005370 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005371 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005372 return 0;
5373}
5374
5375__LJMP static int hlua_log(lua_State *L)
5376{
5377 int level;
5378 const char *msg;
5379
5380 MAY_LJMP(check_args(L, 2, "log"));
5381 level = MAY_LJMP(luaL_checkinteger(L, 1));
5382 msg = MAY_LJMP(luaL_checkstring(L, 2));
5383
5384 if (level < 0 || level >= NB_LOG_LEVELS)
5385 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5386
5387 hlua_sendlog(NULL, level, msg);
5388 return 0;
5389}
5390
5391__LJMP static int hlua_log_debug(lua_State *L)
5392{
5393 const char *msg;
5394
5395 MAY_LJMP(check_args(L, 1, "debug"));
5396 msg = MAY_LJMP(luaL_checkstring(L, 1));
5397 hlua_sendlog(NULL, LOG_DEBUG, msg);
5398 return 0;
5399}
5400
5401__LJMP static int hlua_log_info(lua_State *L)
5402{
5403 const char *msg;
5404
5405 MAY_LJMP(check_args(L, 1, "info"));
5406 msg = MAY_LJMP(luaL_checkstring(L, 1));
5407 hlua_sendlog(NULL, LOG_INFO, msg);
5408 return 0;
5409}
5410
5411__LJMP static int hlua_log_warning(lua_State *L)
5412{
5413 const char *msg;
5414
5415 MAY_LJMP(check_args(L, 1, "warning"));
5416 msg = MAY_LJMP(luaL_checkstring(L, 1));
5417 hlua_sendlog(NULL, LOG_WARNING, msg);
5418 return 0;
5419}
5420
5421__LJMP static int hlua_log_alert(lua_State *L)
5422{
5423 const char *msg;
5424
5425 MAY_LJMP(check_args(L, 1, "alert"));
5426 msg = MAY_LJMP(luaL_checkstring(L, 1));
5427 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005428 return 0;
5429}
5430
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005431__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005432{
5433 int wakeup_ms = lua_tointeger(L, -1);
5434 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005435 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005436 return 0;
5437}
5438
5439__LJMP static int hlua_sleep(lua_State *L)
5440{
5441 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005442 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005443
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005444 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005445
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005446 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005447 wakeup_ms = tick_add(now_ms, delay);
5448 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005449
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005450 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5451 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005452}
5453
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005454__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005455{
5456 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005457 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005458
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005459 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005460
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005461 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005462 wakeup_ms = tick_add(now_ms, delay);
5463 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005464
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005465 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5466 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005467}
5468
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005469/* This functionis an LUA binding. it permits to give back
5470 * the hand at the HAProxy scheduler. It is used when the
5471 * LUA processing consumes a lot of time.
5472 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005473__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005474{
5475 return 0;
5476}
5477
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005478__LJMP static int hlua_yield(lua_State *L)
5479{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005480 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5481 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005482}
5483
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005484/* This function change the nice of the currently executed
5485 * task. It is used set low or high priority at the current
5486 * task.
5487 */
Willy Tarreau59551662015-03-10 14:23:13 +01005488__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005489{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005490 struct hlua *hlua;
5491 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005492
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005493 MAY_LJMP(check_args(L, 1, "set_nice"));
5494 hlua = hlua_gethlua(L);
5495 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005496
5497 /* If he task is not set, I'm in a start mode. */
5498 if (!hlua || !hlua->task)
5499 return 0;
5500
5501 if (nice < -1024)
5502 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005503 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005504 nice = 1024;
5505
5506 hlua->task->nice = nice;
5507 return 0;
5508}
5509
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005510/* This function is used as a calback of a task. It is called by the
5511 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5512 * return an E_AGAIN signal, the emmiter of this signal must set a
5513 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005514 *
5515 * Task wrapper are longjmp safe because the only one Lua code
5516 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005517 */
5518static struct task *hlua_process_task(struct task *task)
5519{
5520 struct hlua *hlua = task->context;
5521 enum hlua_exec status;
5522
Christopher Faulet5bc99722018-04-25 10:34:45 +02005523 if (task->thread_mask == MAX_THREADS_MASK)
5524 task_set_affinity(task, tid_bit);
5525
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005526 /* If it is the first call to the task, we must initialize the
5527 * execution timeouts.
5528 */
5529 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005530 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005531
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005532 /* Execute the Lua code. */
5533 status = hlua_ctx_resume(hlua, 1);
5534
5535 switch (status) {
5536 /* finished or yield */
5537 case HLUA_E_OK:
5538 hlua_ctx_destroy(hlua);
5539 task_delete(task);
5540 task_free(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02005541 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005542 break;
5543
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005544 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01005545 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02005546 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005547 break;
5548
5549 /* finished with error. */
5550 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005551 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005552 hlua_ctx_destroy(hlua);
5553 task_delete(task);
5554 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005555 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005556 break;
5557
5558 case HLUA_E_ERR:
5559 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005560 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005561 hlua_ctx_destroy(hlua);
5562 task_delete(task);
5563 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005564 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005565 break;
5566 }
Emeric Brun253e53e2017-10-17 18:58:40 +02005567 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005568}
5569
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005570/* This function is an LUA binding that register LUA function to be
5571 * executed after the HAProxy configuration parsing and before the
5572 * HAProxy scheduler starts. This function expect only one LUA
5573 * argument that is a function. This function returns nothing, but
5574 * throws if an error is encountered.
5575 */
5576__LJMP static int hlua_register_init(lua_State *L)
5577{
5578 struct hlua_init_function *init;
5579 int ref;
5580
5581 MAY_LJMP(check_args(L, 1, "register_init"));
5582
5583 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5584
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005585 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005586 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005587 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005588
5589 init->function_ref = ref;
5590 LIST_ADDQ(&hlua_init_functions, &init->l);
5591 return 0;
5592}
5593
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005594/* This functio is an LUA binding. It permits to register a task
5595 * executed in parallel of the main HAroxy activity. The task is
5596 * created and it is set in the HAProxy scheduler. It can be called
5597 * from the "init" section, "post init" or during the runtime.
5598 *
5599 * Lua prototype:
5600 *
5601 * <none> core.register_task(<function>)
5602 */
5603static int hlua_register_task(lua_State *L)
5604{
5605 struct hlua *hlua;
5606 struct task *task;
5607 int ref;
5608
5609 MAY_LJMP(check_args(L, 1, "register_task"));
5610
5611 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5612
Willy Tarreaubafbe012017-11-24 17:34:44 +01005613 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005614 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005615 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005616
Emeric Brunc60def82017-09-27 14:59:38 +02005617 task = task_new(MAX_THREADS_MASK);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005618 task->context = hlua;
5619 task->process = hlua_process_task;
5620
5621 if (!hlua_ctx_init(hlua, task))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005622 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005623
5624 /* Restore the function in the stack. */
5625 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5626 hlua->nargs = 0;
5627
5628 /* Schedule task. */
5629 task_schedule(task, now_ms);
5630
5631 return 0;
5632}
5633
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005634/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5635 * doesn't allow "yield" functions because the HAProxy engine cannot
5636 * resume converters.
5637 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005638static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005639{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005640 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005641 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005642 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005643
Willy Tarreaube508f12016-03-10 11:47:01 +01005644 if (!stream)
5645 return 0;
5646
Willy Tarreau87b09662015-04-03 00:22:06 +02005647 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005648 * Lua context can be not initialized. This behavior
5649 * permits to save performances because a systematic
5650 * Lua initialization cause 5% performances loss.
5651 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005652 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005653 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005654 if (!stream->hlua) {
5655 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5656 return 0;
5657 }
5658 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5659 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5660 return 0;
5661 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005662 }
5663
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005664 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005665 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005666
5667 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005668 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5669 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5670 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005671 else
5672 error = "critical error";
5673 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005674 return 0;
5675 }
5676
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005677 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005678 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005679 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005680 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005681 return 0;
5682 }
5683
5684 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005685 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005686
5687 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005688 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005689 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005690 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005691 return 0;
5692 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005693 hlua_smp2lua(stream->hlua->T, smp);
5694 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005695
5696 /* push keywords in the stack. */
5697 if (arg_p) {
5698 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005699 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005700 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005701 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005702 return 0;
5703 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005704 hlua_arg2lua(stream->hlua->T, arg_p);
5705 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005706 }
5707 }
5708
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005709 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005710 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005711
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005712 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005713 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005714 }
5715
5716 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005717 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005718 /* finished. */
5719 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005720 /* If the stack is empty, the function fails. */
5721 if (lua_gettop(stream->hlua->T) <= 0)
5722 return 0;
5723
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005724 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005725 hlua_lua2smp(stream->hlua->T, -1, smp);
5726 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005727 return 1;
5728
5729 /* yield. */
5730 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005731 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005732 return 0;
5733
5734 /* finished with error. */
5735 case HLUA_E_ERRMSG:
5736 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005737 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005738 fcn->name, lua_tostring(stream->hlua->T, -1));
5739 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005740 return 0;
5741
Thierry Fournierd5b073c2018-05-21 19:42:47 +02005742 case HLUA_E_ETMOUT:
5743 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
5744 return 0;
5745
5746 case HLUA_E_NOMEM:
5747 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
5748 return 0;
5749
5750 case HLUA_E_YIELD:
5751 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
5752 return 0;
5753
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005754 case HLUA_E_ERR:
5755 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005756 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005757
5758 default:
5759 return 0;
5760 }
5761}
5762
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005763/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5764 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005765 * resume sample-fetches. This function will be called by the sample
5766 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005767 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005768static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5769 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005770{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005771 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005772 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005773 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005774 const struct chunk msg = { .len = 0 };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005775
Willy Tarreaube508f12016-03-10 11:47:01 +01005776 if (!stream)
5777 return 0;
5778
Willy Tarreau87b09662015-04-03 00:22:06 +02005779 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005780 * Lua context can be not initialized. This behavior
5781 * permits to save performances because a systematic
5782 * Lua initialization cause 5% performances loss.
5783 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005784 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005785 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005786 if (!stream->hlua) {
5787 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5788 return 0;
5789 }
5790 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5791 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5792 return 0;
5793 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005794 }
5795
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005796 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005797
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005798 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005799 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005800
5801 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005802 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5803 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5804 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005805 else
5806 error = "critical error";
5807 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005808 return 0;
5809 }
5810
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005811 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005812 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005813 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005814 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005815 return 0;
5816 }
5817
5818 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005819 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005820
5821 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005822 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005823 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005824 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005825 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005826 return 0;
5827 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005828 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005829
5830 /* push keywords in the stack. */
5831 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5832 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005833 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005834 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005835 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005836 return 0;
5837 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005838 hlua_arg2lua(stream->hlua->T, arg_p);
5839 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005840 }
5841
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005842 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005843 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005844
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005845 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005846 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005847 }
5848
5849 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005850 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005851 /* finished. */
5852 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005853 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005854 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005855 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005856 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005857 /* If the stack is empty, the function fails. */
5858 if (lua_gettop(stream->hlua->T) <= 0)
5859 return 0;
5860
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005861 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005862 hlua_lua2smp(stream->hlua->T, -1, smp);
5863 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005864
5865 /* Set the end of execution flag. */
5866 smp->flags &= ~SMP_F_MAY_CHANGE;
5867 return 1;
5868
5869 /* yield. */
5870 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005871 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005872 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005873 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005874 return 0;
5875
5876 /* finished with error. */
5877 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005878 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005879 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005880 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005881 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005882 fcn->name, lua_tostring(stream->hlua->T, -1));
5883 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005884 return 0;
5885
Thierry Fournierd5b073c2018-05-21 19:42:47 +02005886 case HLUA_E_ETMOUT:
5887 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
5888 stream_int_retnclose(&stream->si[0], &msg);
5889 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
5890 return 0;
5891
5892 case HLUA_E_NOMEM:
5893 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
5894 stream_int_retnclose(&stream->si[0], &msg);
5895 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
5896 return 0;
5897
5898 case HLUA_E_YIELD:
5899 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
5900 stream_int_retnclose(&stream->si[0], &msg);
5901 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
5902 return 0;
5903
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005904 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005905 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005906 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005907 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005908 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005909
5910 default:
5911 return 0;
5912 }
5913}
5914
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005915/* This function is an LUA binding used for registering
5916 * "sample-conv" functions. It expects a converter name used
5917 * in the haproxy configuration file, and an LUA function.
5918 */
5919__LJMP static int hlua_register_converters(lua_State *L)
5920{
5921 struct sample_conv_kw_list *sck;
5922 const char *name;
5923 int ref;
5924 int len;
5925 struct hlua_function *fcn;
5926
5927 MAY_LJMP(check_args(L, 2, "register_converters"));
5928
5929 /* First argument : converter name. */
5930 name = MAY_LJMP(luaL_checkstring(L, 1));
5931
5932 /* Second argument : lua function. */
5933 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5934
5935 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005936 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005937 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005938 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005939 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005940 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005941 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005942
5943 /* Fill fcn. */
5944 fcn->name = strdup(name);
5945 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005946 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005947 fcn->function_ref = ref;
5948
5949 /* List head */
5950 sck->list.n = sck->list.p = NULL;
5951
5952 /* converter keyword. */
5953 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005954 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005955 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005956 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005957
5958 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5959 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005960 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 +01005961 sck->kw[0].val_args = NULL;
5962 sck->kw[0].in_type = SMP_T_STR;
5963 sck->kw[0].out_type = SMP_T_STR;
5964 sck->kw[0].private = fcn;
5965
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005966 /* Register this new converter */
5967 sample_register_convs(sck);
5968
5969 return 0;
5970}
5971
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005972/* This fucntion is an LUA binding used for registering
5973 * "sample-fetch" functions. It expects a converter name used
5974 * in the haproxy configuration file, and an LUA function.
5975 */
5976__LJMP static int hlua_register_fetches(lua_State *L)
5977{
5978 const char *name;
5979 int ref;
5980 int len;
5981 struct sample_fetch_kw_list *sfk;
5982 struct hlua_function *fcn;
5983
5984 MAY_LJMP(check_args(L, 2, "register_fetches"));
5985
5986 /* First argument : sample-fetch name. */
5987 name = MAY_LJMP(luaL_checkstring(L, 1));
5988
5989 /* Second argument : lua function. */
5990 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5991
5992 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005993 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005994 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005995 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005996 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005997 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005998 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005999
6000 /* Fill fcn. */
6001 fcn->name = strdup(name);
6002 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006003 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006004 fcn->function_ref = ref;
6005
6006 /* List head */
6007 sfk->list.n = sfk->list.p = NULL;
6008
6009 /* sample-fetch keyword. */
6010 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006011 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006012 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006013 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006014
6015 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6016 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006017 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 +01006018 sfk->kw[0].val_args = NULL;
6019 sfk->kw[0].out_type = SMP_T_STR;
6020 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6021 sfk->kw[0].val = 0;
6022 sfk->kw[0].private = fcn;
6023
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006024 /* Register this new fetch. */
6025 sample_register_fetches(sfk);
6026
6027 return 0;
6028}
6029
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006030/* This function is a wrapper to execute each LUA function declared
6031 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006032 * return ACT_RET_CONT if the processing is finished (with or without
6033 * error) and return ACT_RET_YIELD if the function must be called again
6034 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006035 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006036static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006037 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006038{
6039 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006040 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006041 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006042 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006043 const struct chunk msg = { .len = 0 };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006044
6045 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01006046 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
6047 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
6048 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
6049 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006050 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006051 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006052 return ACT_RET_CONT;
6053 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006054
Willy Tarreau87b09662015-04-03 00:22:06 +02006055 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006056 * Lua context can be not initialized. This behavior
6057 * permits to save performances because a systematic
6058 * Lua initialization cause 5% performances loss.
6059 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006060 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006061 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006062 if (!s->hlua) {
6063 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6064 rule->arg.hlua_rule->fcn.name);
6065 return ACT_RET_CONT;
6066 }
6067 if (!hlua_ctx_init(s->hlua, s->task)) {
6068 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6069 rule->arg.hlua_rule->fcn.name);
6070 return ACT_RET_CONT;
6071 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006072 }
6073
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006074 consistency_set(s, dir, &s->hlua->cons);
6075
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006076 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006077 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006078
6079 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006080 if (!SET_SAFE_LJMP(s->hlua->T)) {
6081 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6082 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006083 else
6084 error = "critical error";
6085 SEND_ERR(px, "Lua function '%s': %s.\n",
6086 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006087 return ACT_RET_CONT;
6088 }
6089
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006090 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006091 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006092 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006093 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006094 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006095 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006096 }
6097
6098 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006099 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006100
Willy Tarreau87b09662015-04-03 00:22:06 +02006101 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006102 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006103 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006104 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006105 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006106 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006107 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006108 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006109
6110 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006111 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006112 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006113 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006114 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006115 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006116 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006117 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006118 lua_pushstring(s->hlua->T, *arg);
6119 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006120 }
6121
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006122 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006123 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006124
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006125 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006126 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006127 }
6128
6129 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006130 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006131 /* finished. */
6132 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006133 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006134 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006135 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006136 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006137 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006138 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006139 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006140
6141 /* yield. */
6142 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006143 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006144 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006145 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006146 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006147 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006148 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006149 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006150 /* Some actions can be wake up when a "write" event
6151 * is detected on a response channel. This is useful
6152 * only for actions targetted on the requests.
6153 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006154 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006155 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01006156 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006157 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006158 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006159 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006160 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006161 /* We can quit the fcuntion without consistency check
6162 * because HAProxy is not able to manipulate data, it
6163 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006164 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006165
6166 /* finished with error. */
6167 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006168 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006169 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006170 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006171 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006172 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006173 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006174 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6175 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006176 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006177
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006178 case HLUA_E_ETMOUT:
6179 if (!consistency_check(s, dir, &s->hlua->cons)) {
6180 stream_int_retnclose(&s->si[0], &msg);
6181 return ACT_RET_ERR;
6182 }
6183 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
6184 return 0;
6185
6186 case HLUA_E_NOMEM:
6187 if (!consistency_check(s, dir, &s->hlua->cons)) {
6188 stream_int_retnclose(&s->si[0], &msg);
6189 return ACT_RET_ERR;
6190 }
6191 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
6192 return 0;
6193
6194 case HLUA_E_YIELD:
6195 if (!consistency_check(s, dir, &s->hlua->cons)) {
6196 stream_int_retnclose(&s->si[0], &msg);
6197 return ACT_RET_ERR;
6198 }
6199 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6200 rule->arg.hlua_rule->fcn.name);
6201 return 0;
6202
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006203 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006204 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006205 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006206 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006207 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006208 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006209 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006210 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006211
6212 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006213 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006214 }
6215}
6216
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006217struct task *hlua_applet_wakeup(struct task *t)
6218{
6219 struct appctx *ctx = t->context;
6220 struct stream_interface *si = ctx->owner;
6221
6222 /* If the applet is wake up without any expected work, the sheduler
6223 * remove it from the run queue. This flag indicate that the applet
6224 * is waiting for write. If the buffer is full, the main processing
6225 * will send some data and after call the applet, otherwise it call
6226 * the applet ASAP.
6227 */
6228 si_applet_cant_put(si);
6229 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006230 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006231 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006232}
6233
6234static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6235{
6236 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006237 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006238 struct task *task;
6239 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006240 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006241
Willy Tarreaubafbe012017-11-24 17:34:44 +01006242 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006243 if (!hlua) {
6244 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6245 ctx->rule->arg.hlua_rule->fcn.name);
6246 return 0;
6247 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006248 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006249 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006250 ctx->ctx.hlua_apptcp.flags = 0;
6251
6252 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006253 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006254 if (!task) {
6255 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6256 ctx->rule->arg.hlua_rule->fcn.name);
6257 return 0;
6258 }
6259 task->nice = 0;
6260 task->context = ctx;
6261 task->process = hlua_applet_wakeup;
6262 ctx->ctx.hlua_apptcp.task = task;
6263
6264 /* In the execution wrappers linked with a stream, the
6265 * Lua context can be not initialized. This behavior
6266 * permits to save performances because a systematic
6267 * Lua initialization cause 5% performances loss.
6268 */
6269 if (!hlua_ctx_init(hlua, task)) {
6270 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6271 ctx->rule->arg.hlua_rule->fcn.name);
6272 return 0;
6273 }
6274
6275 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006276 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006277
6278 /* The following Lua calls can fail. */
6279 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006280 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6281 error = lua_tostring(hlua->T, -1);
6282 else
6283 error = "critical error";
6284 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6285 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006286 RESET_SAFE_LJMP(hlua->T);
6287 return 0;
6288 }
6289
6290 /* Check stack available size. */
6291 if (!lua_checkstack(hlua->T, 1)) {
6292 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6293 ctx->rule->arg.hlua_rule->fcn.name);
6294 RESET_SAFE_LJMP(hlua->T);
6295 return 0;
6296 }
6297
6298 /* Restore the function in the stack. */
6299 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6300
6301 /* Create and and push object stream in the stack. */
6302 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6303 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6304 ctx->rule->arg.hlua_rule->fcn.name);
6305 RESET_SAFE_LJMP(hlua->T);
6306 return 0;
6307 }
6308 hlua->nargs = 1;
6309
6310 /* push keywords in the stack. */
6311 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6312 if (!lua_checkstack(hlua->T, 1)) {
6313 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6314 ctx->rule->arg.hlua_rule->fcn.name);
6315 RESET_SAFE_LJMP(hlua->T);
6316 return 0;
6317 }
6318 lua_pushstring(hlua->T, *arg);
6319 hlua->nargs++;
6320 }
6321
6322 RESET_SAFE_LJMP(hlua->T);
6323
6324 /* Wakeup the applet ASAP. */
6325 si_applet_cant_get(si);
6326 si_applet_cant_put(si);
6327
6328 return 1;
6329}
6330
6331static void hlua_applet_tcp_fct(struct appctx *ctx)
6332{
6333 struct stream_interface *si = ctx->owner;
6334 struct stream *strm = si_strm(si);
6335 struct channel *res = si_ic(si);
6336 struct act_rule *rule = ctx->rule;
6337 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006338 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006339
6340 /* The applet execution is already done. */
6341 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
6342 return;
6343
6344 /* If the stream is disconnect or closed, ldo nothing. */
6345 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6346 return;
6347
6348 /* Execute the function. */
6349 switch (hlua_ctx_resume(hlua, 1)) {
6350 /* finished. */
6351 case HLUA_E_OK:
6352 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6353
6354 /* log time */
6355 strm->logs.tv_request = now;
6356
6357 /* eat the whole request */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006358 co_skip(si_oc(si), si_ob(si)->o);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006359 res->flags |= CF_READ_NULL;
6360 si_shutr(si);
6361 return;
6362
6363 /* yield. */
6364 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006365 if (hlua->wake_time != TICK_ETERNITY)
6366 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006367 return;
6368
6369 /* finished with error. */
6370 case HLUA_E_ERRMSG:
6371 /* Display log. */
6372 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6373 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6374 lua_pop(hlua->T, 1);
6375 goto error;
6376
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006377 case HLUA_E_ETMOUT:
6378 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
6379 rule->arg.hlua_rule->fcn.name);
6380 goto error;
6381
6382 case HLUA_E_NOMEM:
6383 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
6384 rule->arg.hlua_rule->fcn.name);
6385 goto error;
6386
6387 case HLUA_E_YIELD: /* unexpected */
6388 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
6389 rule->arg.hlua_rule->fcn.name);
6390 goto error;
6391
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006392 case HLUA_E_ERR:
6393 /* Display log. */
6394 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6395 rule->arg.hlua_rule->fcn.name);
6396 goto error;
6397
6398 default:
6399 goto error;
6400 }
6401
6402error:
6403
6404 /* For all other cases, just close the stream. */
6405 si_shutw(si);
6406 si_shutr(si);
6407 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6408}
6409
6410static void hlua_applet_tcp_release(struct appctx *ctx)
6411{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006412 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006413 task_free(ctx->ctx.hlua_apptcp.task);
6414 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006415 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006416 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006417}
6418
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006419/* The function returns 1 if the initialisation is complete, 0 if
6420 * an errors occurs and -1 if more data are required for initializing
6421 * the applet.
6422 */
6423static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6424{
6425 struct stream_interface *si = ctx->owner;
6426 struct channel *req = si_oc(si);
6427 struct http_msg *msg;
6428 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006429 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006430 char **arg;
6431 struct hdr_ctx hdr;
6432 struct task *task;
6433 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006434 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006435
6436 /* Wait for a full HTTP request. */
6437 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6438 if (smp.flags & SMP_F_MAY_CHANGE)
6439 return -1;
6440 return 0;
6441 }
6442 txn = strm->txn;
6443 msg = &txn->req;
6444
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006445 /* We want two things in HTTP mode :
6446 * - enforce server-close mode if we were in keep-alive, so that the
6447 * applet is released after each response ;
6448 * - enable request body transfer to the applet in order to resync
6449 * with the response body.
6450 */
6451 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6452 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006453
Willy Tarreaubafbe012017-11-24 17:34:44 +01006454 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006455 if (!hlua) {
6456 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6457 ctx->rule->arg.hlua_rule->fcn.name);
6458 return 0;
6459 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006460 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006461 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006462 ctx->ctx.hlua_apphttp.left_bytes = -1;
6463 ctx->ctx.hlua_apphttp.flags = 0;
6464
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006465 if (txn->req.flags & HTTP_MSGF_VER_11)
6466 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6467
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006468 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006469 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006470 if (!task) {
6471 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6472 ctx->rule->arg.hlua_rule->fcn.name);
6473 return 0;
6474 }
6475 task->nice = 0;
6476 task->context = ctx;
6477 task->process = hlua_applet_wakeup;
6478 ctx->ctx.hlua_apphttp.task = task;
6479
6480 /* In the execution wrappers linked with a stream, the
6481 * Lua context can be not initialized. This behavior
6482 * permits to save performances because a systematic
6483 * Lua initialization cause 5% performances loss.
6484 */
6485 if (!hlua_ctx_init(hlua, task)) {
6486 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6487 ctx->rule->arg.hlua_rule->fcn.name);
6488 return 0;
6489 }
6490
6491 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006492 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006493
6494 /* The following Lua calls can fail. */
6495 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006496 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6497 error = lua_tostring(hlua->T, -1);
6498 else
6499 error = "critical error";
6500 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6501 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006502 return 0;
6503 }
6504
6505 /* Check stack available size. */
6506 if (!lua_checkstack(hlua->T, 1)) {
6507 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6508 ctx->rule->arg.hlua_rule->fcn.name);
6509 RESET_SAFE_LJMP(hlua->T);
6510 return 0;
6511 }
6512
6513 /* Restore the function in the stack. */
6514 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6515
6516 /* Create and and push object stream in the stack. */
6517 if (!hlua_applet_http_new(hlua->T, ctx)) {
6518 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6519 ctx->rule->arg.hlua_rule->fcn.name);
6520 RESET_SAFE_LJMP(hlua->T);
6521 return 0;
6522 }
6523 hlua->nargs = 1;
6524
6525 /* Look for a 100-continue expected. */
6526 if (msg->flags & HTTP_MSGF_VER_11) {
6527 hdr.idx = 0;
6528 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
6529 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6530 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6531 }
6532
6533 /* push keywords in the stack. */
6534 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6535 if (!lua_checkstack(hlua->T, 1)) {
6536 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6537 ctx->rule->arg.hlua_rule->fcn.name);
6538 RESET_SAFE_LJMP(hlua->T);
6539 return 0;
6540 }
6541 lua_pushstring(hlua->T, *arg);
6542 hlua->nargs++;
6543 }
6544
6545 RESET_SAFE_LJMP(hlua->T);
6546
6547 /* Wakeup the applet when data is ready for read. */
6548 si_applet_cant_get(si);
6549
6550 return 1;
6551}
6552
6553static void hlua_applet_http_fct(struct appctx *ctx)
6554{
6555 struct stream_interface *si = ctx->owner;
6556 struct stream *strm = si_strm(si);
6557 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006558 struct act_rule *rule = ctx->rule;
6559 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006560 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006561 char *blk1;
6562 int len1;
6563 char *blk2;
6564 int len2;
6565 int ret;
6566
6567 /* If the stream is disconnect or closed, ldo nothing. */
6568 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6569 return;
6570
6571 /* Set the currently running flag. */
6572 if (!HLUA_IS_RUNNING(hlua) &&
6573 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6574
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006575 /* Wait for full HTTP analysys. */
6576 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6577 si_applet_cant_get(si);
6578 return;
6579 }
6580
6581 /* Store the max amount of bytes that we can read. */
6582 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6583
6584 /* We need to flush the request header. This left the body
6585 * for the Lua.
6586 */
6587
6588 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006589 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006590 if (ret == -1)
6591 return;
6592
6593 /* No data available, ask for more data. */
6594 if (ret == 1)
6595 len2 = 0;
6596 if (ret == 0)
6597 len1 = 0;
6598 if (len1 + len2 < strm->txn->req.eoh + 2) {
6599 si_applet_cant_get(si);
6600 return;
6601 }
6602
6603 /* skip the requests bytes. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006604 co_skip(si_oc(si), strm->txn->req.eoh + 2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006605 }
6606
6607 /* Executes The applet if it is not done. */
6608 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6609
6610 /* Execute the function. */
6611 switch (hlua_ctx_resume(hlua, 1)) {
6612 /* finished. */
6613 case HLUA_E_OK:
6614 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6615 break;
6616
6617 /* yield. */
6618 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006619 if (hlua->wake_time != TICK_ETERNITY)
6620 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006621 return;
6622
6623 /* finished with error. */
6624 case HLUA_E_ERRMSG:
6625 /* Display log. */
6626 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6627 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6628 lua_pop(hlua->T, 1);
6629 goto error;
6630
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006631 case HLUA_E_ETMOUT:
6632 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
6633 rule->arg.hlua_rule->fcn.name);
6634 goto error;
6635
6636 case HLUA_E_NOMEM:
6637 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
6638 rule->arg.hlua_rule->fcn.name);
6639 goto error;
6640
6641 case HLUA_E_YIELD: /* unexpected */
6642 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
6643 rule->arg.hlua_rule->fcn.name);
6644 goto error;
6645
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006646 case HLUA_E_ERR:
6647 /* Display log. */
6648 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6649 rule->arg.hlua_rule->fcn.name);
6650 goto error;
6651
6652 default:
6653 goto error;
6654 }
6655 }
6656
6657 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6658
6659 /* We must send the final chunk. */
6660 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6661 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6662
6663 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006664 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006665
6666 /* critical error. */
6667 if (ret == -2 || ret == -3) {
6668 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6669 rule->arg.hlua_rule->fcn.name);
6670 goto error;
6671 }
6672
6673 /* no enough space error. */
6674 if (ret == -1) {
6675 si_applet_cant_put(si);
6676 return;
6677 }
6678
6679 /* set the last chunk sent. */
6680 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6681 }
6682
6683 /* close the connection. */
6684
6685 /* status / log */
6686 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6687 strm->logs.tv_request = now;
6688
6689 /* eat the whole request */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006690 co_skip(si_oc(si), si_ob(si)->o);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006691 res->flags |= CF_READ_NULL;
6692 si_shutr(si);
6693
6694 return;
6695 }
6696
6697error:
6698
6699 /* If we are in HTTP mode, and we are not send any
6700 * data, return a 500 server error in best effort:
6701 * if there are no room avalaible in the buffer,
6702 * just close the connection.
6703 */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006704 ci_putblk(res, error_500, strlen(error_500));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006705 if (!(strm->flags & SF_ERR_MASK))
6706 strm->flags |= SF_ERR_RESOURCE;
6707 si_shutw(si);
6708 si_shutr(si);
6709 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6710}
6711
6712static void hlua_applet_http_release(struct appctx *ctx)
6713{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006714 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006715 task_free(ctx->ctx.hlua_apphttp.task);
6716 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006717 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006718 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006719}
6720
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006721/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6722 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006723 *
6724 * This function can fail with an abort() due to an Lua critical error.
6725 * We are in the configuration parsing process of HAProxy, this abort() is
6726 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006727 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006728static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6729 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006730{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006731 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006732 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006733
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006734 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006735 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006736 if (!rule->arg.hlua_rule) {
6737 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006738 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006739 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006740
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006741 /* Memory for arguments. */
6742 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6743 if (!rule->arg.hlua_rule->args) {
6744 memprintf(err, "out of memory error");
6745 return ACT_RET_PRS_ERR;
6746 }
6747
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006748 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006749 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006750
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006751 /* Expect some arguments */
6752 for (i = 0; i < fcn->nargs; i++) {
6753 if (*args[i+1] == '\0') {
6754 memprintf(err, "expect %d arguments", fcn->nargs);
6755 return ACT_RET_PRS_ERR;
6756 }
6757 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6758 if (!rule->arg.hlua_rule->args[i]) {
6759 memprintf(err, "out of memory error");
6760 return ACT_RET_PRS_ERR;
6761 }
6762 (*cur_arg)++;
6763 }
6764 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006765
Thierry FOURNIER42148732015-09-02 17:17:33 +02006766 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006767 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006768 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006769}
6770
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006771static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6772 struct act_rule *rule, char **err)
6773{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006774 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006775
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006776 /* HTTP applets are forbidden in tcp-request rules.
6777 * HTTP applet request requires everything initilized by
6778 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6779 * The applet will be immediately initilized, but its before
6780 * the call of this analyzer.
6781 */
6782 if (rule->from != ACT_F_HTTP_REQ) {
6783 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6784 return ACT_RET_PRS_ERR;
6785 }
6786
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006787 /* Memory for the rule. */
6788 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6789 if (!rule->arg.hlua_rule) {
6790 memprintf(err, "out of memory error");
6791 return ACT_RET_PRS_ERR;
6792 }
6793
6794 /* Reference the Lua function and store the reference. */
6795 rule->arg.hlua_rule->fcn = *fcn;
6796
6797 /* TODO: later accept arguments. */
6798 rule->arg.hlua_rule->args = NULL;
6799
6800 /* Add applet pointer in the rule. */
6801 rule->applet.obj_type = OBJ_TYPE_APPLET;
6802 rule->applet.name = fcn->name;
6803 rule->applet.init = hlua_applet_http_init;
6804 rule->applet.fct = hlua_applet_http_fct;
6805 rule->applet.release = hlua_applet_http_release;
6806 rule->applet.timeout = hlua_timeout_applet;
6807
6808 return ACT_RET_PRS_OK;
6809}
6810
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006811/* This function is an LUA binding used for registering
6812 * "sample-conv" functions. It expects a converter name used
6813 * in the haproxy configuration file, and an LUA function.
6814 */
6815__LJMP static int hlua_register_action(lua_State *L)
6816{
6817 struct action_kw_list *akl;
6818 const char *name;
6819 int ref;
6820 int len;
6821 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006822 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006823
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006824 /* Initialise the number of expected arguments at 0. */
6825 nargs = 0;
6826
6827 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6828 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006829
6830 /* First argument : converter name. */
6831 name = MAY_LJMP(luaL_checkstring(L, 1));
6832
6833 /* Second argument : environment. */
6834 if (lua_type(L, 2) != LUA_TTABLE)
6835 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6836
6837 /* Third argument : lua function. */
6838 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6839
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006840 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6841 if (lua_gettop(L) >= 4)
6842 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6843
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006844 /* browse the second argulent as an array. */
6845 lua_pushnil(L);
6846 while (lua_next(L, 2) != 0) {
6847 if (lua_type(L, -1) != LUA_TSTRING)
6848 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6849
6850 /* Check required environment. Only accepted "http" or "tcp". */
6851 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006852 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006853 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006854 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006855 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006856 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006857 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006858
6859 /* Fill fcn. */
6860 fcn->name = strdup(name);
6861 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006862 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006863 fcn->function_ref = ref;
6864
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006865 /* Set the expected number od arguments. */
6866 fcn->nargs = nargs;
6867
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006868 /* List head */
6869 akl->list.n = akl->list.p = NULL;
6870
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006871 /* action keyword. */
6872 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006873 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006874 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006875 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006876
6877 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6878
6879 akl->kw[0].match_pfx = 0;
6880 akl->kw[0].private = fcn;
6881 akl->kw[0].parse = action_register_lua;
6882
6883 /* select the action registering point. */
6884 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6885 tcp_req_cont_keywords_register(akl);
6886 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6887 tcp_res_cont_keywords_register(akl);
6888 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6889 http_req_keywords_register(akl);
6890 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6891 http_res_keywords_register(akl);
6892 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006893 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006894 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6895 "are expected.", lua_tostring(L, -1)));
6896
6897 /* pop the environment string. */
6898 lua_pop(L, 1);
6899 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006900 return ACT_RET_PRS_OK;
6901}
6902
6903static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6904 struct act_rule *rule, char **err)
6905{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006906 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006907
6908 /* Memory for the rule. */
6909 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6910 if (!rule->arg.hlua_rule) {
6911 memprintf(err, "out of memory error");
6912 return ACT_RET_PRS_ERR;
6913 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006914
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006915 /* Reference the Lua function and store the reference. */
6916 rule->arg.hlua_rule->fcn = *fcn;
6917
6918 /* TODO: later accept arguments. */
6919 rule->arg.hlua_rule->args = NULL;
6920
6921 /* Add applet pointer in the rule. */
6922 rule->applet.obj_type = OBJ_TYPE_APPLET;
6923 rule->applet.name = fcn->name;
6924 rule->applet.init = hlua_applet_tcp_init;
6925 rule->applet.fct = hlua_applet_tcp_fct;
6926 rule->applet.release = hlua_applet_tcp_release;
6927 rule->applet.timeout = hlua_timeout_applet;
6928
6929 return 0;
6930}
6931
6932/* This function is an LUA binding used for registering
6933 * "sample-conv" functions. It expects a converter name used
6934 * in the haproxy configuration file, and an LUA function.
6935 */
6936__LJMP static int hlua_register_service(lua_State *L)
6937{
6938 struct action_kw_list *akl;
6939 const char *name;
6940 const char *env;
6941 int ref;
6942 int len;
6943 struct hlua_function *fcn;
6944
6945 MAY_LJMP(check_args(L, 3, "register_service"));
6946
6947 /* First argument : converter name. */
6948 name = MAY_LJMP(luaL_checkstring(L, 1));
6949
6950 /* Second argument : environment. */
6951 env = MAY_LJMP(luaL_checkstring(L, 2));
6952
6953 /* Third argument : lua function. */
6954 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6955
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006956 /* Allocate and fill the sample fetch keyword struct. */
6957 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6958 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006959 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006960 fcn = calloc(1, sizeof(*fcn));
6961 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006962 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006963
6964 /* Fill fcn. */
6965 len = strlen("<lua.>") + strlen(name) + 1;
6966 fcn->name = calloc(1, len);
6967 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006968 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006969 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6970 fcn->function_ref = ref;
6971
6972 /* List head */
6973 akl->list.n = akl->list.p = NULL;
6974
6975 /* converter keyword. */
6976 len = strlen("lua.") + strlen(name) + 1;
6977 akl->kw[0].kw = calloc(1, len);
6978 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006979 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006980
6981 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6982
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01006983 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006984 if (strcmp(env, "tcp") == 0)
6985 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006986 else if (strcmp(env, "http") == 0)
6987 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006988 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006989 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01006990 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006991
6992 akl->kw[0].match_pfx = 0;
6993 akl->kw[0].private = fcn;
6994
6995 /* End of array. */
6996 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6997
6998 /* Register this new converter */
6999 service_keywords_register(akl);
7000
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007001 return 0;
7002}
7003
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007004/* This function initialises Lua cli handler. It copies the
7005 * arguments in the Lua stack and create channel IO objects.
7006 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007007static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007008{
7009 struct hlua *hlua;
7010 struct hlua_function *fcn;
7011 int i;
7012 const char *error;
7013
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007014 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007015 appctx->ctx.hlua_cli.fcn = private;
7016
Willy Tarreaubafbe012017-11-24 17:34:44 +01007017 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007018 if (!hlua) {
7019 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007020 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007021 }
7022 HLUA_INIT(hlua);
7023 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007024
7025 /* Create task used by signal to wakeup applets.
7026 * We use the same wakeup fonction than the Lua applet_tcp and
7027 * applet_http. It is absolutely compatible.
7028 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007029 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007030 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007031 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007032 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007033 }
7034 appctx->ctx.hlua_cli.task->nice = 0;
7035 appctx->ctx.hlua_cli.task->context = appctx;
7036 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7037
7038 /* Initialises the Lua context */
7039 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
7040 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007041 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007042 }
7043
7044 /* The following Lua calls can fail. */
7045 if (!SET_SAFE_LJMP(hlua->T)) {
7046 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7047 error = lua_tostring(hlua->T, -1);
7048 else
7049 error = "critical error";
7050 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7051 goto error;
7052 }
7053
7054 /* Check stack available size. */
7055 if (!lua_checkstack(hlua->T, 2)) {
7056 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7057 goto error;
7058 }
7059
7060 /* Restore the function in the stack. */
7061 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7062
7063 /* Once the arguments parsed, the CLI is like an AppletTCP,
7064 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007065 */
7066 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7067 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7068 goto error;
7069 }
7070 hlua->nargs = 1;
7071
7072 /* push keywords in the stack. */
7073 for (i = 0; *args[i]; i++) {
7074 /* Check stack available size. */
7075 if (!lua_checkstack(hlua->T, 1)) {
7076 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7077 goto error;
7078 }
7079 lua_pushstring(hlua->T, args[i]);
7080 hlua->nargs++;
7081 }
7082
7083 /* We must initialize the execution timeouts. */
7084 hlua->max_time = hlua_timeout_session;
7085
7086 /* At this point the execution is safe. */
7087 RESET_SAFE_LJMP(hlua->T);
7088
7089 /* It's ok */
7090 return 0;
7091
7092 /* It's not ok. */
7093error:
7094 RESET_SAFE_LJMP(hlua->T);
7095 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007096 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007097 return 1;
7098}
7099
7100static int hlua_cli_io_handler_fct(struct appctx *appctx)
7101{
7102 struct hlua *hlua;
7103 struct stream_interface *si;
7104 struct hlua_function *fcn;
7105
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007106 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007107 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007108 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007109
7110 /* If the stream is disconnect or closed, ldo nothing. */
7111 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7112 return 1;
7113
7114 /* Execute the function. */
7115 switch (hlua_ctx_resume(hlua, 1)) {
7116
7117 /* finished. */
7118 case HLUA_E_OK:
7119 return 1;
7120
7121 /* yield. */
7122 case HLUA_E_AGAIN:
7123 /* We want write. */
7124 if (HLUA_IS_WAKERESWR(hlua))
7125 si_applet_cant_put(si);
7126 /* Set the timeout. */
7127 if (hlua->wake_time != TICK_ETERNITY)
7128 task_schedule(hlua->task, hlua->wake_time);
7129 return 0;
7130
7131 /* finished with error. */
7132 case HLUA_E_ERRMSG:
7133 /* Display log. */
7134 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
7135 fcn->name, lua_tostring(hlua->T, -1));
7136 lua_pop(hlua->T, 1);
7137 return 1;
7138
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007139 case HLUA_E_ETMOUT:
7140 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
7141 fcn->name);
7142 return 1;
7143
7144 case HLUA_E_NOMEM:
7145 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
7146 fcn->name);
7147 return 1;
7148
7149 case HLUA_E_YIELD: /* unexpected */
7150 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
7151 fcn->name);
7152 return 1;
7153
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007154 case HLUA_E_ERR:
7155 /* Display log. */
7156 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
7157 fcn->name);
7158 return 1;
7159
7160 default:
7161 return 1;
7162 }
7163
7164 return 1;
7165}
7166
7167static void hlua_cli_io_release_fct(struct appctx *appctx)
7168{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007169 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007170 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007171}
7172
7173/* This function is an LUA binding used for registering
7174 * new keywords in the cli. It expects a list of keywords
7175 * which are the "path". It is limited to 5 keywords. A
7176 * description of the command, a function to be executed
7177 * for the parsing and a function for io handlers.
7178 */
7179__LJMP static int hlua_register_cli(lua_State *L)
7180{
7181 struct cli_kw_list *cli_kws;
7182 const char *message;
7183 int ref_io;
7184 int len;
7185 struct hlua_function *fcn;
7186 int index;
7187 int i;
7188
7189 MAY_LJMP(check_args(L, 3, "register_cli"));
7190
7191 /* First argument : an array of maximum 5 keywords. */
7192 if (!lua_istable(L, 1))
7193 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
7194
7195 /* Second argument : string with contextual message. */
7196 message = MAY_LJMP(luaL_checkstring(L, 2));
7197
7198 /* Third and fourth argument : lua function. */
7199 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
7200
7201 /* Allocate and fill the sample fetch keyword struct. */
7202 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
7203 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007204 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007205 fcn = calloc(1, sizeof(*fcn));
7206 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007207 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007208
7209 /* Fill path. */
7210 index = 0;
7211 lua_pushnil(L);
7212 while(lua_next(L, 1) != 0) {
7213 if (index >= 5)
7214 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
7215 if (lua_type(L, -1) != LUA_TSTRING)
7216 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
7217 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
7218 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007219 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007220 index++;
7221 lua_pop(L, 1);
7222 }
7223
7224 /* Copy help message. */
7225 cli_kws->kw[0].usage = strdup(message);
7226 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007227 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007228
7229 /* Fill fcn io handler. */
7230 len = strlen("<lua.cli>") + 1;
7231 for (i = 0; i < index; i++)
7232 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
7233 fcn->name = calloc(1, len);
7234 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007235 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007236 strncat((char *)fcn->name, "<lua.cli", len);
7237 for (i = 0; i < index; i++) {
7238 strncat((char *)fcn->name, ".", len);
7239 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
7240 }
7241 strncat((char *)fcn->name, ">", len);
7242 fcn->function_ref = ref_io;
7243
7244 /* Fill last entries. */
7245 cli_kws->kw[0].private = fcn;
7246 cli_kws->kw[0].parse = hlua_cli_parse_fct;
7247 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
7248 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
7249
7250 /* Register this new converter */
7251 cli_register_kw(cli_kws);
7252
7253 return 0;
7254}
7255
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007256static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7257 struct proxy *defpx, const char *file, int line,
7258 char **err, unsigned int *timeout)
7259{
7260 const char *error;
7261
7262 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
7263 if (error && *error != '\0') {
7264 memprintf(err, "%s: invalid timeout", args[0]);
7265 return -1;
7266 }
7267 return 0;
7268}
7269
7270static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7271 struct proxy *defpx, const char *file, int line,
7272 char **err)
7273{
7274 return hlua_read_timeout(args, section_type, curpx, defpx,
7275 file, line, err, &hlua_timeout_session);
7276}
7277
7278static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7279 struct proxy *defpx, const char *file, int line,
7280 char **err)
7281{
7282 return hlua_read_timeout(args, section_type, curpx, defpx,
7283 file, line, err, &hlua_timeout_task);
7284}
7285
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007286static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7287 struct proxy *defpx, const char *file, int line,
7288 char **err)
7289{
7290 return hlua_read_timeout(args, section_type, curpx, defpx,
7291 file, line, err, &hlua_timeout_applet);
7292}
7293
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007294static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7295 struct proxy *defpx, const char *file, int line,
7296 char **err)
7297{
7298 char *error;
7299
7300 hlua_nb_instruction = strtoll(args[1], &error, 10);
7301 if (*error != '\0') {
7302 memprintf(err, "%s: invalid number", args[0]);
7303 return -1;
7304 }
7305 return 0;
7306}
7307
Willy Tarreau32f61e22015-03-18 17:54:59 +01007308static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7309 struct proxy *defpx, const char *file, int line,
7310 char **err)
7311{
7312 char *error;
7313
7314 if (*(args[1]) == 0) {
7315 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7316 return -1;
7317 }
7318 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7319 if (*error != '\0') {
7320 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7321 return -1;
7322 }
7323 return 0;
7324}
7325
7326
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007327/* This function is called by the main configuration key "lua-load". It loads and
7328 * execute an lua file during the parsing of the HAProxy configuration file. It is
7329 * the main lua entry point.
7330 *
7331 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7332 * occured, otherwise it returns 0.
7333 *
7334 * In some error case, LUA set an error message in top of the stack. This function
7335 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007336 *
7337 * This function can fail with an abort() due to an Lua critical error.
7338 * We are in the configuration parsing process of HAProxy, this abort() is
7339 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007340 */
7341static int hlua_load(char **args, int section_type, struct proxy *curpx,
7342 struct proxy *defpx, const char *file, int line,
7343 char **err)
7344{
7345 int error;
7346
7347 /* Just load and compile the file. */
7348 error = luaL_loadfile(gL.T, args[1]);
7349 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007350 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007351 lua_pop(gL.T, 1);
7352 return -1;
7353 }
7354
7355 /* If no syntax error where detected, execute the code. */
7356 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7357 switch (error) {
7358 case LUA_OK:
7359 break;
7360 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007361 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007362 lua_pop(gL.T, 1);
7363 return -1;
7364 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007365 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007366 return -1;
7367 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007368 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007369 lua_pop(gL.T, 1);
7370 return -1;
7371 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007372 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007373 lua_pop(gL.T, 1);
7374 return -1;
7375 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007376 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007377 lua_pop(gL.T, 1);
7378 return -1;
7379 }
7380
7381 return 0;
7382}
7383
7384/* configuration keywords declaration */
7385static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007386 { CFG_GLOBAL, "lua-load", hlua_load },
7387 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7388 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007389 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007390 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007391 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007392 { 0, NULL, NULL },
7393}};
7394
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007395/* This function can fail with an abort() due to an Lua critical error.
7396 * We are in the initialisation process of HAProxy, this abort() is
7397 * tolerated.
7398 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007399int hlua_post_init()
7400{
7401 struct hlua_init_function *init;
7402 const char *msg;
7403 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007404 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007405
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007406 /* Call post initialisation function in safe environement. */
7407 if (!SET_SAFE_LJMP(gL.T)) {
7408 if (lua_type(gL.T, -1) == LUA_TSTRING)
7409 error = lua_tostring(gL.T, -1);
7410 else
7411 error = "critical error";
7412 fprintf(stderr, "Lua post-init: %s.\n", error);
7413 exit(1);
7414 }
7415 hlua_fcn_post_init(gL.T);
7416 RESET_SAFE_LJMP(gL.T);
7417
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007418 list_for_each_entry(init, &hlua_init_functions, l) {
7419 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7420 ret = hlua_ctx_resume(&gL, 0);
7421 switch (ret) {
7422 case HLUA_E_OK:
7423 lua_pop(gL.T, -1);
7424 return 1;
7425 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007426 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007427 return 0;
7428 case HLUA_E_ERRMSG:
7429 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01007430 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007431 return 0;
7432 case HLUA_E_ERR:
7433 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007434 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007435 return 0;
7436 }
7437 }
7438 return 1;
7439}
7440
Willy Tarreau32f61e22015-03-18 17:54:59 +01007441/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7442 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7443 * is the previously allocated size or the kind of object in case of a new
7444 * allocation. <nsize> is the requested new size.
7445 */
7446static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7447{
7448 struct hlua_mem_allocator *zone = ud;
7449
7450 if (nsize == 0) {
7451 /* it's a free */
7452 if (ptr)
7453 zone->allocated -= osize;
7454 free(ptr);
7455 return NULL;
7456 }
7457
7458 if (!ptr) {
7459 /* it's a new allocation */
7460 if (zone->limit && zone->allocated + nsize > zone->limit)
7461 return NULL;
7462
7463 ptr = malloc(nsize);
7464 if (ptr)
7465 zone->allocated += nsize;
7466 return ptr;
7467 }
7468
7469 /* it's a realloc */
7470 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7471 return NULL;
7472
7473 ptr = realloc(ptr, nsize);
7474 if (ptr)
7475 zone->allocated += nsize - osize;
7476 return ptr;
7477}
7478
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007479/* Ithis function can fail with an abort() due to an Lua critical error.
7480 * We are in the initialisation process of HAProxy, this abort() is
7481 * tolerated.
7482 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007483void hlua_init(void)
7484{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007485 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007486 int idx;
7487 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007488 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007489 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007490 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007491#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007492 struct srv_kw *kw;
7493 int tmp_error;
7494 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007495 char *args[] = { /* SSL client configuration. */
7496 "ssl",
7497 "verify",
7498 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007499 NULL
7500 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007501#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007502
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007503 HA_SPIN_INIT(&hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02007504
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007505 /* Initialise struct hlua and com signals pool */
Willy Tarreaubafbe012017-11-24 17:34:44 +01007506 pool_head_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007507
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007508 /* Register configuration keywords. */
7509 cfg_register_keywords(&cfg_kws);
7510
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007511 /* Init main lua stack. */
7512 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007513 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007514 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007515 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007516 hlua_sethlua(&gL);
7517 gL.Tref = LUA_REFNIL;
7518 gL.task = NULL;
7519
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007520 /* From this point, until the end of the initialisation fucntion,
7521 * the Lua function can fail with an abort. We are in the initialisation
7522 * process of HAProxy, this abort() is tolerated.
7523 */
7524
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007525 /* Initialise lua. */
7526 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007527
Thierry Fournier75933d42016-01-21 09:30:18 +01007528 /* Set safe environment for the initialisation. */
7529 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007530 if (lua_type(gL.T, -1) == LUA_TSTRING)
7531 error_msg = lua_tostring(gL.T, -1);
7532 else
7533 error_msg = "critical error";
7534 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007535 exit(1);
7536 }
7537
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007538 /*
7539 *
7540 * Create "core" object.
7541 *
7542 */
7543
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007544 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007545 lua_newtable(gL.T);
7546
7547 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007548 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007549 hlua_class_const_int(gL.T, log_levels[i], i);
7550
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007551 /* Register special functions. */
7552 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007553 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007554 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007555 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007556 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007557 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007558 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007559 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007560 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007561 hlua_class_function(gL.T, "sleep", hlua_sleep);
7562 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007563 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7564 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7565 hlua_class_function(gL.T, "set_map", hlua_set_map);
7566 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007567 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007568 hlua_class_function(gL.T, "log", hlua_log);
7569 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7570 hlua_class_function(gL.T, "Info", hlua_log_info);
7571 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7572 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007573 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007574 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007575
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007576 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007577
7578 /*
7579 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007580 * Register class Map
7581 *
7582 */
7583
7584 /* This table entry is the object "Map" base. */
7585 lua_newtable(gL.T);
7586
7587 /* register pattern types. */
7588 for (i=0; i<PAT_MATCH_NUM; i++)
7589 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007590 for (i=0; i<PAT_MATCH_NUM; i++) {
7591 snprintf(trash.str, trash.size, "_%s", pat_match_names[i]);
7592 hlua_class_const_int(gL.T, trash.str, i);
7593 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007594
7595 /* register constructor. */
7596 hlua_class_function(gL.T, "new", hlua_map_new);
7597
7598 /* Create and fill the metatable. */
7599 lua_newtable(gL.T);
7600
7601 /* Create and fille the __index entry. */
7602 lua_pushstring(gL.T, "__index");
7603 lua_newtable(gL.T);
7604
7605 /* Register . */
7606 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7607 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7608
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007609 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007610
Thierry Fournier45e78d72016-02-19 18:34:46 +01007611 /* Register previous table in the registry with reference and named entry.
7612 * The function hlua_register_metatable() pops the stack, so we
7613 * previously create a copy of the table.
7614 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007615 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007616 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007617
7618 /* Assign the metatable to the mai Map object. */
7619 lua_setmetatable(gL.T, -2);
7620
7621 /* Set a name to the table. */
7622 lua_setglobal(gL.T, "Map");
7623
7624 /*
7625 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007626 * Register class Channel
7627 *
7628 */
7629
7630 /* Create and fill the metatable. */
7631 lua_newtable(gL.T);
7632
7633 /* Create and fille the __index entry. */
7634 lua_pushstring(gL.T, "__index");
7635 lua_newtable(gL.T);
7636
7637 /* Register . */
7638 hlua_class_function(gL.T, "get", hlua_channel_get);
7639 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7640 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7641 hlua_class_function(gL.T, "set", hlua_channel_set);
7642 hlua_class_function(gL.T, "append", hlua_channel_append);
7643 hlua_class_function(gL.T, "send", hlua_channel_send);
7644 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7645 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7646 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007647 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007648
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007649 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007650
7651 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007652 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007653
7654 /*
7655 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007656 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007657 *
7658 */
7659
7660 /* Create and fill the metatable. */
7661 lua_newtable(gL.T);
7662
7663 /* Create and fille the __index entry. */
7664 lua_pushstring(gL.T, "__index");
7665 lua_newtable(gL.T);
7666
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007667 /* Browse existing fetches and create the associated
7668 * object method.
7669 */
7670 sf = NULL;
7671 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7672
7673 /* Dont register the keywork if the arguments check function are
7674 * not safe during the runtime.
7675 */
7676 if ((sf->val_args != NULL) &&
7677 (sf->val_args != val_payload_lv) &&
7678 (sf->val_args != val_hdr))
7679 continue;
7680
7681 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7682 * by an underscore.
7683 */
7684 strncpy(trash.str, sf->kw, trash.size);
7685 trash.str[trash.size - 1] = '\0';
7686 for (p = trash.str; *p; p++)
7687 if (*p == '.' || *p == '-' || *p == '+')
7688 *p = '_';
7689
7690 /* Register the function. */
7691 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007692 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007693 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007694 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007695 }
7696
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007697 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007698
7699 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007700 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007701
7702 /*
7703 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007704 * Register class Converters
7705 *
7706 */
7707
7708 /* Create and fill the metatable. */
7709 lua_newtable(gL.T);
7710
7711 /* Create and fill the __index entry. */
7712 lua_pushstring(gL.T, "__index");
7713 lua_newtable(gL.T);
7714
7715 /* Browse existing converters and create the associated
7716 * object method.
7717 */
7718 sc = NULL;
7719 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7720 /* Dont register the keywork if the arguments check function are
7721 * not safe during the runtime.
7722 */
7723 if (sc->val_args != NULL)
7724 continue;
7725
7726 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7727 * by an underscore.
7728 */
7729 strncpy(trash.str, sc->kw, trash.size);
7730 trash.str[trash.size - 1] = '\0';
7731 for (p = trash.str; *p; p++)
7732 if (*p == '.' || *p == '-' || *p == '+')
7733 *p = '_';
7734
7735 /* Register the function. */
7736 lua_pushstring(gL.T, trash.str);
7737 lua_pushlightuserdata(gL.T, sc);
7738 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007739 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007740 }
7741
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007742 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007743
7744 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007745 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007746
7747 /*
7748 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007749 * Register class HTTP
7750 *
7751 */
7752
7753 /* Create and fill the metatable. */
7754 lua_newtable(gL.T);
7755
7756 /* Create and fille the __index entry. */
7757 lua_pushstring(gL.T, "__index");
7758 lua_newtable(gL.T);
7759
7760 /* Register Lua functions. */
7761 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7762 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7763 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7764 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7765 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7766 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7767 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7768 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7769 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7770 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7771
7772 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7773 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7774 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7775 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7776 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7777 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007778 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007779
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007780 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007781
7782 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007783 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007784
7785 /*
7786 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007787 * Register class AppletTCP
7788 *
7789 */
7790
7791 /* Create and fill the metatable. */
7792 lua_newtable(gL.T);
7793
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007794 /* Create and fille the __index entry. */
7795 lua_pushstring(gL.T, "__index");
7796 lua_newtable(gL.T);
7797
7798 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007799 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7800 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7801 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7802 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7803 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007804 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7805 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7806 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007807
7808 lua_settable(gL.T, -3);
7809
7810 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007811 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007812
7813 /*
7814 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007815 * Register class AppletHTTP
7816 *
7817 */
7818
7819 /* Create and fill the metatable. */
7820 lua_newtable(gL.T);
7821
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007822 /* Create and fille the __index entry. */
7823 lua_pushstring(gL.T, "__index");
7824 lua_newtable(gL.T);
7825
7826 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007827 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7828 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007829 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7830 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7831 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007832 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7833 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7834 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7835 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7836 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7837 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7838
7839 lua_settable(gL.T, -3);
7840
7841 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007842 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007843
7844 /*
7845 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007846 * Register class TXN
7847 *
7848 */
7849
7850 /* Create and fill the metatable. */
7851 lua_newtable(gL.T);
7852
7853 /* Create and fille the __index entry. */
7854 lua_pushstring(gL.T, "__index");
7855 lua_newtable(gL.T);
7856
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007857 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007858 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7859 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007860 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007861 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007862 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007863 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007864 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7865 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7866 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007867 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7868 hlua_class_function(gL.T, "log", hlua_txn_log);
7869 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7870 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7871 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7872 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007873
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007874 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007875
7876 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007877 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007878
7879 /*
7880 *
7881 * Register class Socket
7882 *
7883 */
7884
7885 /* Create and fill the metatable. */
7886 lua_newtable(gL.T);
7887
7888 /* Create and fille the __index entry. */
7889 lua_pushstring(gL.T, "__index");
7890 lua_newtable(gL.T);
7891
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007892#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007893 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007894#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007895 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7896 hlua_class_function(gL.T, "send", hlua_socket_send);
7897 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7898 hlua_class_function(gL.T, "close", hlua_socket_close);
7899 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7900 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7901 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7902 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7903
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007904 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007905
7906 /* Register the garbage collector entry. */
7907 lua_pushstring(gL.T, "__gc");
7908 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007909 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007910
7911 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007912 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007913
7914 /* Proxy and server configuration initialisation. */
7915 memset(&socket_proxy, 0, sizeof(socket_proxy));
7916 init_new_proxy(&socket_proxy);
7917 socket_proxy.parent = NULL;
7918 socket_proxy.last_change = now.tv_sec;
7919 socket_proxy.id = "LUA-SOCKET";
7920 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7921 socket_proxy.maxconn = 0;
7922 socket_proxy.accept = NULL;
7923 socket_proxy.options2 |= PR_O2_INDEPSTR;
7924 socket_proxy.srv = NULL;
7925 socket_proxy.conn_retries = 0;
7926 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7927
7928 /* Init TCP server: unchanged parameters */
7929 memset(&socket_tcp, 0, sizeof(socket_tcp));
7930 socket_tcp.next = NULL;
7931 socket_tcp.proxy = &socket_proxy;
7932 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7933 LIST_INIT(&socket_tcp.actconns);
7934 LIST_INIT(&socket_tcp.pendconns);
Christopher Faulet40a007c2017-07-03 15:41:01 +02007935 socket_tcp.priv_conns = NULL;
7936 socket_tcp.idle_conns = NULL;
7937 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02007938 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007939 socket_tcp.last_change = 0;
7940 socket_tcp.id = "LUA-TCP-CONN";
7941 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7942 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7943 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7944
7945 /* XXX: Copy default parameter from default server,
7946 * but the default server is not initialized.
7947 */
7948 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7949 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7950 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7951 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7952 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7953 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7954 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7955 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7956 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7957 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7958
7959 socket_tcp.check.status = HCHK_STATUS_INI;
7960 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7961 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7962 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7963 socket_tcp.check.server = &socket_tcp;
7964
7965 socket_tcp.agent.status = HCHK_STATUS_INI;
7966 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7967 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7968 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7969 socket_tcp.agent.server = &socket_tcp;
7970
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007971 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007972
7973#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007974 /* Init TCP server: unchanged parameters */
7975 memset(&socket_ssl, 0, sizeof(socket_ssl));
7976 socket_ssl.next = NULL;
7977 socket_ssl.proxy = &socket_proxy;
7978 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7979 LIST_INIT(&socket_ssl.actconns);
7980 LIST_INIT(&socket_ssl.pendconns);
Christopher Faulet40a007c2017-07-03 15:41:01 +02007981 socket_tcp.priv_conns = NULL;
7982 socket_tcp.idle_conns = NULL;
7983 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02007984 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007985 socket_ssl.last_change = 0;
7986 socket_ssl.id = "LUA-SSL-CONN";
7987 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7988 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7989 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7990
7991 /* XXX: Copy default parameter from default server,
7992 * but the default server is not initialized.
7993 */
7994 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7995 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7996 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7997 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7998 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7999 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8000 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8001 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8002 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8003 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8004
8005 socket_ssl.check.status = HCHK_STATUS_INI;
8006 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8007 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8008 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8009 socket_ssl.check.server = &socket_ssl;
8010
8011 socket_ssl.agent.status = HCHK_STATUS_INI;
8012 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8013 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8014 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8015 socket_ssl.agent.server = &socket_ssl;
8016
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008017 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008018 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008019
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008020 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008021 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8022 /*
8023 *
8024 * If the keyword is not known, we can search in the registered
8025 * server keywords. This is usefull to configure special SSL
8026 * features like client certificates and ssl_verify.
8027 *
8028 */
8029 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8030 if (tmp_error != 0) {
8031 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8032 abort(); /* This must be never arrives because the command line
8033 not editable by the user. */
8034 }
8035 idx += kw->skip;
8036 }
8037 }
8038
8039 /* Initialize SSL server. */
Willy Tarreaucbe6da52018-05-18 17:08:28 +02008040 if (socket_ssl.xprt->prepare_srv) {
8041 int saved_used_backed = global.ssl_used_backend;
8042 // don't affect maxconn automatic computation
Willy Tarreau17d45382016-12-22 21:16:08 +01008043 socket_ssl.xprt->prepare_srv(&socket_ssl);
Willy Tarreaucbe6da52018-05-18 17:08:28 +02008044 global.ssl_used_backend = saved_used_backed;
8045 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008046#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008047
8048 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008049}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008050
8051__attribute__((constructor))
8052static void __hlua_init(void)
8053{
8054 char *ptr = NULL;
8055 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8056 hap_register_build_opts(ptr, 1);
8057}