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