blob: f64a56477fb9573ef6c4900a9141badadabc2de0 [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>
Willy Tarreau79e57332018-10-02 16:01:16 +020045#include <proto/http_fetch.h>
Willy Tarreau61c112a2018-10-02 16:43:32 +020046#include <proto/http_rules.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020047#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010048#include <proto/obj_type.h>
Patrick Hemmer268a7072018-05-11 12:52:31 -040049#include <proto/queue.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010050#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010051#include <proto/payload.h>
52#include <proto/proto_http.h>
53#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010054#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020055#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020056#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010057#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010058#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010059#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020060#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010061
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010062/* Lua uses longjmp to perform yield or throwing errors. This
63 * macro is used only for identifying the function that can
64 * not return because a longjmp is executed.
65 * __LJMP marks a prototype of hlua file that can use longjmp.
66 * WILL_LJMP() marks an lua function that will use longjmp.
67 * MAY_LJMP() marks an lua function that may use longjmp.
68 */
69#define __LJMP
Willy Tarreau526aed22018-10-16 17:32:55 +020070#define WILL_LJMP(func) func
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010071#define MAY_LJMP(func) func
72
Thierry FOURNIERbabae282015-09-17 11:36:37 +020073/* This couple of function executes securely some Lua calls outside of
74 * the lua runtime environment. Each Lua call can return a longjmp
75 * if it encounter a memory error.
76 *
77 * Lua documentation extract:
78 *
79 * If an error happens outside any protected environment, Lua calls
80 * a panic function (see lua_atpanic) and then calls abort, thus
81 * exiting the host application. Your panic function can avoid this
82 * exit by never returning (e.g., doing a long jump to your own
83 * recovery point outside Lua).
84 *
85 * The panic function runs as if it were a message handler (see
86 * §2.3); in particular, the error message is at the top of the
87 * stack. However, there is no guarantee about stack space. To push
88 * anything on the stack, the panic function must first check the
89 * available space (see §4.2).
90 *
91 * We must check all the Lua entry point. This includes:
92 * - The include/proto/hlua.h exported functions
93 * - the task wrapper function
94 * - The action wrapper function
95 * - The converters wrapper function
96 * - The sample-fetch wrapper functions
97 *
98 * It is tolerated that the initilisation function returns an abort.
99 * Before each Lua abort, an error message is writed on stderr.
100 *
101 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
102 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
103 * because they must be exists in the program stack when the longjmp
104 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200105 *
106 * Note that the Lua processing is not really thread safe. It provides
107 * heavy system which consists to add our own lock function in the Lua
108 * code and recompile the library. This system will probably not accepted
109 * by maintainers of various distribs.
110 *
111 * Our main excution point of the Lua is the function lua_resume(). A
112 * quick looking on the Lua sources displays a lua_lock() a the start
113 * of function and a lua_unlock() at the end of the function. So I
114 * conclude that the Lua thread safe mode just perform a mutex around
115 * all execution. So I prefer to do this in the HAProxy code, it will be
116 * easier for distro maintainers.
117 *
118 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
119 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
120 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200121 */
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100122__decl_hathreads(HA_SPINLOCK_T hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200123THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200124static int hlua_panic_safe(lua_State *L) { return 0; }
125static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
126
127#define SET_SAFE_LJMP(__L) \
128 ({ \
129 int ret; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100130 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200131 if (setjmp(safe_ljmp_env) != 0) { \
132 lua_atpanic(__L, hlua_panic_safe); \
133 ret = 0; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100134 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200135 } else { \
136 lua_atpanic(__L, hlua_panic_ljmp); \
137 ret = 1; \
138 } \
139 ret; \
140 })
141
142/* If we are the last function catching Lua errors, we
143 * must reset the panic function.
144 */
145#define RESET_SAFE_LJMP(__L) \
146 do { \
147 lua_atpanic(__L, hlua_panic_safe); \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100148 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200149 } while(0)
150
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200151/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200152#define APPLET_DONE 0x01 /* applet processing is done. */
153#define APPLET_100C 0x02 /* 100 continue expected. */
154#define APPLET_HDR_SENT 0x04 /* Response header sent. */
155#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
156#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100157#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200158
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100159/* The main Lua execution context. */
160struct hlua gL;
161
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100162/* This is the memory pool containing struct lua for applets
163 * (including cli).
164 */
Willy Tarreaubafbe012017-11-24 17:34:44 +0100165struct pool_head *pool_head_hlua;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100166
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100167/* Used for Socket connection. */
168static struct proxy socket_proxy;
169static struct server socket_tcp;
170#ifdef USE_OPENSSL
171static struct server socket_ssl;
172#endif
173
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100174/* List head of the function called at the initialisation time. */
175struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
176
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100177/* The following variables contains the reference of the different
178 * Lua classes. These references are useful for identify metadata
179 * associated with an object.
180 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100181static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100182static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100183static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100184static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100185static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100186static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200187static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200188static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200189static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100190
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100191/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200192 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100193 * short timeout. Lua linked with tasks doesn't have a timeout
194 * because a task may remain alive during all the haproxy execution.
195 */
196static unsigned int hlua_timeout_session = 4000; /* session timeout. */
197static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200198static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100199
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100200/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
201 * it is used for preventing infinite loops.
202 *
203 * I test the scheer with an infinite loop containing one incrementation
204 * and one test. I run this loop between 10 seconds, I raise a ceil of
205 * 710M loops from one interrupt each 9000 instructions, so I fix the value
206 * to one interrupt each 10 000 instructions.
207 *
208 * configured | Number of
209 * instructions | loops executed
210 * between two | in milions
211 * forced yields |
212 * ---------------+---------------
213 * 10 | 160
214 * 500 | 670
215 * 1000 | 680
216 * 5000 | 700
217 * 7000 | 700
218 * 8000 | 700
219 * 9000 | 710 <- ceil
220 * 10000 | 710
221 * 100000 | 710
222 * 1000000 | 710
223 *
224 */
225static unsigned int hlua_nb_instruction = 10000;
226
Willy Tarreau32f61e22015-03-18 17:54:59 +0100227/* Descriptor for the memory allocation state. If limit is not null, it will
228 * be enforced on any memory allocation.
229 */
230struct hlua_mem_allocator {
231 size_t allocated;
232 size_t limit;
233};
234
235static struct hlua_mem_allocator hlua_global_allocator;
236
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200237static const char error_500[] =
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200238 "HTTP/1.0 500 Internal Server Error\r\n"
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200239 "Cache-Control: no-cache\r\n"
240 "Connection: close\r\n"
241 "Content-Type: text/html\r\n"
242 "\r\n"
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200243 "<html><body><h1>500 Internal Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200244
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100245/* These functions converts types between HAProxy internal args or
246 * sample and LUA types. Another function permits to check if the
247 * LUA stack contains arguments according with an required ARG_T
248 * format.
249 */
250static int hlua_arg2lua(lua_State *L, const struct arg *arg);
251static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100252__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100253 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100254static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100255static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100256static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
257
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200258__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
259
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200260#define SEND_ERR(__be, __fmt, __args...) \
261 do { \
262 send_log(__be, LOG_ERR, __fmt, ## __args); \
263 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100264 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200265 } while (0)
266
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100267/* Used to check an Lua function type in the stack. It creates and
268 * returns a reference of the function. This function throws an
269 * error if the rgument is not a "function".
270 */
271__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
272{
273 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100274 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100275 WILL_LJMP(luaL_argerror(L, argno, msg));
276 }
277 lua_pushvalue(L, argno);
278 return luaL_ref(L, LUA_REGISTRYINDEX);
279}
280
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200281/* Return the string that is of the top of the stack. */
282const char *hlua_get_top_error_string(lua_State *L)
283{
284 if (lua_gettop(L) < 1)
285 return "unknown error";
286 if (lua_type(L, -1) != LUA_TSTRING)
287 return "unknown error";
288 return lua_tostring(L, -1);
289}
290
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200291__LJMP static const char *hlua_traceback(lua_State *L)
292{
293 lua_Debug ar;
294 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200295 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200296 int filled = 0;
297
298 while (lua_getstack(L, level++, &ar)) {
299
300 /* Add separator */
301 if (filled)
302 chunk_appendf(msg, ", ");
303 filled = 1;
304
305 /* Fill fields:
306 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
307 * 'l': fills in the field currentline;
308 * 'n': fills in the field name and namewhat;
309 * 't': fills in the field istailcall;
310 */
311 lua_getinfo(L, "Slnt", &ar);
312
313 /* Append code localisation */
314 if (ar.currentline > 0)
315 chunk_appendf(msg, "%s:%d ", ar.short_src, ar.currentline);
316 else
317 chunk_appendf(msg, "%s ", ar.short_src);
318
319 /*
320 * Get function name
321 *
322 * if namewhat is no empty, name is defined.
323 * what contains "Lua" for Lua function, "C" for C function,
324 * or "main" for main code.
325 */
326 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
327 chunk_appendf(msg, "%s '%s'", ar.namewhat, ar.name); /* use it */
328
329 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
330 chunk_appendf(msg, "main chunk");
331
332 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
333 chunk_appendf(msg, "C function line %d", ar.linedefined);
334
335 else /* nothing left... */
336 chunk_appendf(msg, "?");
337
338
339 /* Display tailed call */
340 if (ar.istailcall)
341 chunk_appendf(msg, " ...");
342 }
343
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200344 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200345}
346
347
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100348/* This function check the number of arguments available in the
349 * stack. If the number of arguments available is not the same
350 * then <nb> an error is throwed.
351 */
352__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
353{
354 if (lua_gettop(L) == nb)
355 return;
356 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
357}
358
Mark Lakes22154b42018-01-29 14:38:40 -0800359/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100360 * and the line number where the error is encountered.
361 */
362static int hlua_pusherror(lua_State *L, const char *fmt, ...)
363{
364 va_list argp;
365 va_start(argp, fmt);
366 luaL_where(L, 1);
367 lua_pushvfstring(L, fmt, argp);
368 va_end(argp);
369 lua_concat(L, 2);
370 return 1;
371}
372
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100373/* This functions is used with sample fetch and converters. It
374 * converts the HAProxy configuration argument in a lua stack
375 * values.
376 *
377 * It takes an array of "arg", and each entry of the array is
378 * converted and pushed in the LUA stack.
379 */
380static int hlua_arg2lua(lua_State *L, const struct arg *arg)
381{
382 switch (arg->type) {
383 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100384 case ARGT_TIME:
385 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100386 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100387 break;
388
389 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200390 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100391 break;
392
393 case ARGT_IPV4:
394 case ARGT_IPV6:
395 case ARGT_MSK4:
396 case ARGT_MSK6:
397 case ARGT_FE:
398 case ARGT_BE:
399 case ARGT_TAB:
400 case ARGT_SRV:
401 case ARGT_USR:
402 case ARGT_MAP:
403 default:
404 lua_pushnil(L);
405 break;
406 }
407 return 1;
408}
409
410/* This function take one entrie in an LUA stack at the index "ud",
411 * and try to convert it in an HAProxy argument entry. This is useful
412 * with sample fetch wrappers. The input arguments are gived to the
413 * lua wrapper and converted as arg list by thi function.
414 */
415static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
416{
417 switch (lua_type(L, ud)) {
418
419 case LUA_TNUMBER:
420 case LUA_TBOOLEAN:
421 arg->type = ARGT_SINT;
422 arg->data.sint = lua_tointeger(L, ud);
423 break;
424
425 case LUA_TSTRING:
426 arg->type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200427 arg->data.str.area = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100428 break;
429
430 case LUA_TUSERDATA:
431 case LUA_TNIL:
432 case LUA_TTABLE:
433 case LUA_TFUNCTION:
434 case LUA_TTHREAD:
435 case LUA_TLIGHTUSERDATA:
436 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200437 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100438 break;
439 }
440 return 1;
441}
442
443/* the following functions are used to convert a struct sample
444 * in Lua type. This useful to convert the return of the
445 * fetchs or converters.
446 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100447static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100448{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200449 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100450 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100451 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200452 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100453 break;
454
455 case SMP_T_BIN:
456 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200457 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100458 break;
459
460 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200461 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100462 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
463 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
464 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
465 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
466 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
467 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
468 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
469 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
470 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200471 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100472 break;
473 default:
474 lua_pushnil(L);
475 break;
476 }
477 break;
478
479 case SMP_T_IPV4:
480 case SMP_T_IPV6:
481 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200482 if (sample_casts[smp->data.type][SMP_T_STR] &&
483 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200484 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100485 else
486 lua_pushnil(L);
487 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100488 default:
489 lua_pushnil(L);
490 break;
491 }
492 return 1;
493}
494
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100495/* the following functions are used to convert a struct sample
496 * in Lua strings. This is useful to convert the return of the
497 * fetchs or converters.
498 */
499static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
500{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200501 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100502
503 case SMP_T_BIN:
504 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200505 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100506 break;
507
508 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200509 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100510 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
511 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
512 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
513 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
514 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
515 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
516 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
517 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
518 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200519 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100520 break;
521 default:
522 lua_pushstring(L, "");
523 break;
524 }
525 break;
526
527 case SMP_T_SINT:
528 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100529 case SMP_T_IPV4:
530 case SMP_T_IPV6:
531 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200532 if (sample_casts[smp->data.type][SMP_T_STR] &&
533 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200534 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100535 else
536 lua_pushstring(L, "");
537 break;
538 default:
539 lua_pushstring(L, "");
540 break;
541 }
542 return 1;
543}
544
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100545/* the following functions are used to convert an Lua type in a
546 * struct sample. This is useful to provide data from a converter
547 * to the LUA code.
548 */
549static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
550{
551 switch (lua_type(L, ud)) {
552
553 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200554 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200555 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100556 break;
557
558
559 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200560 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200561 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100562 break;
563
564 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200565 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100566 smp->flags |= SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200567 smp->data.u.str.area = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100568 break;
569
570 case LUA_TUSERDATA:
571 case LUA_TNIL:
572 case LUA_TTABLE:
573 case LUA_TFUNCTION:
574 case LUA_TTHREAD:
575 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200576 case LUA_TNONE:
577 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200578 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200579 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100580 break;
581 }
582 return 1;
583}
584
585/* This function check the "argp" builded by another conversion function
586 * is in accord with the expected argp defined by the "mask". The fucntion
587 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100588 *
589 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
590 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100591 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100592__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100593 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100594{
595 int min_arg;
596 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100597 struct proxy *px;
598 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100599
600 idx = 0;
601 min_arg = ARGM(mask);
602 mask >>= ARGM_BITS;
603
604 while (1) {
605
606 /* Check oversize. */
607 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100608 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100609 }
610
611 /* Check for mandatory arguments. */
612 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100613 if (idx < min_arg) {
614
615 /* If miss other argument than the first one, we return an error. */
616 if (idx > 0)
617 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
618
619 /* If first argument have a certain type, some default values
620 * may be used. See the function smp_resolve_args().
621 */
622 switch (mask & ARGT_MASK) {
623
624 case ARGT_FE:
625 if (!(p->cap & PR_CAP_FE))
626 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
627 argp[idx].data.prx = p;
628 argp[idx].type = ARGT_FE;
629 argp[idx+1].type = ARGT_STOP;
630 break;
631
632 case ARGT_BE:
633 if (!(p->cap & PR_CAP_BE))
634 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
635 argp[idx].data.prx = p;
636 argp[idx].type = ARGT_BE;
637 argp[idx+1].type = ARGT_STOP;
638 break;
639
640 case ARGT_TAB:
641 argp[idx].data.prx = p;
642 argp[idx].type = ARGT_TAB;
643 argp[idx+1].type = ARGT_STOP;
644 break;
645
646 default:
647 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
648 break;
649 }
650 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100651 return 0;
652 }
653
654 /* Check for exceed the number of requiered argument. */
655 if ((mask & ARGT_MASK) == ARGT_STOP &&
656 argp[idx].type != ARGT_STOP) {
657 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
658 }
659
660 if ((mask & ARGT_MASK) == ARGT_STOP &&
661 argp[idx].type == ARGT_STOP) {
662 return 0;
663 }
664
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100665 /* Convert some argument types. */
666 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100667 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100668 if (argp[idx].type != ARGT_SINT)
669 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
670 argp[idx].type = ARGT_SINT;
671 break;
672
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100673 case ARGT_TIME:
674 if (argp[idx].type != ARGT_SINT)
675 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200676 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100677 break;
678
679 case ARGT_SIZE:
680 if (argp[idx].type != ARGT_SINT)
681 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200682 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100683 break;
684
685 case ARGT_FE:
686 if (argp[idx].type != ARGT_STR)
687 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200688 memcpy(trash.area, argp[idx].data.str.area,
689 argp[idx].data.str.data);
690 trash.area[argp[idx].data.str.data] = 0;
691 argp[idx].data.prx = proxy_fe_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100692 if (!argp[idx].data.prx)
693 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
694 argp[idx].type = ARGT_FE;
695 break;
696
697 case ARGT_BE:
698 if (argp[idx].type != ARGT_STR)
699 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200700 memcpy(trash.area, argp[idx].data.str.area,
701 argp[idx].data.str.data);
702 trash.area[argp[idx].data.str.data] = 0;
703 argp[idx].data.prx = proxy_be_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100704 if (!argp[idx].data.prx)
705 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
706 argp[idx].type = ARGT_BE;
707 break;
708
709 case ARGT_TAB:
710 if (argp[idx].type != ARGT_STR)
711 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200712 memcpy(trash.area, argp[idx].data.str.area,
713 argp[idx].data.str.data);
714 trash.area[argp[idx].data.str.data] = 0;
715 argp[idx].data.prx = proxy_tbl_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100716 if (!argp[idx].data.prx)
717 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
718 argp[idx].type = ARGT_TAB;
719 break;
720
721 case ARGT_SRV:
722 if (argp[idx].type != ARGT_STR)
723 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200724 memcpy(trash.area, argp[idx].data.str.area,
725 argp[idx].data.str.data);
726 trash.area[argp[idx].data.str.data] = 0;
727 sname = strrchr(trash.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100728 if (sname) {
729 *sname++ = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200730 pname = trash.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200731 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100732 if (!px)
733 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
734 }
735 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200736 sname = trash.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100737 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100738 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100739 argp[idx].data.srv = findserver(px, sname);
740 if (!argp[idx].data.srv)
741 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
742 argp[idx].type = ARGT_SRV;
743 break;
744
745 case ARGT_IPV4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200746 memcpy(trash.area, argp[idx].data.str.area,
747 argp[idx].data.str.data);
748 trash.area[argp[idx].data.str.data] = 0;
749 if (inet_pton(AF_INET, trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100750 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
751 argp[idx].type = ARGT_IPV4;
752 break;
753
754 case ARGT_MSK4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200755 memcpy(trash.area, argp[idx].data.str.area,
756 argp[idx].data.str.data);
757 trash.area[argp[idx].data.str.data] = 0;
758 if (!str2mask(trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100759 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
760 argp[idx].type = ARGT_MSK4;
761 break;
762
763 case ARGT_IPV6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200764 memcpy(trash.area, argp[idx].data.str.area,
765 argp[idx].data.str.data);
766 trash.area[argp[idx].data.str.data] = 0;
767 if (inet_pton(AF_INET6, trash.area, &argp[idx].data.ipv6))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100768 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
769 argp[idx].type = ARGT_IPV6;
770 break;
771
772 case ARGT_MSK6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200773 memcpy(trash.area, argp[idx].data.str.area,
774 argp[idx].data.str.data);
775 trash.area[argp[idx].data.str.data] = 0;
776 if (!str2mask6(trash.area, &argp[idx].data.ipv6))
Tim Duesterhusb814da62018-01-25 16:24:50 +0100777 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 mask"));
778 argp[idx].type = ARGT_MSK6;
779 break;
780
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100781 case ARGT_MAP:
782 case ARGT_REG:
783 case ARGT_USR:
784 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100785 break;
786 }
787
788 /* Check for type of argument. */
789 if ((mask & ARGT_MASK) != argp[idx].type) {
790 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
791 arg_type_names[(mask & ARGT_MASK)],
792 arg_type_names[argp[idx].type & ARGT_MASK]);
793 WILL_LJMP(luaL_argerror(L, first + idx, msg));
794 }
795
796 /* Next argument. */
797 mask >>= ARGT_BITS;
798 idx++;
799 }
800}
801
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100802/*
803 * The following functions are used to make correspondance between the the
804 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100805 *
806 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100807 * - hlua_sethlua : create the association between hlua context and lua_state.
808 */
809static inline struct hlua *hlua_gethlua(lua_State *L)
810{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100811 struct hlua **hlua = lua_getextraspace(L);
812 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100813}
814static inline void hlua_sethlua(struct hlua *hlua)
815{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100816 struct hlua **hlua_store = lua_getextraspace(hlua->T);
817 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100818}
819
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100820/* This function is used to send logs. It try to send on screen (stderr)
821 * and on the default syslog server.
822 */
823static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
824{
825 struct tm tm;
826 char *p;
827
828 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200829 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100830 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200831 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200832 /* Break the message if exceed the buffer size. */
833 *(p-4) = ' ';
834 *(p-3) = '.';
835 *(p-2) = '.';
836 *(p-1) = '.';
837 break;
838 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100839 if (isprint(*msg))
840 *p = *msg;
841 else
842 *p = '.';
843 }
844 *p = '\0';
845
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200846 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100847 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200848 get_localtime(date.tv_sec, &tm);
849 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100850 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200851 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100852 fflush(stderr);
853 }
854}
855
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100856/* This function just ensure that the yield will be always
857 * returned with a timeout and permit to set some flags
858 */
859__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100860 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100861{
862 struct hlua *hlua = hlua_gethlua(L);
863
864 /* Set the wake timeout. If timeout is required, we set
865 * the expiration time.
866 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200867 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100868
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100869 hlua->flags |= flags;
870
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100871 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +0200872 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100873}
874
Willy Tarreau87b09662015-04-03 00:22:06 +0200875/* This function initialises the Lua environment stored in the stream.
876 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100877 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200878 *
879 * This function is particular. it initialises a new Lua thread. If the
880 * initialisation fails (example: out of memory error), the lua function
881 * throws an error (longjmp).
882 *
883 * This function manipulates two Lua stack: the main and the thread. Only
884 * the main stack can fail. The thread is not manipulated. This function
885 * MUST NOT manipulate the created thread stack state, because is not
886 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100887 */
888int hlua_ctx_init(struct hlua *lua, struct task *task)
889{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200890 if (!SET_SAFE_LJMP(gL.T)) {
891 lua->Tref = LUA_REFNIL;
892 return 0;
893 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100894 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100895 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100896 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100897 lua->T = lua_newthread(gL.T);
898 if (!lua->T) {
899 lua->Tref = LUA_REFNIL;
Thierry FOURNIER0a976202017-07-12 11:18:00 +0200900 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100901 return 0;
902 }
903 hlua_sethlua(lua);
904 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
905 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200906 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100907 return 1;
908}
909
Willy Tarreau87b09662015-04-03 00:22:06 +0200910/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100911 * is destroyed. The destroy also the memory context. The struct "lua"
912 * is not freed.
913 */
914void hlua_ctx_destroy(struct hlua *lua)
915{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100916 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100917 return;
918
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100919 if (!lua->T)
920 goto end;
921
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100922 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +0200923 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100924
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200925 if (!SET_SAFE_LJMP(lua->T))
926 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100927 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200928 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200929
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200930 if (!SET_SAFE_LJMP(gL.T))
931 return;
932 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
933 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200934 /* Forces a garbage collecting process. If the Lua program is finished
935 * without error, we run the GC on the thread pointer. Its freed all
936 * the unused memory.
937 * If the thread is finnish with an error or is currently yielded,
938 * it seems that the GC applied on the thread doesn't clean anything,
939 * so e run the GC on the main thread.
940 * NOTE: maybe this action locks all the Lua threads untiml the en of
941 * the garbage collection.
942 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200943 if (lua->flags & HLUA_MUST_GC) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200944 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200945 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200946 lua_gc(gL.T, LUA_GCCOLLECT, 0);
947 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200948 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200949
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200950 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100951
952end:
Willy Tarreaubafbe012017-11-24 17:34:44 +0100953 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100954}
955
956/* This function is used to restore the Lua context when a coroutine
957 * fails. This function copy the common memory between old coroutine
958 * and the new coroutine. The old coroutine is destroyed, and its
959 * replaced by the new coroutine.
960 * If the flag "keep_msg" is set, the last entry of the old is assumed
961 * as string error message and it is copied in the new stack.
962 */
963static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
964{
965 lua_State *T;
966 int new_ref;
967
968 /* Renew the main LUA stack doesn't have sense. */
969 if (lua == &gL)
970 return 0;
971
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100972 /* New Lua coroutine. */
973 T = lua_newthread(gL.T);
974 if (!T)
975 return 0;
976
977 /* Copy last error message. */
978 if (keep_msg)
979 lua_xmove(lua->T, T, 1);
980
981 /* Copy data between the coroutines. */
982 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
983 lua_xmove(lua->T, T, 1);
984 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
985
986 /* Destroy old data. */
987 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
988
989 /* The thread is garbage collected by Lua. */
990 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
991
992 /* Fill the struct with the new coroutine values. */
993 lua->Mref = new_ref;
994 lua->T = T;
995 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
996
997 /* Set context. */
998 hlua_sethlua(lua);
999
1000 return 1;
1001}
1002
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001003void hlua_hook(lua_State *L, lua_Debug *ar)
1004{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001005 struct hlua *hlua = hlua_gethlua(L);
1006
1007 /* Lua cannot yield when its returning from a function,
1008 * so, we can fix the interrupt hook to 1 instruction,
1009 * expecting that the function is finnished.
1010 */
1011 if (lua_gethookmask(L) & LUA_MASKRET) {
1012 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1013 return;
1014 }
1015
1016 /* restore the interrupt condition. */
1017 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1018
1019 /* If we interrupt the Lua processing in yieldable state, we yield.
1020 * If the state is not yieldable, trying yield causes an error.
1021 */
1022 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001023 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001024
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001025 /* If we cannot yield, update the clock and check the timeout. */
1026 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001027 hlua->run_time += now_ms - hlua->start_time;
1028 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001029 lua_pushfstring(L, "execution timeout");
1030 WILL_LJMP(lua_error(L));
1031 }
1032
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001033 /* Update the start time. */
1034 hlua->start_time = now_ms;
1035
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001036 /* Try to interrupt the process at the end of the current
1037 * unyieldable function.
1038 */
1039 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001040}
1041
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001042/* This function start or resumes the Lua stack execution. If the flag
1043 * "yield_allowed" if no set and the LUA stack execution returns a yield
1044 * The function return an error.
1045 *
1046 * The function can returns 4 values:
1047 * - HLUA_E_OK : The execution is terminated without any errors.
1048 * - HLUA_E_AGAIN : The execution must continue at the next associated
1049 * task wakeup.
1050 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
1051 * the top of the stack.
1052 * - HLUA_E_ERR : An error has occured without error message.
1053 *
1054 * If an error occured, the stack is renewed and it is ready to run new
1055 * LUA code.
1056 */
1057static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1058{
1059 int ret;
1060 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001061 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001062
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001063 /* Initialise run time counter. */
1064 if (!HLUA_IS_RUNNING(lua))
1065 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001066
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001067 /* Lock the whole Lua execution. This lock must be before the
1068 * label "resume_execution".
1069 */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001070 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001071
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001072resume_execution:
1073
1074 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1075 * instructions. it is used for preventing infinite loops.
1076 */
1077 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1078
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001079 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001080 HLUA_SET_RUN(lua);
1081 HLUA_CLR_CTRLYIELD(lua);
1082 HLUA_CLR_WAKERESWR(lua);
1083 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001084
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001085 /* Update the start time. */
1086 lua->start_time = now_ms;
1087
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001088 /* Call the function. */
1089 ret = lua_resume(lua->T, gL.T, lua->nargs);
1090 switch (ret) {
1091
1092 case LUA_OK:
1093 ret = HLUA_E_OK;
1094 break;
1095
1096 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001097 /* Check if the execution timeout is expired. It it is the case, we
1098 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001099 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001100 tv_update_date(0, 1);
1101 lua->run_time += now_ms - lua->start_time;
1102 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001103 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001104 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001105 break;
1106 }
1107 /* Process the forced yield. if the general yield is not allowed or
1108 * if no task were associated this the current Lua execution
1109 * coroutine, we resume the execution. Else we want to return in the
1110 * scheduler and we want to be waked up again, to continue the
1111 * current Lua execution. So we schedule our own task.
1112 */
1113 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001114 if (!yield_allowed || !lua->task)
1115 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001116 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001117 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001118 if (!yield_allowed) {
1119 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001120 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001121 break;
1122 }
1123 ret = HLUA_E_AGAIN;
1124 break;
1125
1126 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001127
1128 /* Special exit case. The traditionnal exit is returned as an error
1129 * because the errors ares the only one mean to return immediately
1130 * from and lua execution.
1131 */
1132 if (lua->flags & HLUA_EXIT) {
1133 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001134 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001135 break;
1136 }
1137
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001138 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001139 if (!lua_checkstack(lua->T, 1)) {
1140 ret = HLUA_E_ERR;
1141 break;
1142 }
1143 msg = lua_tostring(lua->T, -1);
1144 lua_settop(lua->T, 0); /* Empty the stack. */
1145 lua_pop(lua->T, 1);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001146 trace = hlua_traceback(lua->T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001147 if (msg)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001148 lua_pushfstring(lua->T, "runtime error: %s from %s", msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001149 else
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001150 lua_pushfstring(lua->T, "unknown runtime error from %s", trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001151 ret = HLUA_E_ERRMSG;
1152 break;
1153
1154 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001155 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001156 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001157 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001158 break;
1159
1160 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001161 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001162 if (!lua_checkstack(lua->T, 1)) {
1163 ret = HLUA_E_ERR;
1164 break;
1165 }
1166 msg = lua_tostring(lua->T, -1);
1167 lua_settop(lua->T, 0); /* Empty the stack. */
1168 lua_pop(lua->T, 1);
1169 if (msg)
1170 lua_pushfstring(lua->T, "message handler error: %s", msg);
1171 else
1172 lua_pushfstring(lua->T, "message handler error");
1173 ret = HLUA_E_ERRMSG;
1174 break;
1175
1176 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001177 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001178 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001179 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001180 break;
1181 }
1182
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001183 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001184 if (lua->flags & HLUA_MUST_GC &&
1185 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001186 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1187
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001188 switch (ret) {
1189 case HLUA_E_AGAIN:
1190 break;
1191
1192 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001193 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001194 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001195 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001196 break;
1197
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001198 case HLUA_E_ETMOUT:
1199 case HLUA_E_NOMEM:
1200 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001201 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001202 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001203 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001204 hlua_ctx_renew(lua, 0);
1205 break;
1206
1207 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001208 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001209 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001210 break;
1211 }
1212
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001213 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001214 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001215
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001216 return ret;
1217}
1218
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001219/* This function exit the current code. */
1220__LJMP static int hlua_done(lua_State *L)
1221{
1222 struct hlua *hlua = hlua_gethlua(L);
1223
1224 hlua->flags |= HLUA_EXIT;
1225 WILL_LJMP(lua_error(L));
1226
1227 return 0;
1228}
1229
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001230/* This function is an LUA binding. It provides a function
1231 * for deleting ACL from a referenced ACL file.
1232 */
1233__LJMP static int hlua_del_acl(lua_State *L)
1234{
1235 const char *name;
1236 const char *key;
1237 struct pat_ref *ref;
1238
1239 MAY_LJMP(check_args(L, 2, "del_acl"));
1240
1241 name = MAY_LJMP(luaL_checkstring(L, 1));
1242 key = MAY_LJMP(luaL_checkstring(L, 2));
1243
1244 ref = pat_ref_lookup(name);
1245 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001246 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001247
1248 pat_ref_delete(ref, key);
1249 return 0;
1250}
1251
1252/* This function is an LUA binding. It provides a function
1253 * for deleting map entry from a referenced map file.
1254 */
1255static int hlua_del_map(lua_State *L)
1256{
1257 const char *name;
1258 const char *key;
1259 struct pat_ref *ref;
1260
1261 MAY_LJMP(check_args(L, 2, "del_map"));
1262
1263 name = MAY_LJMP(luaL_checkstring(L, 1));
1264 key = MAY_LJMP(luaL_checkstring(L, 2));
1265
1266 ref = pat_ref_lookup(name);
1267 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001268 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001269
1270 pat_ref_delete(ref, key);
1271 return 0;
1272}
1273
1274/* This function is an LUA binding. It provides a function
1275 * for adding ACL pattern from a referenced ACL file.
1276 */
1277static int hlua_add_acl(lua_State *L)
1278{
1279 const char *name;
1280 const char *key;
1281 struct pat_ref *ref;
1282
1283 MAY_LJMP(check_args(L, 2, "add_acl"));
1284
1285 name = MAY_LJMP(luaL_checkstring(L, 1));
1286 key = MAY_LJMP(luaL_checkstring(L, 2));
1287
1288 ref = pat_ref_lookup(name);
1289 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001290 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001291
1292 if (pat_ref_find_elt(ref, key) == NULL)
1293 pat_ref_add(ref, key, NULL, NULL);
1294 return 0;
1295}
1296
1297/* This function is an LUA binding. It provides a function
1298 * for setting map pattern and sample from a referenced map
1299 * file.
1300 */
1301static int hlua_set_map(lua_State *L)
1302{
1303 const char *name;
1304 const char *key;
1305 const char *value;
1306 struct pat_ref *ref;
1307
1308 MAY_LJMP(check_args(L, 3, "set_map"));
1309
1310 name = MAY_LJMP(luaL_checkstring(L, 1));
1311 key = MAY_LJMP(luaL_checkstring(L, 2));
1312 value = MAY_LJMP(luaL_checkstring(L, 3));
1313
1314 ref = pat_ref_lookup(name);
1315 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001316 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001317
1318 if (pat_ref_find_elt(ref, key) != NULL)
1319 pat_ref_set(ref, key, value, NULL);
1320 else
1321 pat_ref_add(ref, key, value, NULL);
1322 return 0;
1323}
1324
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001325/* A class is a lot of memory that contain data. This data can be a table,
1326 * an integer or user data. This data is associated with a metatable. This
1327 * metatable have an original version registred in the global context with
1328 * the name of the object (_G[<name>] = <metable> ).
1329 *
1330 * A metable is a table that modify the standard behavior of a standard
1331 * access to the associated data. The entries of this new metatable are
1332 * defined as is:
1333 *
1334 * http://lua-users.org/wiki/MetatableEvents
1335 *
1336 * __index
1337 *
1338 * we access an absent field in a table, the result is nil. This is
1339 * true, but it is not the whole truth. Actually, such access triggers
1340 * the interpreter to look for an __index metamethod: If there is no
1341 * such method, as usually happens, then the access results in nil;
1342 * otherwise, the metamethod will provide the result.
1343 *
1344 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1345 * the key does not appear in the table, but the metatable has an __index
1346 * property:
1347 *
1348 * - if the value is a function, the function is called, passing in the
1349 * table and the key; the return value of that function is returned as
1350 * the result.
1351 *
1352 * - if the value is another table, the value of the key in that table is
1353 * asked for and returned (and if it doesn't exist in that table, but that
1354 * table's metatable has an __index property, then it continues on up)
1355 *
1356 * - Use "rawget(myTable,key)" to skip this metamethod.
1357 *
1358 * http://www.lua.org/pil/13.4.1.html
1359 *
1360 * __newindex
1361 *
1362 * Like __index, but control property assignment.
1363 *
1364 * __mode - Control weak references. A string value with one or both
1365 * of the characters 'k' and 'v' which specifies that the the
1366 * keys and/or values in the table are weak references.
1367 *
1368 * __call - Treat a table like a function. When a table is followed by
1369 * parenthesis such as "myTable( 'foo' )" and the metatable has
1370 * a __call key pointing to a function, that function is invoked
1371 * (passing any specified arguments) and the return value is
1372 * returned.
1373 *
1374 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1375 * called, if the metatable for myTable has a __metatable
1376 * key, the value of that key is returned instead of the
1377 * actual metatable.
1378 *
1379 * __tostring - Control string representation. When the builtin
1380 * "tostring( myTable )" function is called, if the metatable
1381 * for myTable has a __tostring property set to a function,
1382 * that function is invoked (passing myTable to it) and the
1383 * return value is used as the string representation.
1384 *
1385 * __len - Control table length. When the table length is requested using
1386 * the length operator ( '#' ), if the metatable for myTable has
1387 * a __len key pointing to a function, that function is invoked
1388 * (passing myTable to it) and the return value used as the value
1389 * of "#myTable".
1390 *
1391 * __gc - Userdata finalizer code. When userdata is set to be garbage
1392 * collected, if the metatable has a __gc field pointing to a
1393 * function, that function is first invoked, passing the userdata
1394 * to it. The __gc metamethod is not called for tables.
1395 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1396 *
1397 * Special metamethods for redefining standard operators:
1398 * http://www.lua.org/pil/13.1.html
1399 *
1400 * __add "+"
1401 * __sub "-"
1402 * __mul "*"
1403 * __div "/"
1404 * __unm "!"
1405 * __pow "^"
1406 * __concat ".."
1407 *
1408 * Special methods for redfining standar relations
1409 * http://www.lua.org/pil/13.2.html
1410 *
1411 * __eq "=="
1412 * __lt "<"
1413 * __le "<="
1414 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001415
1416/*
1417 *
1418 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001419 * Class Map
1420 *
1421 *
1422 */
1423
1424/* Returns a struct hlua_map if the stack entry "ud" is
1425 * a class session, otherwise it throws an error.
1426 */
1427__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1428{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001429 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001430}
1431
1432/* This function is the map constructor. It don't need
1433 * the class Map object. It creates and return a new Map
1434 * object. It must be called only during "body" or "init"
1435 * context because it process some filesystem accesses.
1436 */
1437__LJMP static int hlua_map_new(struct lua_State *L)
1438{
1439 const char *fn;
1440 int match = PAT_MATCH_STR;
1441 struct sample_conv conv;
1442 const char *file = "";
1443 int line = 0;
1444 lua_Debug ar;
1445 char *err = NULL;
1446 struct arg args[2];
1447
1448 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1449 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1450
1451 fn = MAY_LJMP(luaL_checkstring(L, 1));
1452
1453 if (lua_gettop(L) >= 2) {
1454 match = MAY_LJMP(luaL_checkinteger(L, 2));
1455 if (match < 0 || match >= PAT_MATCH_NUM)
1456 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1457 }
1458
1459 /* Get Lua filename and line number. */
1460 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1461 lua_getinfo(L, "Sl", &ar); /* get info about it */
1462 if (ar.currentline > 0) { /* is there info? */
1463 file = ar.short_src;
1464 line = ar.currentline;
1465 }
1466 }
1467
1468 /* fill fake sample_conv struct. */
1469 conv.kw = ""; /* unused. */
1470 conv.process = NULL; /* unused. */
1471 conv.arg_mask = 0; /* unused. */
1472 conv.val_args = NULL; /* unused. */
1473 conv.out_type = SMP_T_STR;
1474 conv.private = (void *)(long)match;
1475 switch (match) {
1476 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1477 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1478 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1479 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1480 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1481 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1482 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001483 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001484 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1485 default:
1486 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1487 }
1488
1489 /* fill fake args. */
1490 args[0].type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001491 args[0].data.str.area = (char *)fn;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001492 args[1].type = ARGT_STOP;
1493
1494 /* load the map. */
1495 if (!sample_load_map(args, &conv, file, line, &err)) {
1496 /* error case: we cant use luaL_error because we must
1497 * free the err variable.
1498 */
1499 luaL_where(L, 1);
1500 lua_pushfstring(L, "'new': %s.", err);
1501 lua_concat(L, 2);
1502 free(err);
1503 WILL_LJMP(lua_error(L));
1504 }
1505
1506 /* create the lua object. */
1507 lua_newtable(L);
1508 lua_pushlightuserdata(L, args[0].data.map);
1509 lua_rawseti(L, -2, 0);
1510
1511 /* Pop a class Map metatable and affect it to the userdata. */
1512 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1513 lua_setmetatable(L, -2);
1514
1515
1516 return 1;
1517}
1518
1519__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1520{
1521 struct map_descriptor *desc;
1522 struct pattern *pat;
1523 struct sample smp;
1524
1525 MAY_LJMP(check_args(L, 2, "lookup"));
1526 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001527 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001528 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001529 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001530 }
1531 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001532 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001533 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001534 smp.data.u.str.area = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.data));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001535 }
1536
1537 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001538 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001539 if (str)
1540 lua_pushstring(L, "");
1541 else
1542 lua_pushnil(L);
1543 return 1;
1544 }
1545
1546 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001547 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001548 return 1;
1549}
1550
1551__LJMP static int hlua_map_lookup(struct lua_State *L)
1552{
1553 return _hlua_map_lookup(L, 0);
1554}
1555
1556__LJMP static int hlua_map_slookup(struct lua_State *L)
1557{
1558 return _hlua_map_lookup(L, 1);
1559}
1560
1561/*
1562 *
1563 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001564 * Class Socket
1565 *
1566 *
1567 */
1568
1569__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1570{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001571 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001572}
1573
1574/* This function is the handler called for each I/O on the established
1575 * connection. It is used for notify space avalaible to send or data
1576 * received.
1577 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001578static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001579{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001580 struct stream_interface *si = appctx->owner;
Olivier Houchard9aaf7782017-09-13 18:30:23 +02001581 struct connection *c = cs_conn(objt_cs(si_opposite(si)->end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001582
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001583 if (appctx->ctx.hlua_cosocket.die) {
1584 si_shutw(si);
1585 si_shutr(si);
1586 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001587 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1588 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001589 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1590 }
1591
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001592 /* If the connection object is not avalaible, close all the
1593 * streams and wakeup everithing waiting for.
1594 */
1595 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001596 si_shutw(si);
1597 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001598 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001599 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1600 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001601 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001602 }
1603
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001604 /* If we cant write, wakeup the pending write signals. */
1605 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001606 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001607
1608 /* If we cant read, wakeup the pending read signals. */
1609 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001610 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001611
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001612 /* if the connection is not estabkished, inform the stream that we want
1613 * to be notified whenever the connection completes.
1614 */
1615 if (!(c->flags & CO_FL_CONNECTED)) {
1616 si_applet_cant_get(si);
1617 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001618 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001619 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001620
1621 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001622 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001623
1624 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001625 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001626 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001627
1628 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001629 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001630 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001631
1632 /* Some data were injected in the buffer, notify the stream
1633 * interface.
1634 */
1635 if (!channel_is_empty(si_ic(si)))
1636 stream_int_update(si);
1637
1638 /* If write notifications are registered, we considers we want
1639 * to write, so we set the flag cant put
1640 */
1641 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
1642 si_applet_cant_put(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001643}
1644
Willy Tarreau87b09662015-04-03 00:22:06 +02001645/* This function is called when the "struct stream" is destroyed.
1646 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001647 * Wake all the pending signals.
1648 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001649static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001650{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001651 struct xref *peer;
1652
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001653 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001654 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1655 if (peer)
1656 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001657
1658 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001659 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1660 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001661}
1662
1663/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001664 * uses this object. If the stream does not exists, just quit.
1665 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001666 * pending signal can rest in the read and write lists. destroy
1667 * it.
1668 */
1669__LJMP static int hlua_socket_gc(lua_State *L)
1670{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001671 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001672 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001673 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001674
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001675 MAY_LJMP(check_args(L, 1, "__gc"));
1676
1677 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001678 peer = xref_get_peer_and_lock(&socket->xref);
1679 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001680 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001681 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001682
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001683 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001684 appctx->ctx.hlua_cosocket.die = 1;
1685 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001686
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001687 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001688 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001689 return 0;
1690}
1691
1692/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001693 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001694 */
sada05ed3302018-05-11 11:48:18 -07001695__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001696{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001697 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001698 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001699 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001700
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001701 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001702
1703 /* Check if we run on the same thread than the xreator thread.
1704 * We cannot access to the socket if the thread is different.
1705 */
1706 if (socket->tid != tid)
1707 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1708
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001709 peer = xref_get_peer_and_lock(&socket->xref);
1710 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001711 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001712 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001713
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001714 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001715 appctx->ctx.hlua_cosocket.die = 1;
1716 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001717
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001718 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001719 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001720 return 0;
1721}
1722
sada05ed3302018-05-11 11:48:18 -07001723/* The close function calls close_helper.
1724 */
1725__LJMP static int hlua_socket_close(lua_State *L)
1726{
1727 MAY_LJMP(check_args(L, 1, "close"));
1728 return hlua_socket_close_helper(L);
1729}
1730
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001731/* This Lua function assumes that the stack contain three parameters.
1732 * 1 - USERDATA containing a struct socket
1733 * 2 - INTEGER with values of the macro defined below
1734 * If the integer is -1, we must read at most one line.
1735 * If the integer is -2, we ust read all the data until the
1736 * end of the stream.
1737 * If the integer is positive value, we must read a number of
1738 * bytes corresponding to this value.
1739 */
1740#define HLSR_READ_LINE (-1)
1741#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001742__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001743{
1744 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1745 int wanted = lua_tointeger(L, 2);
1746 struct hlua *hlua = hlua_gethlua(L);
1747 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001748 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001749 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02001750 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001751 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02001752 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001753 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001754 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001755 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001756 struct stream_interface *si;
1757 struct stream *s;
1758 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001759 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001760
1761 /* Check if this lua stack is schedulable. */
1762 if (!hlua || !hlua->task)
1763 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1764 "'frontend', 'backend' or 'task'"));
1765
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001766 /* Check if we run on the same thread than the xreator thread.
1767 * We cannot access to the socket if the thread is different.
1768 */
1769 if (socket->tid != tid)
1770 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1771
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001772 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001773 peer = xref_get_peer_and_lock(&socket->xref);
1774 if (!peer)
1775 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001776 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1777 si = appctx->owner;
1778 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001779
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001780 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001781 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001782 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001783 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001784 if (nblk < 0) /* Connection close. */
1785 goto connection_closed;
1786 if (nblk == 0) /* No data avalaible. */
1787 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001788
1789 /* remove final \r\n. */
1790 if (nblk == 1) {
1791 if (blk1[len1-1] == '\n') {
1792 len1--;
1793 skip_at_end++;
1794 if (blk1[len1-1] == '\r') {
1795 len1--;
1796 skip_at_end++;
1797 }
1798 }
1799 }
1800 else {
1801 if (blk2[len2-1] == '\n') {
1802 len2--;
1803 skip_at_end++;
1804 if (blk2[len2-1] == '\r') {
1805 len2--;
1806 skip_at_end++;
1807 }
1808 }
1809 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001810 }
1811
1812 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001813 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001814 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001815 if (nblk < 0) /* Connection close. */
1816 goto connection_closed;
1817 if (nblk == 0) /* No data avalaible. */
1818 goto connection_empty;
1819 }
1820
1821 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001822 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001823 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001824 if (nblk < 0) /* Connection close. */
1825 goto connection_closed;
1826 if (nblk == 0) /* No data avalaible. */
1827 goto connection_empty;
1828
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001829 missing_bytes = wanted - socket->b.n;
1830 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001831 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001832 len1 = missing_bytes;
1833 } if (nblk == 2 && len1 + len2 > missing_bytes)
1834 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001835 }
1836
1837 len = len1;
1838
1839 luaL_addlstring(&socket->b, blk1, len1);
1840 if (nblk == 2) {
1841 len += len2;
1842 luaL_addlstring(&socket->b, blk2, len2);
1843 }
1844
1845 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001846 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001847
1848 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02001849 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001850
1851 /* If the pattern reclaim to read all the data
1852 * in the connection, got out.
1853 */
1854 if (wanted == HLSR_READ_ALL)
1855 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001856 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001857 goto connection_empty;
1858
1859 /* Return result. */
1860 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001861 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001862 return 1;
1863
1864connection_closed:
1865
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001866 xref_unlock(&socket->xref, peer);
1867
1868no_peer:
1869
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001870 /* If the buffer containds data. */
1871 if (socket->b.n > 0) {
1872 luaL_pushresult(&socket->b);
1873 return 1;
1874 }
1875 lua_pushnil(L);
1876 lua_pushstring(L, "connection closed.");
1877 return 2;
1878
1879connection_empty:
1880
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001881 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1882 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001883 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001884 }
1885 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02001886 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001887 return 0;
1888}
1889
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001890/* This Lua function gets two parameters. The first one can be string
1891 * or a number. If the string is "*l", the user requires one line. If
1892 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001893 * If the value is a number, the user require a number of bytes equal
1894 * to the value. The default value is "*l" (a line).
1895 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001896 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001897 * integer takes this values:
1898 * -1 : read a line
1899 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001900 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001901 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001902 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001903 * concatenated with the read data.
1904 */
1905__LJMP static int hlua_socket_receive(struct lua_State *L)
1906{
1907 int wanted = HLSR_READ_LINE;
1908 const char *pattern;
1909 int type;
1910 char *error;
1911 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001912 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001913
1914 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1915 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1916
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001917 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001918
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001919 /* Check if we run on the same thread than the xreator thread.
1920 * We cannot access to the socket if the thread is different.
1921 */
1922 if (socket->tid != tid)
1923 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1924
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001925 /* check for pattern. */
1926 if (lua_gettop(L) >= 2) {
1927 type = lua_type(L, 2);
1928 if (type == LUA_TSTRING) {
1929 pattern = lua_tostring(L, 2);
1930 if (strcmp(pattern, "*a") == 0)
1931 wanted = HLSR_READ_ALL;
1932 else if (strcmp(pattern, "*l") == 0)
1933 wanted = HLSR_READ_LINE;
1934 else {
1935 wanted = strtoll(pattern, &error, 10);
1936 if (*error != '\0')
1937 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1938 }
1939 }
1940 else if (type == LUA_TNUMBER) {
1941 wanted = lua_tointeger(L, 2);
1942 if (wanted < 0)
1943 WILL_LJMP(luaL_error(L, "Unsupported size."));
1944 }
1945 }
1946
1947 /* Set pattern. */
1948 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01001949
1950 /* Check if we would replace the top by itself. */
1951 if (lua_gettop(L) != 2)
1952 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001953
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001954 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001955 luaL_buffinit(L, &socket->b);
1956
1957 /* Check prefix. */
1958 if (lua_gettop(L) >= 3) {
1959 if (lua_type(L, 3) != LUA_TSTRING)
1960 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1961 pattern = lua_tolstring(L, 3, &len);
1962 luaL_addlstring(&socket->b, pattern, len);
1963 }
1964
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001965 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001966}
1967
1968/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08001969 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001970 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001971static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001972{
1973 struct hlua_socket *socket;
1974 struct hlua *hlua = hlua_gethlua(L);
1975 struct appctx *appctx;
1976 size_t buf_len;
1977 const char *buf;
1978 int len;
1979 int send_len;
1980 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001981 struct xref *peer;
1982 struct stream_interface *si;
1983 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001984
1985 /* Check if this lua stack is schedulable. */
1986 if (!hlua || !hlua->task)
1987 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1988 "'frontend', 'backend' or 'task'"));
1989
1990 /* Get object */
1991 socket = MAY_LJMP(hlua_checksocket(L, 1));
1992 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001993 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001994
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001995 /* Check if we run on the same thread than the xreator thread.
1996 * We cannot access to the socket if the thread is different.
1997 */
1998 if (socket->tid != tid)
1999 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2000
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002001 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002002 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002003 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002004 lua_pushinteger(L, -1);
2005 return 1;
2006 }
2007 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2008 si = appctx->owner;
2009 s = si_strm(si);
2010
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002011 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002012 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002013 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002014 lua_pushinteger(L, -1);
2015 return 1;
2016 }
2017
2018 /* Update the input buffer data. */
2019 buf += sent;
2020 send_len = buf_len - sent;
2021
2022 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002023 if (sent >= buf_len) {
2024 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002025 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002026 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002027
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002028 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2029 * the request buffer if its not required.
2030 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002031 if (s->req.buf.size == 0) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002032 if (!channel_alloc_buffer(&s->req, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002033 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002034 }
2035
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002036 /* Check for avalaible space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002037 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002038 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002039 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002040 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002041
2042 /* send data */
2043 if (len < send_len)
2044 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002045 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002046
2047 /* "Not enough space" (-1), "Buffer too little to contain
2048 * the data" (-2) are not expected because the available length
2049 * is tested.
2050 * Other unknown error are also not expected.
2051 */
2052 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002053 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002054 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002055
sada05ed3302018-05-11 11:48:18 -07002056 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002057 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002058 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002059 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002060 return 1;
2061 }
2062
2063 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002064 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002065
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002066 s->req.rex = TICK_ETERNITY;
2067 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002068
2069 /* Update length sent. */
2070 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002071 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002072
2073 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002074 if (sent + len >= buf_len) {
2075 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002076 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002077 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002078
2079hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002080 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2081 xref_unlock(&socket->xref, peer);
2082 WILL_LJMP(luaL_error(L, "out of memory"));
2083 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002084 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002085 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002086 return 0;
2087}
2088
2089/* This function initiate the send of data. It just check the input
2090 * parameters and push an integer in the Lua stack that contain the
2091 * amount of data writed in the buffer. This is used by the function
2092 * "hlua_socket_write_yield" that can yield.
2093 *
2094 * The Lua function gets between 3 and 4 parameters. The first one is
2095 * the associated object. The second is a string buffer. The third is
2096 * a facultative integer that represents where is the buffer position
2097 * of the start of the data that can send. The first byte is the
2098 * position "1". The default value is "1". The fourth argument is a
2099 * facultative integer that represents where is the buffer position
2100 * of the end of the data that can send. The default is the last byte.
2101 */
2102static int hlua_socket_send(struct lua_State *L)
2103{
2104 int i;
2105 int j;
2106 const char *buf;
2107 size_t buf_len;
2108
2109 /* Check number of arguments. */
2110 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2111 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2112
2113 /* Get the string. */
2114 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2115
2116 /* Get and check j. */
2117 if (lua_gettop(L) == 4) {
2118 j = MAY_LJMP(luaL_checkinteger(L, 4));
2119 if (j < 0)
2120 j = buf_len + j + 1;
2121 if (j > buf_len)
2122 j = buf_len + 1;
2123 lua_pop(L, 1);
2124 }
2125 else
2126 j = buf_len;
2127
2128 /* Get and check i. */
2129 if (lua_gettop(L) == 3) {
2130 i = MAY_LJMP(luaL_checkinteger(L, 3));
2131 if (i < 0)
2132 i = buf_len + i + 1;
2133 if (i > buf_len)
2134 i = buf_len + 1;
2135 lua_pop(L, 1);
2136 } else
2137 i = 1;
2138
2139 /* Check bth i and j. */
2140 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002141 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002142 return 1;
2143 }
2144 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002145 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002146 return 1;
2147 }
2148 if (i == 0)
2149 i = 1;
2150 if (j == 0)
2151 j = 1;
2152
2153 /* Pop the string. */
2154 lua_pop(L, 1);
2155
2156 /* Update the buffer length. */
2157 buf += i - 1;
2158 buf_len = j - i + 1;
2159 lua_pushlstring(L, buf, buf_len);
2160
2161 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002162 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002163
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002164 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002165}
2166
Willy Tarreau22b0a682015-06-17 19:43:49 +02002167#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002168__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2169{
2170 static char buffer[SOCKET_INFO_MAX_LEN];
2171 int ret;
2172 int len;
2173 char *p;
2174
2175 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2176 if (ret <= 0) {
2177 lua_pushnil(L);
2178 return 1;
2179 }
2180
2181 if (ret == AF_UNIX) {
2182 lua_pushstring(L, buffer+1);
2183 return 1;
2184 }
2185 else if (ret == AF_INET6) {
2186 buffer[0] = '[';
2187 len = strlen(buffer);
2188 buffer[len] = ']';
2189 len++;
2190 buffer[len] = ':';
2191 len++;
2192 p = buffer;
2193 }
2194 else if (ret == AF_INET) {
2195 p = buffer + 1;
2196 len = strlen(p);
2197 p[len] = ':';
2198 len++;
2199 }
2200 else {
2201 lua_pushnil(L);
2202 return 1;
2203 }
2204
2205 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2206 lua_pushnil(L);
2207 return 1;
2208 }
2209
2210 lua_pushstring(L, p);
2211 return 1;
2212}
2213
2214/* Returns information about the peer of the connection. */
2215__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2216{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002217 struct hlua_socket *socket;
2218 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002219 struct xref *peer;
2220 struct appctx *appctx;
2221 struct stream_interface *si;
2222 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002223 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002224
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002225 MAY_LJMP(check_args(L, 1, "getpeername"));
2226
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002227 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002228
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002229 /* Check if we run on the same thread than the xreator thread.
2230 * We cannot access to the socket if the thread is different.
2231 */
2232 if (socket->tid != tid)
2233 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2234
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002235 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002236 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002237 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002238 lua_pushnil(L);
2239 return 1;
2240 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002241 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2242 si = appctx->owner;
2243 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002244
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002245 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002246 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002247 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002248 lua_pushnil(L);
2249 return 1;
2250 }
2251
Willy Tarreaua71f6422016-11-16 17:00:14 +01002252 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002253 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002254 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002255 lua_pushnil(L);
2256 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002257 }
2258
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002259 ret = MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2260 xref_unlock(&socket->xref, peer);
2261 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002262}
2263
2264/* Returns information about my connection side. */
2265static int hlua_socket_getsockname(struct lua_State *L)
2266{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002267 struct hlua_socket *socket;
2268 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002269 struct appctx *appctx;
2270 struct xref *peer;
2271 struct stream_interface *si;
2272 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002273 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002274
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002275 MAY_LJMP(check_args(L, 1, "getsockname"));
2276
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002277 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002278
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002279 /* Check if we run on the same thread than the xreator thread.
2280 * We cannot access to the socket if the thread is different.
2281 */
2282 if (socket->tid != tid)
2283 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2284
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002285 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002286 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002287 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002288 lua_pushnil(L);
2289 return 1;
2290 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002291 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2292 si = appctx->owner;
2293 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002294
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002295 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002296 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002297 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002298 lua_pushnil(L);
2299 return 1;
2300 }
2301
Willy Tarreaua71f6422016-11-16 17:00:14 +01002302 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002303 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002304 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002305 lua_pushnil(L);
2306 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002307 }
2308
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002309 ret = hlua_socket_info(L, &conn->addr.from);
2310 xref_unlock(&socket->xref, peer);
2311 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002312}
2313
2314/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002315static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002316 .obj_type = OBJ_TYPE_APPLET,
2317 .name = "<LUA_TCP>",
2318 .fct = hlua_socket_handler,
2319 .release = hlua_socket_release,
2320};
2321
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002322__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323{
2324 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2325 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002326 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002327 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002328 struct stream_interface *si;
2329 struct stream *s;
2330
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002331 /* Check if we run on the same thread than the xreator thread.
2332 * We cannot access to the socket if the thread is different.
2333 */
2334 if (socket->tid != tid)
2335 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2336
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002337 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002338 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002339 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002340 lua_pushnil(L);
2341 lua_pushstring(L, "Can't connect");
2342 return 2;
2343 }
2344 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2345 si = appctx->owner;
2346 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002347
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002348 /* Check if we run on the same thread than the xreator thread.
2349 * We cannot access to the socket if the thread is different.
2350 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002351 if (socket->tid != tid) {
2352 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002353 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002354 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002355
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002356 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002357 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002358 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002359 lua_pushnil(L);
2360 lua_pushstring(L, "Can't connect");
2361 return 2;
2362 }
2363
Willy Tarreaue09101e2018-10-16 17:37:12 +02002364 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002365
2366 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002367 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002368 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002369 lua_pushinteger(L, 1);
2370 return 1;
2371 }
2372
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002373 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2374 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002375 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002376 }
2377 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002378 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002379 return 0;
2380}
2381
2382/* This function fail or initite the connection. */
2383__LJMP static int hlua_socket_connect(struct lua_State *L)
2384{
2385 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002386 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002387 const char *ip;
2388 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002389 struct hlua *hlua;
2390 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002391 int low, high;
2392 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002393 struct xref *peer;
2394 struct stream_interface *si;
2395 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002396
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002397 if (lua_gettop(L) < 2)
2398 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002399
2400 /* Get args. */
2401 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002402
2403 /* Check if we run on the same thread than the xreator thread.
2404 * We cannot access to the socket if the thread is different.
2405 */
2406 if (socket->tid != tid)
2407 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2408
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002409 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002410 if (lua_gettop(L) >= 3) {
2411 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002412 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002413
Tim Duesterhus6edab862018-01-06 19:04:45 +01002414 /* Force the ip to end with a colon, to support IPv6 addresses
2415 * that are not enclosed within square brackets.
2416 */
2417 if (port > 0) {
2418 luaL_buffinit(L, &b);
2419 luaL_addstring(&b, ip);
2420 luaL_addchar(&b, ':');
2421 luaL_pushresult(&b);
2422 ip = lua_tolstring(L, lua_gettop(L), NULL);
2423 }
2424 }
2425
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002426 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002427 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002428 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002429 lua_pushnil(L);
2430 return 1;
2431 }
2432 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2433 si = appctx->owner;
2434 s = si_strm(si);
2435
2436 /* Initialise connection. */
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002437 conn = cs_conn(si_alloc_cs(&s->si[1], NULL));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002438 if (!conn) {
2439 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002440 WILL_LJMP(luaL_error(L, "connect: internal error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002441 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002442
Willy Tarreau3adac082015-09-26 17:51:09 +02002443 /* needed for the connection not to be closed */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002444 conn->target = s->target;
Willy Tarreau3adac082015-09-26 17:51:09 +02002445
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002446 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002447 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002448 if (!addr) {
2449 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002450 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002451 }
2452 if (low != high) {
2453 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002454 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002455 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002456 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002457
2458 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002459 if (low == 0) {
2460 if (conn->addr.to.ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002461 if (port == -1) {
2462 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002463 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002464 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002465 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2466 } else if (conn->addr.to.ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002467 if (port == -1) {
2468 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002469 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002470 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002471 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2472 }
2473 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002474
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002475 hlua = hlua_gethlua(L);
Willy Tarreaue09101e2018-10-16 17:37:12 +02002476 appctx = __objt_appctx(s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002477
2478 /* inform the stream that we want to be notified whenever the
2479 * connection completes.
2480 */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002481 si_applet_cant_get(&s->si[0]);
2482 si_applet_cant_put(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002483 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002484
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002485 hlua->flags |= HLUA_MUST_GC;
2486
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002487 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2488 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002489 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002490 }
2491 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002492
2493 task_wakeup(s->task, TASK_WOKEN_INIT);
2494 /* Return yield waiting for connection. */
2495
Willy Tarreau9635e032018-10-16 17:52:55 +02002496 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002497
2498 return 0;
2499}
2500
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002501#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002502__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2503{
2504 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002505 struct xref *peer;
2506 struct appctx *appctx;
2507 struct stream_interface *si;
2508 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002509
2510 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2511 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002512
2513 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002514 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002515 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002516 lua_pushnil(L);
2517 return 1;
2518 }
2519 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2520 si = appctx->owner;
2521 s = si_strm(si);
2522
2523 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002524 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002525 return MAY_LJMP(hlua_socket_connect(L));
2526}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002527#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002528
2529__LJMP static int hlua_socket_setoption(struct lua_State *L)
2530{
2531 return 0;
2532}
2533
2534__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2535{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002536 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002537 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002538 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002539 struct xref *peer;
2540 struct appctx *appctx;
2541 struct stream_interface *si;
2542 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002543
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002544 MAY_LJMP(check_args(L, 2, "settimeout"));
2545
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002546 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002547
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002548 /* convert the timeout to millis */
2549 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002550
Thierry Fournier17a921b2018-03-08 09:59:02 +01002551 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002552 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002553 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2554
Mark Lakes56cc1252018-03-27 09:48:06 +02002555 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002556 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002557
2558 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002559 if (tmout == 0)
2560 tmout++; /* very small timeouts are adjusted to a minium of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002561
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002562 /* Check if we run on the same thread than the xreator thread.
2563 * We cannot access to the socket if the thread is different.
2564 */
2565 if (socket->tid != tid)
2566 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2567
Mark Lakes56cc1252018-03-27 09:48:06 +02002568 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002569 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002570 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002571 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2572 WILL_LJMP(lua_error(L));
2573 return 0;
2574 }
2575 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2576 si = appctx->owner;
2577 s = si_strm(si);
2578
Cyril Bonté7bb63452018-08-17 23:51:02 +02002579 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002580 s->req.rto = tmout;
2581 s->req.wto = tmout;
2582 s->res.rto = tmout;
2583 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002584 s->req.rex = tick_add_ifset(now_ms, tmout);
2585 s->req.wex = tick_add_ifset(now_ms, tmout);
2586 s->res.rex = tick_add_ifset(now_ms, tmout);
2587 s->res.wex = tick_add_ifset(now_ms, tmout);
2588
2589 s->task->expire = tick_add_ifset(now_ms, tmout);
2590 task_queue(s->task);
2591
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002592 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002593
Thierry Fourniere9636f12018-03-08 09:54:32 +01002594 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002595 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002596}
2597
2598__LJMP static int hlua_socket_new(lua_State *L)
2599{
2600 struct hlua_socket *socket;
2601 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002602 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002603 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002604
2605 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002606 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002607 hlua_pusherror(L, "socket: full stack");
2608 goto out_fail_conf;
2609 }
2610
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002611 /* Create the object: obj[0] = userdata. */
2612 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002613 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002614 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002615 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002616 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002617
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002618 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002619 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002620 hlua_pusherror(L, "socket: uninitialized pools.");
2621 goto out_fail_conf;
2622 }
2623
Willy Tarreau87b09662015-04-03 00:22:06 +02002624 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002625 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2626 lua_setmetatable(L, -2);
2627
Willy Tarreaud420a972015-04-06 00:39:18 +02002628 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002629 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002630 if (!appctx) {
2631 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002632 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002633 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002634
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002635 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002636 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002637 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2638 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002639
Willy Tarreaud420a972015-04-06 00:39:18 +02002640 /* Now create a session, task and stream for this applet */
2641 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2642 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002643 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002644 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002645 }
2646
Willy Tarreau87787ac2017-08-28 16:22:54 +02002647 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002648 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002649 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002650 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002651 }
2652
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002653 /* Initialise cross reference between stream and Lua socket object. */
2654 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002655
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002656 /* Configure "right" stream interface. this "si" is used to connect
2657 * and retrieve data from the server. The connection is initialized
2658 * with the "struct server".
2659 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002660 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002661
2662 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002663 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2664 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002665
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002666 return 1;
2667
Willy Tarreaud420a972015-04-06 00:39:18 +02002668 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002669 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002670 out_fail_sess:
2671 appctx_free(appctx);
2672 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002673 WILL_LJMP(lua_error(L));
2674 return 0;
2675}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002676
2677/*
2678 *
2679 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002680 * Class Channel
2681 *
2682 *
2683 */
2684
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002685/* The state between the channel data and the HTTP parser state can be
2686 * unconsistent, so reset the parser and call it again. Warning, this
2687 * action not revalidate the request and not send a 400 if the modified
2688 * resuest is not valid.
2689 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002690 * This function never fails. The direction is set using dir, which equals
2691 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002692 */
2693static void hlua_resynchonize_proto(struct stream *stream, int dir)
2694{
2695 /* Protocol HTTP. */
2696 if (stream->be->mode == PR_MODE_HTTP) {
2697
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002698 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002699 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002700 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002701 http_txn_reset_res(stream->txn);
2702
2703 if (stream->txn->hdr_idx.v)
2704 hdr_idx_init(&stream->txn->hdr_idx);
2705
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002706 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002707 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002708 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002709 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2710 }
2711}
2712
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002713/* This function is called before the Lua execution. It stores
2714 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002715 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002716static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002717{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002718 c->mode = stream->be->mode;
2719 switch (c->mode) {
2720 case PR_MODE_HTTP:
2721 c->data.http.dir = opt & SMP_OPT_DIR;
2722 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2723 c->data.http.state = stream->txn->req.msg_state;
2724 else
2725 c->data.http.state = stream->txn->rsp.msg_state;
2726 break;
2727 default:
2728 break;
2729 }
2730}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002731
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002732/* This function is called after the Lua execution. it
2733 * returns true if the parser state is consistent, otherwise,
2734 * it return false.
2735 *
2736 * In HTTP mode, the parser state must be in the same state
2737 * or greater when we exit the function. Even if we do a
2738 * control yield. This prevent to break the HTTP message
2739 * from the Lua code.
2740 */
2741static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2742{
2743 if (c->mode != stream->be->mode)
2744 return 0;
2745
2746 switch (c->mode) {
2747 case PR_MODE_HTTP:
2748 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002749 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002750 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2751 return stream->txn->req.msg_state >= c->data.http.state;
2752 else
2753 return stream->txn->rsp.msg_state >= c->data.http.state;
2754 default:
2755 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002756 }
2757 return 1;
2758}
2759
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002760/* Returns the struct hlua_channel join to the class channel in the
2761 * stack entry "ud" or throws an argument error.
2762 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002763__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002764{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002765 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002766}
2767
Willy Tarreau47860ed2015-03-10 14:07:50 +01002768/* Pushes the channel onto the top of the stack. If the stask does not have a
2769 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002770 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002771static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002772{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002773 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002774 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002775 return 0;
2776
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002777 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002778 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002779 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002780
2781 /* Pop a class sesison metatable and affect it to the userdata. */
2782 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2783 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002784 return 1;
2785}
2786
2787/* Duplicate all the data present in the input channel and put it
2788 * in a string LUA variables. Returns -1 and push a nil value in
2789 * the stack if the channel is closed and all the data are consumed,
2790 * returns 0 if no data are available, otherwise it returns the length
2791 * of the builded string.
2792 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002793static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002794{
2795 char *blk1;
2796 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002797 size_t len1;
2798 size_t len2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002799 int ret;
2800 luaL_Buffer b;
2801
Willy Tarreau06d80a92017-10-19 14:32:15 +02002802 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002803 if (unlikely(ret == 0))
2804 return 0;
2805
2806 if (unlikely(ret < 0)) {
2807 lua_pushnil(L);
2808 return -1;
2809 }
2810
2811 luaL_buffinit(L, &b);
2812 luaL_addlstring(&b, blk1, len1);
2813 if (unlikely(ret == 2))
2814 luaL_addlstring(&b, blk2, len2);
2815 luaL_pushresult(&b);
2816
2817 if (unlikely(ret == 2))
2818 return len1 + len2;
2819 return len1;
2820}
2821
2822/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2823 * a yield. This function keep the data in the buffer.
2824 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002825__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002826{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002827 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002828
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002829 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2830
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002831 if (_hlua_channel_dup(chn, L) == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002832 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002833 return 1;
2834}
2835
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002836/* Check arguments for the function "hlua_channel_dup_yield". */
2837__LJMP static int hlua_channel_dup(lua_State *L)
2838{
2839 MAY_LJMP(check_args(L, 1, "dup"));
2840 MAY_LJMP(hlua_checkchannel(L, 1));
2841 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2842}
2843
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002844/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2845 * a yield. This function consumes the data in the buffer. It returns
2846 * a string containing the data or a nil pointer if no data are available
2847 * and the channel is closed.
2848 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002849__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002850{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002851 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002852 int ret;
2853
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002854 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002855
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002856 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002857 if (unlikely(ret == 0))
Willy Tarreau9635e032018-10-16 17:52:55 +02002858 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002859
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002860 if (unlikely(ret == -1))
2861 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002862
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002863 b_sub(&chn->buf, ret);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002864 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002865 return 1;
2866}
2867
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002868/* Check arguments for the fucntion "hlua_channel_get_yield". */
2869__LJMP static int hlua_channel_get(lua_State *L)
2870{
2871 MAY_LJMP(check_args(L, 1, "get"));
2872 MAY_LJMP(hlua_checkchannel(L, 1));
2873 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2874}
2875
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002876/* This functions consumes and returns one line. If the channel is closed,
2877 * and the last data does not contains a final '\n', the data are returned
2878 * without the final '\n'. When no more data are avalaible, it returns nil
2879 * value.
2880 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002881__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002882{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002883 char *blk1;
2884 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002885 size_t len1;
2886 size_t len2;
2887 size_t len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002888 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002889 int ret;
2890 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002891
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002892 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2893
Willy Tarreau06d80a92017-10-19 14:32:15 +02002894 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002895 if (ret == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002896 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002897
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002898 if (ret == -1) {
2899 lua_pushnil(L);
2900 return 1;
2901 }
2902
2903 luaL_buffinit(L, &b);
2904 luaL_addlstring(&b, blk1, len1);
2905 len = len1;
2906 if (unlikely(ret == 2)) {
2907 luaL_addlstring(&b, blk2, len2);
2908 len += len2;
2909 }
2910 luaL_pushresult(&b);
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002911 b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn) + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002912 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002913 return 1;
2914}
2915
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002916/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2917__LJMP static int hlua_channel_getline(lua_State *L)
2918{
2919 MAY_LJMP(check_args(L, 1, "getline"));
2920 MAY_LJMP(hlua_checkchannel(L, 1));
2921 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2922}
2923
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002924/* This function takes a string as input, and append it at the
2925 * input side of channel. If the data is too big, but a space
2926 * is probably available after sending some data, the function
2927 * yield. If the data is bigger than the buffer, or if the
2928 * channel is closed, it returns -1. otherwise, it returns the
2929 * amount of data writed.
2930 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002931__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002932{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002933 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002934 size_t len;
2935 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2936 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2937 int ret;
2938 int max;
2939
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002940 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2941 * the request buffer if its not required.
2942 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002943 if (chn->buf.size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002944 si_applet_cant_put(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02002945 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002946 }
2947
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002948 max = channel_recv_limit(chn) - b_data(&chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002949 if (max > len - l)
2950 max = len - l;
2951
Willy Tarreau06d80a92017-10-19 14:32:15 +02002952 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002953 if (ret == -2 || ret == -3) {
2954 lua_pushinteger(L, -1);
2955 return 1;
2956 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002957 if (ret == -1) {
2958 chn->flags |= CF_WAKE_WRITE;
Willy Tarreau9635e032018-10-16 17:52:55 +02002959 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002960 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002961 l += ret;
2962 lua_pop(L, 1);
2963 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002964 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002965
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002966 max = channel_recv_limit(chn) - b_data(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02002967 if (max == 0 && co_data(chn) == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002968 /* There are no space avalaible, and the output buffer is empty.
2969 * in this case, we cannot add more data, so we cannot yield,
2970 * we return the amount of copyied data.
2971 */
2972 return 1;
2973 }
2974 if (l < len)
Willy Tarreau9635e032018-10-16 17:52:55 +02002975 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002976 return 1;
2977}
2978
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002979/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002980 * of the writed string, or -1 if the channel is closed or if the
2981 * buffer size is too little for the data.
2982 */
2983__LJMP static int hlua_channel_append(lua_State *L)
2984{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002985 size_t len;
2986
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002987 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002988 MAY_LJMP(hlua_checkchannel(L, 1));
2989 MAY_LJMP(luaL_checklstring(L, 2, &len));
2990 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002991 lua_pushinteger(L, 0);
2992
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002993 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002994}
2995
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002996/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002997 * his process by cleaning the buffer. The result is a replacement
2998 * of the current data. It returns the length of the writed string,
2999 * or -1 if the channel is closed or if the buffer size is too
3000 * little for the data.
3001 */
3002__LJMP static int hlua_channel_set(lua_State *L)
3003{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003004 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003005
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003006 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003007 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003008 lua_pushinteger(L, 0);
3009
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003010 b_set_data(&chn->buf, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003011
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003012 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003013}
3014
3015/* Append data in the output side of the buffer. This data is immediatly
3016 * sent. The fcuntion returns the ammount of data writed. If the buffer
3017 * cannot contains the data, the function yield. The function returns -1
3018 * if the channel is closed.
3019 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003020__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003021{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003022 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003023 size_t len;
3024 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3025 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3026 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003027 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003028
Willy Tarreau47860ed2015-03-10 14:07:50 +01003029 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003030 lua_pushinteger(L, -1);
3031 return 1;
3032 }
3033
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003034 /* Check if the buffer is avalaible because HAProxy doesn't allocate
3035 * the request buffer if its not required.
3036 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003037 if (chn->buf.size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01003038 si_applet_cant_put(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02003039 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003040 }
3041
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003042 /* the writed data will be immediatly sent, so we can check
3043 * the avalaible space without taking in account the reserve.
3044 * The reserve is guaranted for the processing of incoming
3045 * data, because the buffer will be flushed.
3046 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003047 max = b_room(&chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003048
3049 /* If there are no space avalaible, and the output buffer is empty.
3050 * in this case, we cannot add more data, so we cannot yield,
3051 * we return the amount of copyied data.
3052 */
Willy Tarreaua79021a2018-06-15 18:07:57 +02003053 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003054 return 1;
3055
3056 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003057 if (max > len - l)
3058 max = len - l;
3059
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003060 /* The buffer avalaible size may be not contiguous. This test
3061 * detects a non contiguous buffer and realign it.
3062 */
Willy Tarreau3f679992018-06-15 15:06:42 +02003063 if (ci_space_for_replace(chn) < max)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003064 channel_slow_realign(chn, trash.area);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003065
3066 /* Copy input data in the buffer. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003067 max = b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn), str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003068
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003069 /* buffer replace considers that the input part is filled.
3070 * so, I must forward these new data in the output part.
3071 */
Willy Tarreaubcbd3932018-06-06 07:13:22 +02003072 c_adv(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003073
3074 l += max;
3075 lua_pop(L, 1);
3076 lua_pushinteger(L, l);
3077
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003078 /* If there are no space avalaible, and the output buffer is empty.
3079 * in this case, we cannot add more data, so we cannot yield,
3080 * we return the amount of copyied data.
3081 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003082 max = b_room(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003083 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003084 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003085
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003086 if (l < len) {
3087 /* If we are waiting for space in the response buffer, we
3088 * must set the flag WAKERESWR. This flag required the task
3089 * wake up if any activity is detected on the response buffer.
3090 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003091 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003092 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003093 else
3094 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003095 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003096 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003097
3098 return 1;
3099}
3100
3101/* Just a wraper of "_hlua_channel_send". This wrapper permits
3102 * yield the LUA process, and resume it without checking the
3103 * input arguments.
3104 */
3105__LJMP static int hlua_channel_send(lua_State *L)
3106{
3107 MAY_LJMP(check_args(L, 2, "send"));
3108 lua_pushinteger(L, 0);
3109
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003110 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003111}
3112
3113/* This function forward and amount of butes. The data pass from
3114 * the input side of the buffer to the output side, and can be
3115 * forwarded. This function never fails.
3116 *
3117 * The Lua function takes an amount of bytes to be forwarded in
3118 * imput. It returns the number of bytes forwarded.
3119 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003120__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003121{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003122 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003123 int len;
3124 int l;
3125 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003126 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003127
3128 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3129 len = MAY_LJMP(luaL_checkinteger(L, 2));
3130 l = MAY_LJMP(luaL_checkinteger(L, -1));
3131
3132 max = len - l;
Willy Tarreaua79021a2018-06-15 18:07:57 +02003133 if (max > ci_data(chn))
3134 max = ci_data(chn);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003135 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003136 l += max;
3137
3138 lua_pop(L, 1);
3139 lua_pushinteger(L, l);
3140
3141 /* Check if it miss bytes to forward. */
3142 if (l < len) {
3143 /* The the input channel or the output channel are closed, we
3144 * must return the amount of data forwarded.
3145 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003146 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003147 return 1;
3148
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003149 /* If we are waiting for space data in the response buffer, we
3150 * must set the flag WAKERESWR. This flag required the task
3151 * wake up if any activity is detected on the response buffer.
3152 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003153 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003154 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003155 else
3156 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003157
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003158 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003159 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003160 }
3161
3162 return 1;
3163}
3164
3165/* Just check the input and prepare the stack for the previous
3166 * function "hlua_channel_forward_yield"
3167 */
3168__LJMP static int hlua_channel_forward(lua_State *L)
3169{
3170 MAY_LJMP(check_args(L, 2, "forward"));
3171 MAY_LJMP(hlua_checkchannel(L, 1));
3172 MAY_LJMP(luaL_checkinteger(L, 2));
3173
3174 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003175 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003176}
3177
3178/* Just returns the number of bytes available in the input
3179 * side of the buffer. This function never fails.
3180 */
3181__LJMP static int hlua_channel_get_in_len(lua_State *L)
3182{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003183 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003184
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003185 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003186 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003187 lua_pushinteger(L, ci_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003188 return 1;
3189}
3190
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003191/* Returns true if the channel is full. */
3192__LJMP static int hlua_channel_is_full(lua_State *L)
3193{
3194 struct channel *chn;
3195 int rem;
3196
3197 MAY_LJMP(check_args(L, 1, "is_full"));
3198 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3199
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003200 rem = b_room(&chn->buf);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003201 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
3202
3203 lua_pushboolean(L, rem <= 0);
3204 return 1;
3205}
3206
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003207/* Just returns the number of bytes available in the output
3208 * side of the buffer. This function never fails.
3209 */
3210__LJMP static int hlua_channel_get_out_len(lua_State *L)
3211{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003212 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003213
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003214 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003215 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003216 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003217 return 1;
3218}
3219
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003220/*
3221 *
3222 *
3223 * Class Fetches
3224 *
3225 *
3226 */
3227
3228/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003229 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003230 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003231__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003232{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003233 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003234}
3235
3236/* This function creates and push in the stack a fetch object according
3237 * with a current TXN.
3238 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003239static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003240{
Willy Tarreau7073c472015-04-06 11:15:40 +02003241 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003242
3243 /* Check stack size. */
3244 if (!lua_checkstack(L, 3))
3245 return 0;
3246
3247 /* Create the object: obj[0] = userdata.
3248 * Note that the base of the Fetches object is the
3249 * transaction object.
3250 */
3251 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003252 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003253 lua_rawseti(L, -2, 0);
3254
Willy Tarreau7073c472015-04-06 11:15:40 +02003255 hsmp->s = txn->s;
3256 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003257 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003258 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003259
3260 /* Pop a class sesison metatable and affect it to the userdata. */
3261 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3262 lua_setmetatable(L, -2);
3263
3264 return 1;
3265}
3266
3267/* This function is an LUA binding. It is called with each sample-fetch.
3268 * It uses closure argument to store the associated sample-fetch. It
3269 * returns only one argument or throws an error. An error is thrown
3270 * only if an error is encountered during the argument parsing. If
3271 * the "sample-fetch" function fails, nil is returned.
3272 */
3273__LJMP static int hlua_run_sample_fetch(lua_State *L)
3274{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003275 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003276 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003277 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003278 int i;
3279 struct sample smp;
3280
3281 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003282 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003283
3284 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003285 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003286
Thierry FOURNIERca988662015-12-20 18:43:03 +01003287 /* Check execution authorization. */
3288 if (f->use & SMP_USE_HTTP_ANY &&
3289 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3290 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3291 "is not available in Lua services", f->kw);
3292 WILL_LJMP(lua_error(L));
3293 }
3294
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003295 /* Get extra arguments. */
3296 for (i = 0; i < lua_gettop(L) - 1; i++) {
3297 if (i >= ARGM_NBARGS)
3298 break;
3299 hlua_lua2arg(L, i + 2, &args[i]);
3300 }
3301 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003302 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003303
3304 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003305 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003306
3307 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003308 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003309 lua_pushfstring(L, "error in arguments");
3310 WILL_LJMP(lua_error(L));
3311 }
3312
3313 /* Initialise the sample. */
3314 memset(&smp, 0, sizeof(smp));
3315
3316 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003317 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003318 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003319 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003320 lua_pushstring(L, "");
3321 else
3322 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003323 return 1;
3324 }
3325
3326 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003327 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003328 hlua_smp2lua_str(L, &smp);
3329 else
3330 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003331 return 1;
3332}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003333
3334/*
3335 *
3336 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003337 * Class Converters
3338 *
3339 *
3340 */
3341
3342/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003343 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003344 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003345__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003346{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003347 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003348}
3349
3350/* This function creates and push in the stack a Converters object
3351 * according with a current TXN.
3352 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003353static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003354{
Willy Tarreau7073c472015-04-06 11:15:40 +02003355 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003356
3357 /* Check stack size. */
3358 if (!lua_checkstack(L, 3))
3359 return 0;
3360
3361 /* Create the object: obj[0] = userdata.
3362 * Note that the base of the Converters object is the
3363 * same than the TXN object.
3364 */
3365 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003366 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003367 lua_rawseti(L, -2, 0);
3368
Willy Tarreau7073c472015-04-06 11:15:40 +02003369 hsmp->s = txn->s;
3370 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003371 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003372 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003373
Willy Tarreau87b09662015-04-03 00:22:06 +02003374 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003375 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3376 lua_setmetatable(L, -2);
3377
3378 return 1;
3379}
3380
3381/* This function is an LUA binding. It is called with each converter.
3382 * It uses closure argument to store the associated converter. It
3383 * returns only one argument or throws an error. An error is thrown
3384 * only if an error is encountered during the argument parsing. If
3385 * the converter function function fails, nil is returned.
3386 */
3387__LJMP static int hlua_run_sample_conv(lua_State *L)
3388{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003389 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003390 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003391 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003392 int i;
3393 struct sample smp;
3394
3395 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003396 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003397
3398 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003399 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003400
3401 /* Get extra arguments. */
3402 for (i = 0; i < lua_gettop(L) - 2; i++) {
3403 if (i >= ARGM_NBARGS)
3404 break;
3405 hlua_lua2arg(L, i + 3, &args[i]);
3406 }
3407 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003408 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003409
3410 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003411 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003412
3413 /* Run the special args checker. */
3414 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3415 hlua_pusherror(L, "error in arguments");
3416 WILL_LJMP(lua_error(L));
3417 }
3418
3419 /* Initialise the sample. */
3420 if (!hlua_lua2smp(L, 2, &smp)) {
3421 hlua_pusherror(L, "error in the input argument");
3422 WILL_LJMP(lua_error(L));
3423 }
3424
Willy Tarreau1777ea62016-03-10 16:15:46 +01003425 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3426
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003427 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003428 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003429 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003430 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003431 WILL_LJMP(lua_error(L));
3432 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003433 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3434 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003435 hlua_pusherror(L, "error during the input argument casting");
3436 WILL_LJMP(lua_error(L));
3437 }
3438
3439 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003440 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003441 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003442 lua_pushstring(L, "");
3443 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003444 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003445 return 1;
3446 }
3447
3448 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003449 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003450 hlua_smp2lua_str(L, &smp);
3451 else
3452 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003453 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003454}
3455
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003456/*
3457 *
3458 *
3459 * Class AppletTCP
3460 *
3461 *
3462 */
3463
3464/* Returns a struct hlua_txn if the stack entry "ud" is
3465 * a class stream, otherwise it throws an error.
3466 */
3467__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3468{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003469 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003470}
3471
3472/* This function creates and push in the stack an Applet object
3473 * according with a current TXN.
3474 */
3475static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3476{
3477 struct hlua_appctx *appctx;
3478 struct stream_interface *si = ctx->owner;
3479 struct stream *s = si_strm(si);
3480 struct proxy *p = s->be;
3481
3482 /* Check stack size. */
3483 if (!lua_checkstack(L, 3))
3484 return 0;
3485
3486 /* Create the object: obj[0] = userdata.
3487 * Note that the base of the Converters object is the
3488 * same than the TXN object.
3489 */
3490 lua_newtable(L);
3491 appctx = lua_newuserdata(L, sizeof(*appctx));
3492 lua_rawseti(L, -2, 0);
3493 appctx->appctx = ctx;
3494 appctx->htxn.s = s;
3495 appctx->htxn.p = p;
3496
3497 /* Create the "f" field that contains a list of fetches. */
3498 lua_pushstring(L, "f");
3499 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3500 return 0;
3501 lua_settable(L, -3);
3502
3503 /* Create the "sf" field that contains a list of stringsafe fetches. */
3504 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003505 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003506 return 0;
3507 lua_settable(L, -3);
3508
3509 /* Create the "c" field that contains a list of converters. */
3510 lua_pushstring(L, "c");
3511 if (!hlua_converters_new(L, &appctx->htxn, 0))
3512 return 0;
3513 lua_settable(L, -3);
3514
3515 /* Create the "sc" field that contains a list of stringsafe converters. */
3516 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003517 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003518 return 0;
3519 lua_settable(L, -3);
3520
3521 /* Pop a class stream metatable and affect it to the table. */
3522 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3523 lua_setmetatable(L, -2);
3524
3525 return 1;
3526}
3527
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003528__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3529{
3530 struct hlua_appctx *appctx;
3531 struct stream *s;
3532 const char *name;
3533 size_t len;
3534 struct sample smp;
3535
3536 MAY_LJMP(check_args(L, 3, "set_var"));
3537
3538 /* It is useles to retrieve the stream, but this function
3539 * runs only in a stream context.
3540 */
3541 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3542 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3543 s = appctx->htxn.s;
3544
3545 /* Converts the third argument in a sample. */
3546 hlua_lua2smp(L, 3, &smp);
3547
3548 /* Store the sample in a variable. */
3549 smp_set_owner(&smp, s->be, s->sess, s, 0);
3550 vars_set_by_name(name, len, &smp);
3551 return 0;
3552}
3553
3554__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3555{
3556 struct hlua_appctx *appctx;
3557 struct stream *s;
3558 const char *name;
3559 size_t len;
3560 struct sample smp;
3561
3562 MAY_LJMP(check_args(L, 2, "unset_var"));
3563
3564 /* It is useles to retrieve the stream, but this function
3565 * runs only in a stream context.
3566 */
3567 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3568 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3569 s = appctx->htxn.s;
3570
3571 /* Unset the variable. */
3572 smp_set_owner(&smp, s->be, s->sess, s, 0);
3573 vars_unset_by_name(name, len, &smp);
3574 return 0;
3575}
3576
3577__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3578{
3579 struct hlua_appctx *appctx;
3580 struct stream *s;
3581 const char *name;
3582 size_t len;
3583 struct sample smp;
3584
3585 MAY_LJMP(check_args(L, 2, "get_var"));
3586
3587 /* It is useles to retrieve the stream, but this function
3588 * runs only in a stream context.
3589 */
3590 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3591 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3592 s = appctx->htxn.s;
3593
3594 smp_set_owner(&smp, s->be, s->sess, s, 0);
3595 if (!vars_get_by_name(name, len, &smp)) {
3596 lua_pushnil(L);
3597 return 1;
3598 }
3599
3600 return hlua_smp2lua(L, &smp);
3601}
3602
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003603__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3604{
3605 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3606 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003607 struct hlua *hlua;
3608
3609 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003610 if (!s->hlua)
3611 return 0;
3612 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003613
3614 MAY_LJMP(check_args(L, 2, "set_priv"));
3615
3616 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003617 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003618
3619 /* Get and store new value. */
3620 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3621 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3622
3623 return 0;
3624}
3625
3626__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3627{
3628 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3629 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003630 struct hlua *hlua;
3631
3632 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003633 if (!s->hlua) {
3634 lua_pushnil(L);
3635 return 1;
3636 }
3637 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003638
3639 /* Push configuration index in the stack. */
3640 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3641
3642 return 1;
3643}
3644
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003645/* If expected data not yet available, it returns a yield. This function
3646 * consumes the data in the buffer. It returns a string containing the
3647 * data. This string can be empty.
3648 */
3649__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3650{
3651 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3652 struct stream_interface *si = appctx->appctx->owner;
3653 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003654 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003655 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003656 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003657 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003658
3659 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003660 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003661
3662 /* Data not yet avalaible. return yield. */
3663 if (ret == 0) {
3664 si_applet_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003665 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003666 }
3667
3668 /* End of data: commit the total strings and return. */
3669 if (ret < 0) {
3670 luaL_pushresult(&appctx->b);
3671 return 1;
3672 }
3673
3674 /* Ensure that the block 2 length is usable. */
3675 if (ret == 1)
3676 len2 = 0;
3677
3678 /* dont check the max length read and dont check. */
3679 luaL_addlstring(&appctx->b, blk1, len1);
3680 luaL_addlstring(&appctx->b, blk2, 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 luaL_pushresult(&appctx->b);
3685 return 1;
3686}
3687
3688/* Check arguments for the fucntion "hlua_channel_get_yield". */
3689__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3690{
3691 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3692
3693 /* Initialise the string catenation. */
3694 luaL_buffinit(L, &appctx->b);
3695
3696 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3697}
3698
3699/* If expected data not yet available, it returns a yield. This function
3700 * consumes the data in the buffer. It returns a string containing the
3701 * data. This string can be empty.
3702 */
3703__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3704{
3705 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3706 struct stream_interface *si = appctx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003707 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003708 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003709 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003710 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003711 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003712 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003713
3714 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003715 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003716
3717 /* Data not yet avalaible. return yield. */
3718 if (ret == 0) {
3719 si_applet_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003720 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003721 }
3722
3723 /* End of data: commit the total strings and return. */
3724 if (ret < 0) {
3725 luaL_pushresult(&appctx->b);
3726 return 1;
3727 }
3728
3729 /* Ensure that the block 2 length is usable. */
3730 if (ret == 1)
3731 len2 = 0;
3732
3733 if (len == -1) {
3734
3735 /* If len == -1, catenate all the data avalaile and
3736 * yield because we want to get all the data until
3737 * the end of data stream.
3738 */
3739 luaL_addlstring(&appctx->b, blk1, len1);
3740 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003741 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003742 si_applet_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003743 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003744
3745 } else {
3746
3747 /* Copy the fisrt block caping to the length required. */
3748 if (len1 > len)
3749 len1 = len;
3750 luaL_addlstring(&appctx->b, blk1, len1);
3751 len -= len1;
3752
3753 /* Copy the second block. */
3754 if (len2 > len)
3755 len2 = len;
3756 luaL_addlstring(&appctx->b, blk2, len2);
3757 len -= len2;
3758
3759 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003760 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003761
3762 /* If we are no other data avalaible, yield waiting for new data. */
3763 if (len > 0) {
3764 lua_pushinteger(L, len);
3765 lua_replace(L, 2);
3766 si_applet_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003767 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003768 }
3769
3770 /* return the result. */
3771 luaL_pushresult(&appctx->b);
3772 return 1;
3773 }
3774
3775 /* we never executes this */
3776 hlua_pusherror(L, "Lua: internal error");
3777 WILL_LJMP(lua_error(L));
3778 return 0;
3779}
3780
3781/* Check arguments for the fucntion "hlua_channel_get_yield". */
3782__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3783{
3784 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3785 int len = -1;
3786
3787 if (lua_gettop(L) > 2)
3788 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3789 if (lua_gettop(L) >= 2) {
3790 len = MAY_LJMP(luaL_checkinteger(L, 2));
3791 lua_pop(L, 1);
3792 }
3793
3794 /* Confirm or set the required length */
3795 lua_pushinteger(L, len);
3796
3797 /* Initialise the string catenation. */
3798 luaL_buffinit(L, &appctx->b);
3799
3800 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3801}
3802
3803/* Append data in the output side of the buffer. This data is immediatly
3804 * sent. The fcuntion returns the ammount of data writed. If the buffer
3805 * cannot contains the data, the function yield. The function returns -1
3806 * if the channel is closed.
3807 */
3808__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3809{
3810 size_t len;
3811 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3812 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3813 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3814 struct stream_interface *si = appctx->appctx->owner;
3815 struct channel *chn = si_ic(si);
3816 int max;
3817
3818 /* Get the max amount of data which can write as input in the channel. */
3819 max = channel_recv_max(chn);
3820 if (max > (len - l))
3821 max = len - l;
3822
3823 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003824 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003825
3826 /* update counters. */
3827 l += max;
3828 lua_pop(L, 1);
3829 lua_pushinteger(L, l);
3830
3831 /* If some data is not send, declares the situation to the
3832 * applet, and returns a yield.
3833 */
3834 if (l < len) {
3835 si_applet_cant_put(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003836 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003837 }
3838
3839 return 1;
3840}
3841
3842/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3843 * yield the LUA process, and resume it without checking the
3844 * input arguments.
3845 */
3846__LJMP static int hlua_applet_tcp_send(lua_State *L)
3847{
3848 MAY_LJMP(check_args(L, 2, "send"));
3849 lua_pushinteger(L, 0);
3850
3851 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3852}
3853
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003854/*
3855 *
3856 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003857 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003858 *
3859 *
3860 */
3861
3862/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003863 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003864 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003865__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003866{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003867 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003868}
3869
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003870/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003871 * according with a current TXN.
3872 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003873static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003874{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003875 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003876 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003877 struct stream_interface *si = ctx->owner;
3878 struct stream *s = si_strm(si);
3879 struct proxy *px = s->be;
3880 struct http_txn *txn = s->txn;
3881 const char *path;
3882 const char *end;
3883 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003884
3885 /* Check stack size. */
3886 if (!lua_checkstack(L, 3))
3887 return 0;
3888
3889 /* Create the object: obj[0] = userdata.
3890 * Note that the base of the Converters object is the
3891 * same than the TXN object.
3892 */
3893 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003894 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003895 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003896 appctx->appctx = ctx;
3897 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003898 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003899 appctx->htxn.s = s;
3900 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003901
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003902 /* Create the "f" field that contains a list of fetches. */
3903 lua_pushstring(L, "f");
3904 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3905 return 0;
3906 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003907
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003908 /* Create the "sf" field that contains a list of stringsafe fetches. */
3909 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003910 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003911 return 0;
3912 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003913
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003914 /* Create the "c" field that contains a list of converters. */
3915 lua_pushstring(L, "c");
3916 if (!hlua_converters_new(L, &appctx->htxn, 0))
3917 return 0;
3918 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003919
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003920 /* Create the "sc" field that contains a list of stringsafe converters. */
3921 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003922 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003923 return 0;
3924 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003925
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003926 /* Stores the request method. */
3927 lua_pushstring(L, "method");
Willy Tarreaua79021a2018-06-15 18:07:57 +02003928 lua_pushlstring(L, ci_head(txn->req.chn), txn->req.sl.rq.m_l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003929 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003930
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003931 /* Stores the http version. */
3932 lua_pushstring(L, "version");
Willy Tarreaua79021a2018-06-15 18:07:57 +02003933 lua_pushlstring(L, ci_head(txn->req.chn) + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003934 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003935
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003936 /* creates an array of headers. hlua_http_get_headers() crates and push
3937 * the array on the top of the stack.
3938 */
3939 lua_pushstring(L, "headers");
3940 htxn.s = s;
3941 htxn.p = px;
3942 htxn.dir = SMP_OPT_DIR_REQ;
3943 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3944 return 0;
3945 lua_settable(L, -3);
3946
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003947 /* Get path and qs */
Willy Tarreau6b952c82018-09-10 17:45:34 +02003948 path = http_txn_get_path(txn);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003949 if (path) {
Willy Tarreaua79021a2018-06-15 18:07:57 +02003950 end = ci_head(txn->req.chn) + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003951 p = path;
3952 while (p < end && *p != '?')
3953 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003954
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003955 /* Stores the request path. */
3956 lua_pushstring(L, "path");
3957 lua_pushlstring(L, path, p - path);
3958 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003959
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003960 /* Stores the query string. */
3961 lua_pushstring(L, "qs");
3962 if (*p == '?')
3963 p++;
3964 lua_pushlstring(L, p, end - p);
3965 lua_settable(L, -3);
3966 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003967
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003968 /* Stores the request path. */
3969 lua_pushstring(L, "length");
3970 lua_pushinteger(L, txn->req.body_len);
3971 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003972
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003973 /* Create an array of HTTP request headers. */
3974 lua_pushstring(L, "headers");
3975 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3976 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003977
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003978 /* Create an empty array of HTTP request headers. */
3979 lua_pushstring(L, "response");
3980 lua_newtable(L);
3981 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003982
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003983 /* Pop a class stream metatable and affect it to the table. */
3984 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3985 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003986
3987 return 1;
3988}
3989
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003990__LJMP static int hlua_applet_http_set_var(lua_State *L)
3991{
3992 struct hlua_appctx *appctx;
3993 struct stream *s;
3994 const char *name;
3995 size_t len;
3996 struct sample smp;
3997
3998 MAY_LJMP(check_args(L, 3, "set_var"));
3999
4000 /* It is useles to retrieve the stream, but this function
4001 * runs only in a stream context.
4002 */
4003 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4004 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4005 s = appctx->htxn.s;
4006
4007 /* Converts the third argument in a sample. */
4008 hlua_lua2smp(L, 3, &smp);
4009
4010 /* Store the sample in a variable. */
4011 smp_set_owner(&smp, s->be, s->sess, s, 0);
4012 vars_set_by_name(name, len, &smp);
4013 return 0;
4014}
4015
4016__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4017{
4018 struct hlua_appctx *appctx;
4019 struct stream *s;
4020 const char *name;
4021 size_t len;
4022 struct sample smp;
4023
4024 MAY_LJMP(check_args(L, 2, "unset_var"));
4025
4026 /* It is useles to retrieve the stream, but this function
4027 * runs only in a stream context.
4028 */
4029 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4030 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4031 s = appctx->htxn.s;
4032
4033 /* Unset the variable. */
4034 smp_set_owner(&smp, s->be, s->sess, s, 0);
4035 vars_unset_by_name(name, len, &smp);
4036 return 0;
4037}
4038
4039__LJMP static int hlua_applet_http_get_var(lua_State *L)
4040{
4041 struct hlua_appctx *appctx;
4042 struct stream *s;
4043 const char *name;
4044 size_t len;
4045 struct sample smp;
4046
4047 MAY_LJMP(check_args(L, 2, "get_var"));
4048
4049 /* It is useles to retrieve the stream, but this function
4050 * runs only in a stream context.
4051 */
4052 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4053 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4054 s = appctx->htxn.s;
4055
4056 smp_set_owner(&smp, s->be, s->sess, s, 0);
4057 if (!vars_get_by_name(name, len, &smp)) {
4058 lua_pushnil(L);
4059 return 1;
4060 }
4061
4062 return hlua_smp2lua(L, &smp);
4063}
4064
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004065__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4066{
4067 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4068 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004069 struct hlua *hlua;
4070
4071 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004072 if (!s->hlua)
4073 return 0;
4074 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004075
4076 MAY_LJMP(check_args(L, 2, "set_priv"));
4077
4078 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004079 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004080
4081 /* Get and store new value. */
4082 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4083 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4084
4085 return 0;
4086}
4087
4088__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4089{
4090 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4091 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004092 struct hlua *hlua;
4093
4094 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004095 if (!s->hlua) {
4096 lua_pushnil(L);
4097 return 1;
4098 }
4099 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004100
4101 /* Push configuration index in the stack. */
4102 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4103
4104 return 1;
4105}
4106
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004107/* If expected data not yet available, it returns a yield. This function
4108 * consumes the data in the buffer. It returns a string containing the
4109 * data. This string can be empty.
4110 */
4111__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004112{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004113 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4114 struct stream_interface *si = appctx->appctx->owner;
4115 struct channel *chn = si_ic(si);
4116 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004117 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004118 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004119 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004120 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004121
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004122 /* Maybe we cant send a 100-continue ? */
4123 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02004124 ret = ci_putblk(chn, HTTP_100.ptr, HTTP_100.len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004125 /* if ret == -2 or -3 the channel closed or the message si too
4126 * big for the buffers. We cant send anything. So, we ignoring
4127 * the error, considers that the 100-continue is sent, and try
4128 * to receive.
4129 * If ret is -1, we dont have room in the buffer, so we yield.
4130 */
4131 if (ret == -1) {
4132 si_applet_cant_put(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004133 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004134 }
4135 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4136 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004137
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004138 /* Check for the end of the data. */
4139 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4140 luaL_pushresult(&appctx->b);
4141 return 1;
4142 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004143
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004144 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004145 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004146
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004147 /* Data not yet avalaible. return yield. */
4148 if (ret == 0) {
4149 si_applet_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004150 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004151 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004152
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004153 /* End of data: commit the total strings and return. */
4154 if (ret < 0) {
4155 luaL_pushresult(&appctx->b);
4156 return 1;
4157 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004158
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004159 /* Ensure that the block 2 length is usable. */
4160 if (ret == 1)
4161 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004162
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004163 /* Copy the fisrt block caping to the length required. */
4164 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4165 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4166 luaL_addlstring(&appctx->b, blk1, len1);
4167 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004168
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004169 /* Copy the second block. */
4170 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4171 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4172 luaL_addlstring(&appctx->b, blk2, len2);
4173 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004174
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004175 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004176 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004177 luaL_pushresult(&appctx->b);
4178 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004179}
4180
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004181/* Check arguments for the fucntion "hlua_channel_get_yield". */
4182__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004183{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004184 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004185
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004186 /* Initialise the string catenation. */
4187 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004188
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004189 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004190}
4191
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004192/* If expected data not yet available, it returns a yield. This function
4193 * consumes the data in the buffer. It returns a string containing the
4194 * data. This string can be empty.
4195 */
4196__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004197{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004198 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4199 struct stream_interface *si = appctx->appctx->owner;
4200 int len = MAY_LJMP(luaL_checkinteger(L, 2));
4201 struct channel *chn = si_ic(si);
4202 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004203 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004204 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004205 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004206 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004207
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004208 /* Maybe we cant send a 100-continue ? */
4209 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02004210 ret = ci_putblk(chn, HTTP_100.ptr, HTTP_100.len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004211 /* if ret == -2 or -3 the channel closed or the message si too
4212 * big for the buffers. We cant send anything. So, we ignoring
4213 * the error, considers that the 100-continue is sent, and try
4214 * to receive.
4215 * If ret is -1, we dont have room in the buffer, so we yield.
4216 */
4217 if (ret == -1) {
4218 si_applet_cant_put(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004219 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004220 }
4221 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4222 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004223
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004224 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004225 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004226
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004227 /* Data not yet avalaible. return yield. */
4228 if (ret == 0) {
4229 si_applet_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004230 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004231 }
4232
4233 /* End of data: commit the total strings and return. */
4234 if (ret < 0) {
4235 luaL_pushresult(&appctx->b);
4236 return 1;
4237 }
4238
4239 /* Ensure that the block 2 length is usable. */
4240 if (ret == 1)
4241 len2 = 0;
4242
4243 /* Copy the fisrt block caping to the length required. */
4244 if (len1 > len)
4245 len1 = len;
4246 luaL_addlstring(&appctx->b, blk1, len1);
4247 len -= len1;
4248
4249 /* Copy the second block. */
4250 if (len2 > len)
4251 len2 = len;
4252 luaL_addlstring(&appctx->b, blk2, len2);
4253 len -= len2;
4254
4255 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004256 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004257 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4258 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4259
4260 /* If we are no other data avalaible, yield waiting for new data. */
4261 if (len > 0) {
4262 lua_pushinteger(L, len);
4263 lua_replace(L, 2);
4264 si_applet_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004265 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004266 }
4267
4268 /* return the result. */
4269 luaL_pushresult(&appctx->b);
4270 return 1;
4271}
4272
4273/* Check arguments for the fucntion "hlua_channel_get_yield". */
4274__LJMP static int hlua_applet_http_recv(lua_State *L)
4275{
4276 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4277 int len = -1;
4278
4279 /* Check arguments. */
4280 if (lua_gettop(L) > 2)
4281 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4282 if (lua_gettop(L) >= 2) {
4283 len = MAY_LJMP(luaL_checkinteger(L, 2));
4284 lua_pop(L, 1);
4285 }
4286
4287 /* Check the required length */
4288 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4289 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4290 lua_pushinteger(L, len);
4291
4292 /* Initialise the string catenation. */
4293 luaL_buffinit(L, &appctx->b);
4294
4295 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4296}
4297
4298/* Append data in the output side of the buffer. This data is immediatly
4299 * sent. The fcuntion returns the ammount of data writed. If the buffer
4300 * cannot contains the data, the function yield. The function returns -1
4301 * if the channel is closed.
4302 */
4303__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4304{
4305 size_t len;
4306 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4307 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4308 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4309 struct stream_interface *si = appctx->appctx->owner;
4310 struct channel *chn = si_ic(si);
4311 int max;
4312
4313 /* Get the max amount of data which can write as input in the channel. */
4314 max = channel_recv_max(chn);
4315 if (max > (len - l))
4316 max = len - l;
4317
4318 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004319 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004320
4321 /* update counters. */
4322 l += max;
4323 lua_pop(L, 1);
4324 lua_pushinteger(L, l);
4325
4326 /* If some data is not send, declares the situation to the
4327 * applet, and returns a yield.
4328 */
4329 if (l < len) {
4330 si_applet_cant_put(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004331 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004332 }
4333
4334 return 1;
4335}
4336
4337/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4338 * yield the LUA process, and resume it without checking the
4339 * input arguments.
4340 */
4341__LJMP static int hlua_applet_http_send(lua_State *L)
4342{
4343 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4344 size_t len;
4345 char hex[10];
4346
4347 MAY_LJMP(luaL_checklstring(L, 2, &len));
4348
4349 /* If transfer encoding chunked is selected, we surround the data
4350 * by chunk data.
4351 */
4352 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4353 snprintf(hex, 9, "%x", (unsigned int)len);
4354 lua_pushfstring(L, "%s\r\n", hex);
4355 lua_insert(L, 2); /* swap the last 2 entries. */
4356 lua_pushstring(L, "\r\n");
4357 lua_concat(L, 3);
4358 }
4359
4360 /* This interger is used for followinf the amount of data sent. */
4361 lua_pushinteger(L, 0);
4362
4363 /* We want to send some data. Headers must be sent. */
4364 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4365 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4366 WILL_LJMP(lua_error(L));
4367 }
4368
4369 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4370}
4371
4372__LJMP static int hlua_applet_http_addheader(lua_State *L)
4373{
4374 const char *name;
4375 int ret;
4376
4377 MAY_LJMP(hlua_checkapplet_http(L, 1));
4378 name = MAY_LJMP(luaL_checkstring(L, 2));
4379 MAY_LJMP(luaL_checkstring(L, 3));
4380
4381 /* Push in the stack the "response" entry. */
4382 ret = lua_getfield(L, 1, "response");
4383 if (ret != LUA_TTABLE) {
4384 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4385 "is expected as an array. %s found", lua_typename(L, ret));
4386 WILL_LJMP(lua_error(L));
4387 }
4388
4389 /* check if the header is already registered if it is not
4390 * the case, register it.
4391 */
4392 ret = lua_getfield(L, -1, name);
4393 if (ret == LUA_TNIL) {
4394
4395 /* Entry not found. */
4396 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4397
4398 /* Insert the new header name in the array in the top of the stack.
4399 * It left the new array in the top of the stack.
4400 */
4401 lua_newtable(L);
4402 lua_pushvalue(L, 2);
4403 lua_pushvalue(L, -2);
4404 lua_settable(L, -4);
4405
4406 } else if (ret != LUA_TTABLE) {
4407
4408 /* corruption error. */
4409 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4410 "is expected as an array. %s found", name, lua_typename(L, ret));
4411 WILL_LJMP(lua_error(L));
4412 }
4413
4414 /* Now the top od thestack is an array of values. We push
4415 * the header value as new entry.
4416 */
4417 lua_pushvalue(L, 3);
4418 ret = lua_rawlen(L, -2);
4419 lua_rawseti(L, -2, ret + 1);
4420 lua_pushboolean(L, 1);
4421 return 1;
4422}
4423
4424__LJMP static int hlua_applet_http_status(lua_State *L)
4425{
4426 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4427 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004428 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004429
4430 if (status < 100 || status > 599) {
4431 lua_pushboolean(L, 0);
4432 return 1;
4433 }
4434
4435 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004436 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004437 lua_pushboolean(L, 1);
4438 return 1;
4439}
4440
4441/* We will build the status line and the headers of the HTTP response.
4442 * We will try send at once if its not possible, we give back the hand
4443 * waiting for more room.
4444 */
4445__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4446{
4447 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4448 struct stream_interface *si = appctx->appctx->owner;
4449 struct channel *chn = si_ic(si);
4450 int ret;
4451 size_t len;
4452 const char *msg;
4453
4454 /* Get the message as the first argument on the stack. */
4455 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4456
4457 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004458 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004459
4460 /* if ret == -2 or -3 the channel closed or the message si too
4461 * big for the buffers.
4462 */
4463 if (ret == -2 || ret == -3) {
4464 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4465 WILL_LJMP(lua_error(L));
4466 }
4467
4468 /* If ret is -1, we dont have room in the buffer, so we yield. */
4469 if (ret == -1) {
4470 si_applet_cant_put(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004471 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004472 }
4473
4474 /* Headers sent, set the flag. */
4475 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4476 return 0;
4477}
4478
4479__LJMP static int hlua_applet_http_start_response(lua_State *L)
4480{
Willy Tarreau83061a82018-07-13 11:56:34 +02004481 struct buffer *tmp = get_trash_chunk();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004482 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004483 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02004484 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004485 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02004486 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004487 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004488 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004489 int hdr_chunked = 0;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004490 const char *reason = appctx->appctx->ctx.hlua_apphttp.reason;
4491
4492 if (reason == NULL)
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02004493 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004494
4495 /* Use the same http version than the request. */
4496 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004497 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004498 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004499 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004500
4501 /* Get the array associated to the field "response" in the object AppletHTTP. */
4502 lua_pushvalue(L, 0);
4503 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4504 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4505 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4506 WILL_LJMP(lua_error(L));
4507 }
4508
4509 /* Browse the list of headers. */
4510 lua_pushnil(L);
4511 while(lua_next(L, -2) != 0) {
4512
4513 /* We expect a string as -2. */
4514 if (lua_type(L, -2) != LUA_TSTRING) {
4515 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4516 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4517 lua_typename(L, lua_type(L, -2)));
4518 WILL_LJMP(lua_error(L));
4519 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004520 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004521
4522 /* We expect an array as -1. */
4523 if (lua_type(L, -1) != LUA_TTABLE) {
4524 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4525 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4526 name,
4527 lua_typename(L, lua_type(L, -1)));
4528 WILL_LJMP(lua_error(L));
4529 }
4530
4531 /* Browse the table who is on the top of the stack. */
4532 lua_pushnil(L);
4533 while(lua_next(L, -2) != 0) {
4534
4535 /* We expect a number as -2. */
4536 if (lua_type(L, -2) != LUA_TNUMBER) {
4537 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4538 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4539 name,
4540 lua_typename(L, lua_type(L, -2)));
4541 WILL_LJMP(lua_error(L));
4542 }
4543 id = lua_tointeger(L, -2);
4544
4545 /* We expect a string as -2. */
4546 if (lua_type(L, -1) != LUA_TSTRING) {
4547 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4548 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4549 name, id,
4550 lua_typename(L, lua_type(L, -1)));
4551 WILL_LJMP(lua_error(L));
4552 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004553 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004554
4555 /* Catenate a new header. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004556 if (tmp->data + name_len + 2 + value_len + 2 < tmp->size) {
4557 memcpy(tmp->area + tmp->data, name, name_len);
4558 tmp->data += name_len;
4559 tmp->area[tmp->data++] = ':';
4560 tmp->area[tmp->data++] = ' ';
Willy Tarreaua3294632017-08-23 11:24:47 +02004561
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004562 memcpy(tmp->area + tmp->data, value,
4563 value_len);
4564 tmp->data += value_len;
4565 tmp->area[tmp->data++] = '\r';
4566 tmp->area[tmp->data++] = '\n';
Willy Tarreaua3294632017-08-23 11:24:47 +02004567 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004568
4569 /* Protocol checks. */
4570
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004571 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004572 * is done without control. If it contains a bad value,
4573 * the content-length remains negative so that we can
4574 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004575 */
Willy Tarreaua3294632017-08-23 11:24:47 +02004576 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004577 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004578
4579 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004580 if (name_len == 17 && value_len == 7 &&
4581 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004582 strcasecmp("chunked", value) == 0)
4583 hdr_chunked = 1;
4584
4585 /* Remove the array from the stack, and get next element with a remaining string. */
4586 lua_pop(L, 1);
4587 }
4588
4589 /* Remove the array from the stack, and get next element with a remaining string. */
4590 lua_pop(L, 1);
4591 }
4592
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004593 /* If we dont have a content-length set, and the HTTP version is 1.1
4594 * and the status code implies the presence of a message body, we must
4595 * announce a transfer encoding chunked. This is required by haproxy
4596 * for the keepalive compliance. If the applet annouces a transfer-encoding
4597 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004598 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004599 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004600 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
4601 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4602 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4603 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004604 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4605 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4606 }
4607
4608 /* Finalize headers. */
4609 chunk_appendf(tmp, "\r\n");
4610
4611 /* Remove the last entry and the array of headers */
4612 lua_pop(L, 2);
4613
4614 /* Push the headers block. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004615 lua_pushlstring(L, tmp->area, tmp->data);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004616
4617 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4618}
4619
4620/*
4621 *
4622 *
4623 * Class HTTP
4624 *
4625 *
4626 */
4627
4628/* Returns a struct hlua_txn if the stack entry "ud" is
4629 * a class stream, otherwise it throws an error.
4630 */
4631__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4632{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004633 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004634}
4635
4636/* This function creates and push in the stack a HTTP object
4637 * according with a current TXN.
4638 */
4639static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4640{
4641 struct hlua_txn *htxn;
4642
4643 /* Check stack size. */
4644 if (!lua_checkstack(L, 3))
4645 return 0;
4646
4647 /* Create the object: obj[0] = userdata.
4648 * Note that the base of the Converters object is the
4649 * same than the TXN object.
4650 */
4651 lua_newtable(L);
4652 htxn = lua_newuserdata(L, sizeof(*htxn));
4653 lua_rawseti(L, -2, 0);
4654
4655 htxn->s = txn->s;
4656 htxn->p = txn->p;
4657
4658 /* Pop a class stream metatable and affect it to the table. */
4659 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4660 lua_setmetatable(L, -2);
4661
4662 return 1;
4663}
4664
4665/* This function creates ans returns an array of HTTP headers.
4666 * This function does not fails. It is used as wrapper with the
4667 * 2 following functions.
4668 */
4669__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4670{
4671 const char *cur_ptr, *cur_next, *p;
4672 int old_idx, cur_idx;
4673 struct hdr_idx_elem *cur_hdr;
4674 const char *hn, *hv;
4675 int hnl, hvl;
4676 int type;
4677 const char *in;
4678 char *out;
4679 int len;
4680
4681 /* Create the table. */
4682 lua_newtable(L);
4683
4684 if (!htxn->s->txn)
4685 return 1;
4686
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004687 /* Check if a valid response is parsed */
4688 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4689 return 1;
4690
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004691 /* Build array of headers. */
4692 old_idx = 0;
Willy Tarreaua79021a2018-06-15 18:07:57 +02004693 cur_next = ci_head(msg->chn) + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004694
4695 while (1) {
4696 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4697 if (!cur_idx)
4698 break;
4699 old_idx = cur_idx;
4700
4701 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4702 cur_ptr = cur_next;
4703 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4704
4705 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4706 * and the next header starts at cur_next. We'll check
4707 * this header in the list as well as against the default
4708 * rule.
4709 */
4710
4711 /* look for ': *'. */
4712 hn = cur_ptr;
4713 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4714 if (p >= cur_ptr+cur_hdr->len)
4715 continue;
4716 hnl = p - hn;
4717 p++;
4718 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4719 p++;
4720 if (p >= cur_ptr+cur_hdr->len)
4721 continue;
4722 hv = p;
4723 hvl = cur_ptr+cur_hdr->len-p;
4724
4725 /* Lowercase the key. Don't check the size of trash, it have
4726 * the size of one buffer and the input data contains in one
4727 * buffer.
4728 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004729 out = trash.area;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004730 for (in=hn; in<hn+hnl; in++, out++)
4731 *out = tolower(*in);
4732 *out = '\0';
4733
4734 /* Check for existing entry:
4735 * assume that the table is on the top of the stack, and
4736 * push the key in the stack, the function lua_gettable()
4737 * perform the lookup.
4738 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004739 lua_pushlstring(L, trash.area, hnl);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004740 lua_gettable(L, -2);
4741 type = lua_type(L, -1);
4742
4743 switch (type) {
4744 case LUA_TNIL:
4745 /* Table not found, create it. */
4746 lua_pop(L, 1); /* remove the nil value. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004747 lua_pushlstring(L, trash.area, hnl); /* push the header name as key. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004748 lua_newtable(L); /* create and push empty table. */
4749 lua_pushlstring(L, hv, hvl); /* push header value. */
4750 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4751 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4752 break;
4753
4754 case LUA_TTABLE:
4755 /* Entry found: push the value in the table. */
4756 len = lua_rawlen(L, -1);
4757 lua_pushlstring(L, hv, hvl); /* push header value. */
4758 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4759 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4760 break;
4761
4762 default:
4763 /* Other cases are errors. */
4764 hlua_pusherror(L, "internal error during the parsing of headers.");
4765 WILL_LJMP(lua_error(L));
4766 }
4767 }
4768
4769 return 1;
4770}
4771
4772__LJMP static int hlua_http_req_get_headers(lua_State *L)
4773{
4774 struct hlua_txn *htxn;
4775
4776 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4777 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4778
4779 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4780}
4781
4782__LJMP static int hlua_http_res_get_headers(lua_State *L)
4783{
4784 struct hlua_txn *htxn;
4785
4786 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4787 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4788
4789 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4790}
4791
4792/* This function replace full header, or just a value in
4793 * the request or in the response. It is a wrapper fir the
4794 * 4 following functions.
4795 */
4796__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4797 struct http_msg *msg, int action)
4798{
4799 size_t name_len;
4800 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4801 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4802 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4803 struct my_regex re;
4804
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004805 /* Check if a valid response is parsed */
4806 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4807 return 0;
4808
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004809 if (!regex_comp(reg, &re, 1, 1, NULL))
4810 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4811
4812 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4813 regex_free(&re);
4814 return 0;
4815}
4816
4817__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4818{
4819 struct hlua_txn *htxn;
4820
4821 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4822 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4823
4824 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4825}
4826
4827__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4828{
4829 struct hlua_txn *htxn;
4830
4831 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4832 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4833
4834 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4835}
4836
4837__LJMP static int hlua_http_req_rep_val(lua_State *L)
4838{
4839 struct hlua_txn *htxn;
4840
4841 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4842 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4843
4844 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4845}
4846
4847__LJMP static int hlua_http_res_rep_val(lua_State *L)
4848{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004849 struct hlua_txn *htxn;
4850
4851 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4852 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4853
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004854 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004855}
4856
4857/* This function deletes all the occurences of an header.
4858 * It is a wrapper for the 2 following functions.
4859 */
4860__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4861{
4862 size_t len;
4863 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4864 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004865 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004866
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004867 /* Check if a valid response is parsed */
4868 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4869 return 0;
4870
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004871 ctx.idx = 0;
Willy Tarreaua79021a2018-06-15 18:07:57 +02004872 while (http_find_header2(name, len, ci_head(msg->chn), &txn->hdr_idx, &ctx))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004873 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4874 return 0;
4875}
4876
4877__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4878{
4879 struct hlua_txn *htxn;
4880
4881 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4882 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4883
Willy Tarreaueee5b512015-04-03 23:46:31 +02004884 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004885}
4886
4887__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4888{
4889 struct hlua_txn *htxn;
4890
4891 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4892 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4893
Willy Tarreaueee5b512015-04-03 23:46:31 +02004894 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004895}
4896
4897/* This function adds an header. It is a wrapper used by
4898 * the 2 following functions.
4899 */
4900__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4901{
4902 size_t name_len;
4903 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4904 size_t value_len;
4905 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4906 char *p;
4907
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004908 /* Check if a valid message is parsed */
4909 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4910 return 0;
4911
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004912 /* Check length. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004913 trash.data = value_len + name_len + 2;
4914 if (trash.data > trash.size)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004915 return 0;
4916
4917 /* Creates the header string. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004918 p = trash.area;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004919 memcpy(p, name, name_len);
4920 p += name_len;
4921 *p = ':';
4922 p++;
4923 *p = ' ';
4924 p++;
4925 memcpy(p, value, value_len);
4926
Willy Tarreaueee5b512015-04-03 23:46:31 +02004927 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004928 trash.area, trash.data) != 0);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004929
4930 return 0;
4931}
4932
4933__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4934{
4935 struct hlua_txn *htxn;
4936
4937 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4938 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4939
Willy Tarreaueee5b512015-04-03 23:46:31 +02004940 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004941}
4942
4943__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4944{
4945 struct hlua_txn *htxn;
4946
4947 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4948 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4949
Willy Tarreaueee5b512015-04-03 23:46:31 +02004950 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004951}
4952
4953static int hlua_http_req_set_hdr(lua_State *L)
4954{
4955 struct hlua_txn *htxn;
4956
4957 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4958 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4959
Willy Tarreaueee5b512015-04-03 23:46:31 +02004960 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4961 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004962}
4963
4964static int hlua_http_res_set_hdr(lua_State *L)
4965{
4966 struct hlua_txn *htxn;
4967
4968 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4969 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4970
Willy Tarreaueee5b512015-04-03 23:46:31 +02004971 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4972 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004973}
4974
4975/* This function set the method. */
4976static int hlua_http_req_set_meth(lua_State *L)
4977{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004978 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004979 size_t name_len;
4980 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004981
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004982 /* Check if a valid request is parsed */
4983 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4984 lua_pushboolean(L, 0);
4985 return 1;
4986 }
4987
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004988 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004989 return 1;
4990}
4991
4992/* This function set the method. */
4993static int hlua_http_req_set_path(lua_State *L)
4994{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004995 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004996 size_t name_len;
4997 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004998
4999 /* Check if a valid request is parsed */
5000 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
5001 lua_pushboolean(L, 0);
5002 return 1;
5003 }
5004
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005005 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005006 return 1;
5007}
5008
5009/* This function set the query-string. */
5010static int hlua_http_req_set_query(lua_State *L)
5011{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005012 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005013 size_t name_len;
5014 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005015
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005016 /* Check if a valid request is parsed */
5017 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
5018 lua_pushboolean(L, 0);
5019 return 1;
5020 }
5021
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005022 /* Check length. */
5023 if (name_len > trash.size - 1) {
5024 lua_pushboolean(L, 0);
5025 return 1;
5026 }
5027
5028 /* Add the mark question as prefix. */
5029 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005030 trash.area[trash.data++] = '?';
5031 memcpy(trash.area + trash.data, name, name_len);
5032 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005033
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005034 lua_pushboolean(L,
5035 http_replace_req_line(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005036 return 1;
5037}
5038
5039/* This function set the uri. */
5040static int hlua_http_req_set_uri(lua_State *L)
5041{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005042 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005043 size_t name_len;
5044 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005045
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005046 /* Check if a valid request is parsed */
5047 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
5048 lua_pushboolean(L, 0);
5049 return 1;
5050 }
5051
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005052 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005053 return 1;
5054}
5055
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005056/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005057static int hlua_http_res_set_status(lua_State *L)
5058{
5059 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5060 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005061 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005062
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005063 /* Check if a valid response is parsed */
5064 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
5065 return 0;
5066
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005067 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005068 return 0;
5069}
5070
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005071/*
5072 *
5073 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005074 * Class TXN
5075 *
5076 *
5077 */
5078
5079/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005080 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005081 */
5082__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5083{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005084 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005085}
5086
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005087__LJMP static int hlua_set_var(lua_State *L)
5088{
5089 struct hlua_txn *htxn;
5090 const char *name;
5091 size_t len;
5092 struct sample smp;
5093
5094 MAY_LJMP(check_args(L, 3, "set_var"));
5095
5096 /* It is useles to retrieve the stream, but this function
5097 * runs only in a stream context.
5098 */
5099 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5100 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5101
5102 /* Converts the third argument in a sample. */
5103 hlua_lua2smp(L, 3, &smp);
5104
5105 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005106 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005107 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005108 return 0;
5109}
5110
Christopher Faulet85d79c92016-11-09 16:54:56 +01005111__LJMP static int hlua_unset_var(lua_State *L)
5112{
5113 struct hlua_txn *htxn;
5114 const char *name;
5115 size_t len;
5116 struct sample smp;
5117
5118 MAY_LJMP(check_args(L, 2, "unset_var"));
5119
5120 /* It is useles to retrieve the stream, but this function
5121 * runs only in a stream context.
5122 */
5123 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5124 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5125
5126 /* Unset the variable. */
5127 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5128 vars_unset_by_name(name, len, &smp);
5129 return 0;
5130}
5131
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005132__LJMP static int hlua_get_var(lua_State *L)
5133{
5134 struct hlua_txn *htxn;
5135 const char *name;
5136 size_t len;
5137 struct sample smp;
5138
5139 MAY_LJMP(check_args(L, 2, "get_var"));
5140
5141 /* It is useles to retrieve the stream, but this function
5142 * runs only in a stream context.
5143 */
5144 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5145 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5146
Willy Tarreau7560dd42016-03-10 16:28:58 +01005147 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005148 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005149 lua_pushnil(L);
5150 return 1;
5151 }
5152
5153 return hlua_smp2lua(L, &smp);
5154}
5155
Willy Tarreau59551662015-03-10 14:23:13 +01005156__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005157{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005158 struct hlua *hlua;
5159
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005160 MAY_LJMP(check_args(L, 2, "set_priv"));
5161
Willy Tarreau87b09662015-04-03 00:22:06 +02005162 /* It is useles to retrieve the stream, but this function
5163 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005164 */
5165 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005166 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005167
5168 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005169 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005170
5171 /* Get and store new value. */
5172 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5173 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5174
5175 return 0;
5176}
5177
Willy Tarreau59551662015-03-10 14:23:13 +01005178__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005179{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005180 struct hlua *hlua;
5181
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005182 MAY_LJMP(check_args(L, 1, "get_priv"));
5183
Willy Tarreau87b09662015-04-03 00:22:06 +02005184 /* It is useles to retrieve the stream, but this function
5185 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005186 */
5187 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005188 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005189
5190 /* Push configuration index in the stack. */
5191 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5192
5193 return 1;
5194}
5195
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005196/* Create stack entry containing a class TXN. This function
5197 * return 0 if the stack does not contains free slots,
5198 * otherwise it returns 1.
5199 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005200static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005201{
Willy Tarreaude491382015-04-06 11:04:28 +02005202 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005203
5204 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005205 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005206 return 0;
5207
5208 /* NOTE: The allocation never fails. The failure
5209 * throw an error, and the function never returns.
5210 * if the throw is not avalaible, the process is aborted.
5211 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005212 /* Create the object: obj[0] = userdata. */
5213 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005214 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005215 lua_rawseti(L, -2, 0);
5216
Willy Tarreaude491382015-04-06 11:04:28 +02005217 htxn->s = s;
5218 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005219 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005220 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005221
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005222 /* Create the "f" field that contains a list of fetches. */
5223 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005224 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005225 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005226 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005227
5228 /* Create the "sf" field that contains a list of stringsafe fetches. */
5229 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005230 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005231 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005232 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005233
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005234 /* Create the "c" field that contains a list of converters. */
5235 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005236 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005237 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005238 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005239
5240 /* Create the "sc" field that contains a list of stringsafe converters. */
5241 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005242 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005243 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005244 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005245
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005246 /* Create the "req" field that contains the request channel object. */
5247 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005248 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005249 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005250 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005251
5252 /* Create the "res" field that contains the response channel object. */
5253 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005254 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005255 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005256 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005257
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005258 /* Creates the HTTP object is the current proxy allows http. */
5259 lua_pushstring(L, "http");
5260 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005261 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005262 return 0;
5263 }
5264 else
5265 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005266 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005267
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005268 /* Pop a class sesison metatable and affect it to the userdata. */
5269 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5270 lua_setmetatable(L, -2);
5271
5272 return 1;
5273}
5274
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005275__LJMP static int hlua_txn_deflog(lua_State *L)
5276{
5277 const char *msg;
5278 struct hlua_txn *htxn;
5279
5280 MAY_LJMP(check_args(L, 2, "deflog"));
5281 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5282 msg = MAY_LJMP(luaL_checkstring(L, 2));
5283
5284 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5285 return 0;
5286}
5287
5288__LJMP static int hlua_txn_log(lua_State *L)
5289{
5290 int level;
5291 const char *msg;
5292 struct hlua_txn *htxn;
5293
5294 MAY_LJMP(check_args(L, 3, "log"));
5295 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5296 level = MAY_LJMP(luaL_checkinteger(L, 2));
5297 msg = MAY_LJMP(luaL_checkstring(L, 3));
5298
5299 if (level < 0 || level >= NB_LOG_LEVELS)
5300 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5301
5302 hlua_sendlog(htxn->s->be, level, msg);
5303 return 0;
5304}
5305
5306__LJMP static int hlua_txn_log_debug(lua_State *L)
5307{
5308 const char *msg;
5309 struct hlua_txn *htxn;
5310
5311 MAY_LJMP(check_args(L, 2, "Debug"));
5312 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5313 msg = MAY_LJMP(luaL_checkstring(L, 2));
5314 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5315 return 0;
5316}
5317
5318__LJMP static int hlua_txn_log_info(lua_State *L)
5319{
5320 const char *msg;
5321 struct hlua_txn *htxn;
5322
5323 MAY_LJMP(check_args(L, 2, "Info"));
5324 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5325 msg = MAY_LJMP(luaL_checkstring(L, 2));
5326 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5327 return 0;
5328}
5329
5330__LJMP static int hlua_txn_log_warning(lua_State *L)
5331{
5332 const char *msg;
5333 struct hlua_txn *htxn;
5334
5335 MAY_LJMP(check_args(L, 2, "Warning"));
5336 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5337 msg = MAY_LJMP(luaL_checkstring(L, 2));
5338 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5339 return 0;
5340}
5341
5342__LJMP static int hlua_txn_log_alert(lua_State *L)
5343{
5344 const char *msg;
5345 struct hlua_txn *htxn;
5346
5347 MAY_LJMP(check_args(L, 2, "Alert"));
5348 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5349 msg = MAY_LJMP(luaL_checkstring(L, 2));
5350 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5351 return 0;
5352}
5353
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005354__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5355{
5356 struct hlua_txn *htxn;
5357 int ll;
5358
5359 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5360 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5361 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5362
5363 if (ll < 0 || ll > 7)
5364 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5365
5366 htxn->s->logs.level = ll;
5367 return 0;
5368}
5369
5370__LJMP static int hlua_txn_set_tos(lua_State *L)
5371{
5372 struct hlua_txn *htxn;
5373 struct connection *cli_conn;
5374 int tos;
5375
5376 MAY_LJMP(check_args(L, 2, "set_tos"));
5377 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5378 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5379
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005380 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005381 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005382
5383 return 0;
5384}
5385
5386__LJMP static int hlua_txn_set_mark(lua_State *L)
5387{
5388#ifdef SO_MARK
5389 struct hlua_txn *htxn;
5390 struct connection *cli_conn;
5391 int mark;
5392
5393 MAY_LJMP(check_args(L, 2, "set_mark"));
5394 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5395 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5396
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005397 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005398 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005399#endif
5400 return 0;
5401}
5402
Patrick Hemmer268a7072018-05-11 12:52:31 -04005403__LJMP static int hlua_txn_set_priority_class(lua_State *L)
5404{
5405 struct hlua_txn *htxn;
5406
5407 MAY_LJMP(check_args(L, 2, "set_priority_class"));
5408 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5409 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
5410 return 0;
5411}
5412
5413__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
5414{
5415 struct hlua_txn *htxn;
5416
5417 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
5418 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5419 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
5420 return 0;
5421}
5422
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005423/* This function is an Lua binding that send pending data
5424 * to the client, and close the stream interface.
5425 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005426__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005427{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005428 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005429 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005430 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005431
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005432 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005433 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005434 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005435
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005436 /* If the flags NOTERM is set, we cannot terminate the http
5437 * session, so we just end the execution of the current
5438 * lua code.
5439 */
5440 if (htxn->flags & HLUA_TXN_NOTERM) {
5441 WILL_LJMP(hlua_done(L));
5442 return 0;
5443 }
5444
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005445 ic = &htxn->s->req;
5446 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005447
Willy Tarreau630ef452015-08-28 10:06:15 +02005448 if (htxn->s->txn) {
5449 /* HTTP mode, let's stay in sync with the stream */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02005450 b_del(&ic->buf, htxn->s->txn->req.sov);
Willy Tarreau630ef452015-08-28 10:06:15 +02005451 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5452 htxn->s->txn->req.sov = 0;
5453 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5454 oc->analysers = AN_RES_HTTP_XFER_BODY;
5455 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5456 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5457
Willy Tarreau630ef452015-08-28 10:06:15 +02005458 /* Note that if we want to support keep-alive, we need
5459 * to bypass the close/shutr_now calls below, but that
5460 * may only be done if the HTTP request was already
5461 * processed and the connection header is known (ie
5462 * not during TCP rules).
5463 */
5464 }
5465
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005466 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005467 channel_abort(ic);
5468 channel_auto_close(ic);
5469 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005470
5471 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005472 channel_auto_read(oc);
5473 channel_auto_close(oc);
5474 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005475
Willy Tarreau0458b082015-08-28 09:40:04 +02005476 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005477
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005478 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005479 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005480 return 0;
5481}
5482
5483__LJMP static int hlua_log(lua_State *L)
5484{
5485 int level;
5486 const char *msg;
5487
5488 MAY_LJMP(check_args(L, 2, "log"));
5489 level = MAY_LJMP(luaL_checkinteger(L, 1));
5490 msg = MAY_LJMP(luaL_checkstring(L, 2));
5491
5492 if (level < 0 || level >= NB_LOG_LEVELS)
5493 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5494
5495 hlua_sendlog(NULL, level, msg);
5496 return 0;
5497}
5498
5499__LJMP static int hlua_log_debug(lua_State *L)
5500{
5501 const char *msg;
5502
5503 MAY_LJMP(check_args(L, 1, "debug"));
5504 msg = MAY_LJMP(luaL_checkstring(L, 1));
5505 hlua_sendlog(NULL, LOG_DEBUG, msg);
5506 return 0;
5507}
5508
5509__LJMP static int hlua_log_info(lua_State *L)
5510{
5511 const char *msg;
5512
5513 MAY_LJMP(check_args(L, 1, "info"));
5514 msg = MAY_LJMP(luaL_checkstring(L, 1));
5515 hlua_sendlog(NULL, LOG_INFO, msg);
5516 return 0;
5517}
5518
5519__LJMP static int hlua_log_warning(lua_State *L)
5520{
5521 const char *msg;
5522
5523 MAY_LJMP(check_args(L, 1, "warning"));
5524 msg = MAY_LJMP(luaL_checkstring(L, 1));
5525 hlua_sendlog(NULL, LOG_WARNING, msg);
5526 return 0;
5527}
5528
5529__LJMP static int hlua_log_alert(lua_State *L)
5530{
5531 const char *msg;
5532
5533 MAY_LJMP(check_args(L, 1, "alert"));
5534 msg = MAY_LJMP(luaL_checkstring(L, 1));
5535 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005536 return 0;
5537}
5538
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005539__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005540{
5541 int wakeup_ms = lua_tointeger(L, -1);
5542 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02005543 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005544 return 0;
5545}
5546
5547__LJMP static int hlua_sleep(lua_State *L)
5548{
5549 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005550 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005551
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005552 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005553
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005554 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005555 wakeup_ms = tick_add(now_ms, delay);
5556 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005557
Willy Tarreau9635e032018-10-16 17:52:55 +02005558 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005559 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005560}
5561
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005562__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005563{
5564 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005565 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005566
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005567 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005568
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005569 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005570 wakeup_ms = tick_add(now_ms, delay);
5571 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005572
Willy Tarreau9635e032018-10-16 17:52:55 +02005573 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005574 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005575}
5576
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005577/* This functionis an LUA binding. it permits to give back
5578 * the hand at the HAProxy scheduler. It is used when the
5579 * LUA processing consumes a lot of time.
5580 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005581__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005582{
5583 return 0;
5584}
5585
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005586__LJMP static int hlua_yield(lua_State *L)
5587{
Willy Tarreau9635e032018-10-16 17:52:55 +02005588 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005589 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005590}
5591
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005592/* This function change the nice of the currently executed
5593 * task. It is used set low or high priority at the current
5594 * task.
5595 */
Willy Tarreau59551662015-03-10 14:23:13 +01005596__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005597{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005598 struct hlua *hlua;
5599 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005600
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005601 MAY_LJMP(check_args(L, 1, "set_nice"));
5602 hlua = hlua_gethlua(L);
5603 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005604
5605 /* If he task is not set, I'm in a start mode. */
5606 if (!hlua || !hlua->task)
5607 return 0;
5608
5609 if (nice < -1024)
5610 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005611 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005612 nice = 1024;
5613
5614 hlua->task->nice = nice;
5615 return 0;
5616}
5617
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005618/* This function is used as a calback of a task. It is called by the
5619 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5620 * return an E_AGAIN signal, the emmiter of this signal must set a
5621 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005622 *
5623 * Task wrapper are longjmp safe because the only one Lua code
5624 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005625 */
Olivier Houchard9f6af332018-05-25 14:04:04 +02005626static struct task *hlua_process_task(struct task *task, void *context, unsigned short state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005627{
Olivier Houchard9f6af332018-05-25 14:04:04 +02005628 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005629 enum hlua_exec status;
5630
Christopher Faulet5bc99722018-04-25 10:34:45 +02005631 if (task->thread_mask == MAX_THREADS_MASK)
5632 task_set_affinity(task, tid_bit);
5633
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005634 /* If it is the first call to the task, we must initialize the
5635 * execution timeouts.
5636 */
5637 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005638 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005639
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005640 /* Execute the Lua code. */
5641 status = hlua_ctx_resume(hlua, 1);
5642
5643 switch (status) {
5644 /* finished or yield */
5645 case HLUA_E_OK:
5646 hlua_ctx_destroy(hlua);
5647 task_delete(task);
5648 task_free(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02005649 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005650 break;
5651
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005652 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01005653 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02005654 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005655 break;
5656
5657 /* finished with error. */
5658 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005659 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005660 hlua_ctx_destroy(hlua);
5661 task_delete(task);
5662 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005663 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005664 break;
5665
5666 case HLUA_E_ERR:
5667 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005668 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005669 hlua_ctx_destroy(hlua);
5670 task_delete(task);
5671 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005672 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005673 break;
5674 }
Emeric Brun253e53e2017-10-17 18:58:40 +02005675 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005676}
5677
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005678/* This function is an LUA binding that register LUA function to be
5679 * executed after the HAProxy configuration parsing and before the
5680 * HAProxy scheduler starts. This function expect only one LUA
5681 * argument that is a function. This function returns nothing, but
5682 * throws if an error is encountered.
5683 */
5684__LJMP static int hlua_register_init(lua_State *L)
5685{
5686 struct hlua_init_function *init;
5687 int ref;
5688
5689 MAY_LJMP(check_args(L, 1, "register_init"));
5690
5691 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5692
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005693 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005694 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005695 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005696
5697 init->function_ref = ref;
5698 LIST_ADDQ(&hlua_init_functions, &init->l);
5699 return 0;
5700}
5701
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005702/* This functio is an LUA binding. It permits to register a task
5703 * executed in parallel of the main HAroxy activity. The task is
5704 * created and it is set in the HAProxy scheduler. It can be called
5705 * from the "init" section, "post init" or during the runtime.
5706 *
5707 * Lua prototype:
5708 *
5709 * <none> core.register_task(<function>)
5710 */
5711static int hlua_register_task(lua_State *L)
5712{
5713 struct hlua *hlua;
5714 struct task *task;
5715 int ref;
5716
5717 MAY_LJMP(check_args(L, 1, "register_task"));
5718
5719 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5720
Willy Tarreaubafbe012017-11-24 17:34:44 +01005721 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005722 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005723 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005724
Emeric Brunc60def82017-09-27 14:59:38 +02005725 task = task_new(MAX_THREADS_MASK);
Willy Tarreaue09101e2018-10-16 17:37:12 +02005726 if (!task)
5727 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
5728
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005729 task->context = hlua;
5730 task->process = hlua_process_task;
5731
5732 if (!hlua_ctx_init(hlua, task))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005733 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005734
5735 /* Restore the function in the stack. */
5736 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5737 hlua->nargs = 0;
5738
5739 /* Schedule task. */
5740 task_schedule(task, now_ms);
5741
5742 return 0;
5743}
5744
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005745/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5746 * doesn't allow "yield" functions because the HAProxy engine cannot
5747 * resume converters.
5748 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005749static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005750{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005751 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005752 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005753 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005754
Willy Tarreaube508f12016-03-10 11:47:01 +01005755 if (!stream)
5756 return 0;
5757
Willy Tarreau87b09662015-04-03 00:22:06 +02005758 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005759 * Lua context can be not initialized. This behavior
5760 * permits to save performances because a systematic
5761 * Lua initialization cause 5% performances loss.
5762 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005763 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005764 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005765 if (!stream->hlua) {
5766 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5767 return 0;
5768 }
5769 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5770 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5771 return 0;
5772 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005773 }
5774
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005775 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005776 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005777
5778 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005779 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5780 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5781 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005782 else
5783 error = "critical error";
5784 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005785 return 0;
5786 }
5787
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005788 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005789 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005790 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005791 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005792 return 0;
5793 }
5794
5795 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005796 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005797
5798 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005799 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005800 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005801 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005802 return 0;
5803 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005804 hlua_smp2lua(stream->hlua->T, smp);
5805 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005806
5807 /* push keywords in the stack. */
5808 if (arg_p) {
5809 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005810 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005811 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005812 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005813 return 0;
5814 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005815 hlua_arg2lua(stream->hlua->T, arg_p);
5816 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005817 }
5818 }
5819
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005820 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005821 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005822
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005823 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005824 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005825 }
5826
5827 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005828 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005829 /* finished. */
5830 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005831 /* If the stack is empty, the function fails. */
5832 if (lua_gettop(stream->hlua->T) <= 0)
5833 return 0;
5834
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005835 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005836 hlua_lua2smp(stream->hlua->T, -1, smp);
5837 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005838 return 1;
5839
5840 /* yield. */
5841 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005842 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005843 return 0;
5844
5845 /* finished with error. */
5846 case HLUA_E_ERRMSG:
5847 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005848 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005849 fcn->name, lua_tostring(stream->hlua->T, -1));
5850 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005851 return 0;
5852
Thierry Fournierd5b073c2018-05-21 19:42:47 +02005853 case HLUA_E_ETMOUT:
5854 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
5855 return 0;
5856
5857 case HLUA_E_NOMEM:
5858 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
5859 return 0;
5860
5861 case HLUA_E_YIELD:
5862 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
5863 return 0;
5864
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005865 case HLUA_E_ERR:
5866 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005867 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005868
5869 default:
5870 return 0;
5871 }
5872}
5873
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005874/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5875 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005876 * resume sample-fetches. This function will be called by the sample
5877 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005878 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005879static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5880 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005881{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005882 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005883 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005884 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02005885 const struct buffer msg = { };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005886
Willy Tarreaube508f12016-03-10 11:47:01 +01005887 if (!stream)
5888 return 0;
5889
Willy Tarreau87b09662015-04-03 00:22:06 +02005890 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005891 * Lua context can be not initialized. This behavior
5892 * permits to save performances because a systematic
5893 * Lua initialization cause 5% performances loss.
5894 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005895 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005896 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005897 if (!stream->hlua) {
5898 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5899 return 0;
5900 }
5901 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5902 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5903 return 0;
5904 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005905 }
5906
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005907 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005908
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005909 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005910 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005911
5912 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005913 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5914 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5915 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005916 else
5917 error = "critical error";
5918 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005919 return 0;
5920 }
5921
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005922 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005923 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005924 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005925 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005926 return 0;
5927 }
5928
5929 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005930 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005931
5932 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005933 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005934 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005935 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005936 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005937 return 0;
5938 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005939 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005940
5941 /* push keywords in the stack. */
5942 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5943 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005944 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005945 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005946 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005947 return 0;
5948 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005949 hlua_arg2lua(stream->hlua->T, arg_p);
5950 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005951 }
5952
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005953 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005954 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005955
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005956 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005957 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005958 }
5959
5960 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005961 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005962 /* finished. */
5963 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005964 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005965 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005966 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005967 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005968 /* If the stack is empty, the function fails. */
5969 if (lua_gettop(stream->hlua->T) <= 0)
5970 return 0;
5971
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005972 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005973 hlua_lua2smp(stream->hlua->T, -1, smp);
5974 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005975
5976 /* Set the end of execution flag. */
5977 smp->flags &= ~SMP_F_MAY_CHANGE;
5978 return 1;
5979
5980 /* yield. */
5981 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005982 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005983 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005984 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005985 return 0;
5986
5987 /* finished with error. */
5988 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005989 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005990 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005991 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005992 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005993 fcn->name, lua_tostring(stream->hlua->T, -1));
5994 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005995 return 0;
5996
Thierry Fournierd5b073c2018-05-21 19:42:47 +02005997 case HLUA_E_ETMOUT:
5998 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
5999 stream_int_retnclose(&stream->si[0], &msg);
6000 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
6001 return 0;
6002
6003 case HLUA_E_NOMEM:
6004 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
6005 stream_int_retnclose(&stream->si[0], &msg);
6006 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
6007 return 0;
6008
6009 case HLUA_E_YIELD:
6010 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
6011 stream_int_retnclose(&stream->si[0], &msg);
6012 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
6013 return 0;
6014
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006015 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006016 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006017 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006018 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006019 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006020
6021 default:
6022 return 0;
6023 }
6024}
6025
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006026/* This function is an LUA binding used for registering
6027 * "sample-conv" functions. It expects a converter name used
6028 * in the haproxy configuration file, and an LUA function.
6029 */
6030__LJMP static int hlua_register_converters(lua_State *L)
6031{
6032 struct sample_conv_kw_list *sck;
6033 const char *name;
6034 int ref;
6035 int len;
6036 struct hlua_function *fcn;
6037
6038 MAY_LJMP(check_args(L, 2, "register_converters"));
6039
6040 /* First argument : converter name. */
6041 name = MAY_LJMP(luaL_checkstring(L, 1));
6042
6043 /* Second argument : lua function. */
6044 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6045
6046 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006047 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006048 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006049 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006050 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006051 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006052 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006053
6054 /* Fill fcn. */
6055 fcn->name = strdup(name);
6056 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006057 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006058 fcn->function_ref = ref;
6059
6060 /* List head */
6061 sck->list.n = sck->list.p = NULL;
6062
6063 /* converter keyword. */
6064 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006065 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006066 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006067 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006068
6069 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6070 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006071 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 +01006072 sck->kw[0].val_args = NULL;
6073 sck->kw[0].in_type = SMP_T_STR;
6074 sck->kw[0].out_type = SMP_T_STR;
6075 sck->kw[0].private = fcn;
6076
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006077 /* Register this new converter */
6078 sample_register_convs(sck);
6079
6080 return 0;
6081}
6082
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006083/* This fucntion is an LUA binding used for registering
6084 * "sample-fetch" functions. It expects a converter name used
6085 * in the haproxy configuration file, and an LUA function.
6086 */
6087__LJMP static int hlua_register_fetches(lua_State *L)
6088{
6089 const char *name;
6090 int ref;
6091 int len;
6092 struct sample_fetch_kw_list *sfk;
6093 struct hlua_function *fcn;
6094
6095 MAY_LJMP(check_args(L, 2, "register_fetches"));
6096
6097 /* First argument : sample-fetch name. */
6098 name = MAY_LJMP(luaL_checkstring(L, 1));
6099
6100 /* Second argument : lua function. */
6101 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6102
6103 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006104 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006105 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006106 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006107 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006108 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006109 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006110
6111 /* Fill fcn. */
6112 fcn->name = strdup(name);
6113 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006114 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006115 fcn->function_ref = ref;
6116
6117 /* List head */
6118 sfk->list.n = sfk->list.p = NULL;
6119
6120 /* sample-fetch keyword. */
6121 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006122 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006123 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006124 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006125
6126 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6127 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006128 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 +01006129 sfk->kw[0].val_args = NULL;
6130 sfk->kw[0].out_type = SMP_T_STR;
6131 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6132 sfk->kw[0].val = 0;
6133 sfk->kw[0].private = fcn;
6134
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006135 /* Register this new fetch. */
6136 sample_register_fetches(sfk);
6137
6138 return 0;
6139}
6140
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006141/* This function is a wrapper to execute each LUA function declared
6142 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006143 * return ACT_RET_CONT if the processing is finished (with or without
6144 * error) and return ACT_RET_YIELD if the function must be called again
6145 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006146 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006147static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006148 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006149{
6150 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006151 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006152 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006153 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006154 const struct buffer msg = { };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006155
6156 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01006157 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
6158 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
6159 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
6160 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006161 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006162 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006163 return ACT_RET_CONT;
6164 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006165
Willy Tarreau87b09662015-04-03 00:22:06 +02006166 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006167 * Lua context can be not initialized. This behavior
6168 * permits to save performances because a systematic
6169 * Lua initialization cause 5% performances loss.
6170 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006171 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006172 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006173 if (!s->hlua) {
6174 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6175 rule->arg.hlua_rule->fcn.name);
6176 return ACT_RET_CONT;
6177 }
6178 if (!hlua_ctx_init(s->hlua, s->task)) {
6179 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6180 rule->arg.hlua_rule->fcn.name);
6181 return ACT_RET_CONT;
6182 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006183 }
6184
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006185 consistency_set(s, dir, &s->hlua->cons);
6186
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006187 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006188 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006189
6190 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006191 if (!SET_SAFE_LJMP(s->hlua->T)) {
6192 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6193 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006194 else
6195 error = "critical error";
6196 SEND_ERR(px, "Lua function '%s': %s.\n",
6197 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006198 return ACT_RET_CONT;
6199 }
6200
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006201 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006202 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006203 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006204 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006205 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006206 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006207 }
6208
6209 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006210 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006211
Willy Tarreau87b09662015-04-03 00:22:06 +02006212 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006213 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006214 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006215 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006216 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006217 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006218 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006219 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006220
6221 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006222 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006223 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006224 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006225 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006226 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006227 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006228 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006229 lua_pushstring(s->hlua->T, *arg);
6230 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006231 }
6232
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006233 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006234 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006235
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006236 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006237 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006238 }
6239
6240 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006241 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006242 /* finished. */
6243 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006244 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006245 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006246 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006247 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006248 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006249 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006250 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006251
6252 /* yield. */
6253 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006254 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006255 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006256 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006257 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006258 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006259 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006260 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006261 /* Some actions can be wake up when a "write" event
6262 * is detected on a response channel. This is useful
6263 * only for actions targetted on the requests.
6264 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006265 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006266 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01006267 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006268 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006269 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006270 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006271 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006272 /* We can quit the fcuntion without consistency check
6273 * because HAProxy is not able to manipulate data, it
6274 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006275 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006276
6277 /* finished with error. */
6278 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006279 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006280 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006281 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006282 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006283 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006284 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006285 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6286 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006287 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006288
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006289 case HLUA_E_ETMOUT:
6290 if (!consistency_check(s, dir, &s->hlua->cons)) {
6291 stream_int_retnclose(&s->si[0], &msg);
6292 return ACT_RET_ERR;
6293 }
6294 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
6295 return 0;
6296
6297 case HLUA_E_NOMEM:
6298 if (!consistency_check(s, dir, &s->hlua->cons)) {
6299 stream_int_retnclose(&s->si[0], &msg);
6300 return ACT_RET_ERR;
6301 }
6302 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
6303 return 0;
6304
6305 case HLUA_E_YIELD:
6306 if (!consistency_check(s, dir, &s->hlua->cons)) {
6307 stream_int_retnclose(&s->si[0], &msg);
6308 return ACT_RET_ERR;
6309 }
6310 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6311 rule->arg.hlua_rule->fcn.name);
6312 return 0;
6313
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006314 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006315 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006316 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006317 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006318 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006319 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006320 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006321 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006322
6323 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006324 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006325 }
6326}
6327
Olivier Houchard9f6af332018-05-25 14:04:04 +02006328struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006329{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006330 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006331 struct stream_interface *si = ctx->owner;
6332
6333 /* If the applet is wake up without any expected work, the sheduler
6334 * remove it from the run queue. This flag indicate that the applet
6335 * is waiting for write. If the buffer is full, the main processing
6336 * will send some data and after call the applet, otherwise it call
6337 * the applet ASAP.
6338 */
6339 si_applet_cant_put(si);
6340 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006341 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006342 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006343}
6344
6345static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6346{
6347 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006348 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006349 struct task *task;
6350 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006351 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006352
Willy Tarreaubafbe012017-11-24 17:34:44 +01006353 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006354 if (!hlua) {
6355 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6356 ctx->rule->arg.hlua_rule->fcn.name);
6357 return 0;
6358 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006359 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006360 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006361 ctx->ctx.hlua_apptcp.flags = 0;
6362
6363 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006364 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006365 if (!task) {
6366 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6367 ctx->rule->arg.hlua_rule->fcn.name);
6368 return 0;
6369 }
6370 task->nice = 0;
6371 task->context = ctx;
6372 task->process = hlua_applet_wakeup;
6373 ctx->ctx.hlua_apptcp.task = task;
6374
6375 /* In the execution wrappers linked with a stream, the
6376 * Lua context can be not initialized. This behavior
6377 * permits to save performances because a systematic
6378 * Lua initialization cause 5% performances loss.
6379 */
6380 if (!hlua_ctx_init(hlua, task)) {
6381 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6382 ctx->rule->arg.hlua_rule->fcn.name);
6383 return 0;
6384 }
6385
6386 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006387 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006388
6389 /* The following Lua calls can fail. */
6390 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006391 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6392 error = lua_tostring(hlua->T, -1);
6393 else
6394 error = "critical error";
6395 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6396 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006397 return 0;
6398 }
6399
6400 /* Check stack available size. */
6401 if (!lua_checkstack(hlua->T, 1)) {
6402 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6403 ctx->rule->arg.hlua_rule->fcn.name);
6404 RESET_SAFE_LJMP(hlua->T);
6405 return 0;
6406 }
6407
6408 /* Restore the function in the stack. */
6409 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6410
6411 /* Create and and push object stream in the stack. */
6412 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6413 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6414 ctx->rule->arg.hlua_rule->fcn.name);
6415 RESET_SAFE_LJMP(hlua->T);
6416 return 0;
6417 }
6418 hlua->nargs = 1;
6419
6420 /* push keywords in the stack. */
6421 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6422 if (!lua_checkstack(hlua->T, 1)) {
6423 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6424 ctx->rule->arg.hlua_rule->fcn.name);
6425 RESET_SAFE_LJMP(hlua->T);
6426 return 0;
6427 }
6428 lua_pushstring(hlua->T, *arg);
6429 hlua->nargs++;
6430 }
6431
6432 RESET_SAFE_LJMP(hlua->T);
6433
6434 /* Wakeup the applet ASAP. */
6435 si_applet_cant_get(si);
6436 si_applet_cant_put(si);
6437
6438 return 1;
6439}
6440
6441static void hlua_applet_tcp_fct(struct appctx *ctx)
6442{
6443 struct stream_interface *si = ctx->owner;
6444 struct stream *strm = si_strm(si);
6445 struct channel *res = si_ic(si);
6446 struct act_rule *rule = ctx->rule;
6447 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006448 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006449
6450 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02006451 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
6452 /* eat the whole request */
6453 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006454 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02006455 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006456
6457 /* If the stream is disconnect or closed, ldo nothing. */
6458 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6459 return;
6460
6461 /* Execute the function. */
6462 switch (hlua_ctx_resume(hlua, 1)) {
6463 /* finished. */
6464 case HLUA_E_OK:
6465 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6466
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006467 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02006468 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006469 res->flags |= CF_READ_NULL;
6470 si_shutr(si);
6471 return;
6472
6473 /* yield. */
6474 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006475 if (hlua->wake_time != TICK_ETERNITY)
6476 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006477 return;
6478
6479 /* finished with error. */
6480 case HLUA_E_ERRMSG:
6481 /* Display log. */
6482 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6483 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6484 lua_pop(hlua->T, 1);
6485 goto error;
6486
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006487 case HLUA_E_ETMOUT:
6488 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
6489 rule->arg.hlua_rule->fcn.name);
6490 goto error;
6491
6492 case HLUA_E_NOMEM:
6493 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
6494 rule->arg.hlua_rule->fcn.name);
6495 goto error;
6496
6497 case HLUA_E_YIELD: /* unexpected */
6498 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
6499 rule->arg.hlua_rule->fcn.name);
6500 goto error;
6501
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006502 case HLUA_E_ERR:
6503 /* Display log. */
6504 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6505 rule->arg.hlua_rule->fcn.name);
6506 goto error;
6507
6508 default:
6509 goto error;
6510 }
6511
6512error:
6513
6514 /* For all other cases, just close the stream. */
6515 si_shutw(si);
6516 si_shutr(si);
6517 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6518}
6519
6520static void hlua_applet_tcp_release(struct appctx *ctx)
6521{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006522 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006523 task_free(ctx->ctx.hlua_apptcp.task);
6524 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006525 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006526 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006527}
6528
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006529/* The function returns 1 if the initialisation is complete, 0 if
6530 * an errors occurs and -1 if more data are required for initializing
6531 * the applet.
6532 */
6533static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6534{
6535 struct stream_interface *si = ctx->owner;
6536 struct channel *req = si_oc(si);
6537 struct http_msg *msg;
6538 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006539 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006540 char **arg;
6541 struct hdr_ctx hdr;
6542 struct task *task;
6543 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006544 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006545
6546 /* Wait for a full HTTP request. */
6547 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6548 if (smp.flags & SMP_F_MAY_CHANGE)
6549 return -1;
6550 return 0;
6551 }
6552 txn = strm->txn;
6553 msg = &txn->req;
6554
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006555 /* We want two things in HTTP mode :
6556 * - enforce server-close mode if we were in keep-alive, so that the
6557 * applet is released after each response ;
6558 * - enable request body transfer to the applet in order to resync
6559 * with the response body.
6560 */
6561 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6562 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006563
Willy Tarreaubafbe012017-11-24 17:34:44 +01006564 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006565 if (!hlua) {
6566 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6567 ctx->rule->arg.hlua_rule->fcn.name);
6568 return 0;
6569 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006570 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006571 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006572 ctx->ctx.hlua_apphttp.left_bytes = -1;
6573 ctx->ctx.hlua_apphttp.flags = 0;
6574
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006575 if (txn->req.flags & HTTP_MSGF_VER_11)
6576 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6577
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006578 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006579 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006580 if (!task) {
6581 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6582 ctx->rule->arg.hlua_rule->fcn.name);
6583 return 0;
6584 }
6585 task->nice = 0;
6586 task->context = ctx;
6587 task->process = hlua_applet_wakeup;
6588 ctx->ctx.hlua_apphttp.task = task;
6589
6590 /* In the execution wrappers linked with a stream, the
6591 * Lua context can be not initialized. This behavior
6592 * permits to save performances because a systematic
6593 * Lua initialization cause 5% performances loss.
6594 */
6595 if (!hlua_ctx_init(hlua, task)) {
6596 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6597 ctx->rule->arg.hlua_rule->fcn.name);
6598 return 0;
6599 }
6600
6601 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006602 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006603
6604 /* The following Lua calls can fail. */
6605 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006606 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6607 error = lua_tostring(hlua->T, -1);
6608 else
6609 error = "critical error";
6610 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6611 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006612 return 0;
6613 }
6614
6615 /* Check stack available size. */
6616 if (!lua_checkstack(hlua->T, 1)) {
6617 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6618 ctx->rule->arg.hlua_rule->fcn.name);
6619 RESET_SAFE_LJMP(hlua->T);
6620 return 0;
6621 }
6622
6623 /* Restore the function in the stack. */
6624 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6625
6626 /* Create and and push object stream in the stack. */
6627 if (!hlua_applet_http_new(hlua->T, ctx)) {
6628 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6629 ctx->rule->arg.hlua_rule->fcn.name);
6630 RESET_SAFE_LJMP(hlua->T);
6631 return 0;
6632 }
6633 hlua->nargs = 1;
6634
6635 /* Look for a 100-continue expected. */
6636 if (msg->flags & HTTP_MSGF_VER_11) {
6637 hdr.idx = 0;
Willy Tarreaua79021a2018-06-15 18:07:57 +02006638 if (http_find_header2("Expect", 6, ci_head(req), &txn->hdr_idx, &hdr) &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006639 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6640 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6641 }
6642
6643 /* push keywords in the stack. */
6644 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6645 if (!lua_checkstack(hlua->T, 1)) {
6646 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6647 ctx->rule->arg.hlua_rule->fcn.name);
6648 RESET_SAFE_LJMP(hlua->T);
6649 return 0;
6650 }
6651 lua_pushstring(hlua->T, *arg);
6652 hlua->nargs++;
6653 }
6654
6655 RESET_SAFE_LJMP(hlua->T);
6656
6657 /* Wakeup the applet when data is ready for read. */
6658 si_applet_cant_get(si);
6659
6660 return 1;
6661}
6662
6663static void hlua_applet_http_fct(struct appctx *ctx)
6664{
6665 struct stream_interface *si = ctx->owner;
6666 struct stream *strm = si_strm(si);
6667 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006668 struct act_rule *rule = ctx->rule;
6669 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006670 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Willy Tarreau206ba832018-06-14 15:27:31 +02006671 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02006672 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02006673 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02006674 size_t len2;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006675 int ret;
6676
6677 /* If the stream is disconnect or closed, ldo nothing. */
6678 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6679 return;
6680
6681 /* Set the currently running flag. */
6682 if (!HLUA_IS_RUNNING(hlua) &&
6683 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6684
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006685 /* Wait for full HTTP analysys. */
6686 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6687 si_applet_cant_get(si);
6688 return;
6689 }
6690
6691 /* Store the max amount of bytes that we can read. */
6692 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6693
6694 /* We need to flush the request header. This left the body
6695 * for the Lua.
6696 */
6697
6698 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006699 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006700 if (ret == -1)
6701 return;
6702
6703 /* No data available, ask for more data. */
6704 if (ret == 1)
6705 len2 = 0;
6706 if (ret == 0)
6707 len1 = 0;
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02006708 if (len1 + len2 < strm->txn->req.eoh + strm->txn->req.eol) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006709 si_applet_cant_get(si);
6710 return;
6711 }
6712
6713 /* skip the requests bytes. */
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02006714 co_skip(si_oc(si), strm->txn->req.eoh + strm->txn->req.eol);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006715 }
6716
6717 /* Executes The applet if it is not done. */
6718 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6719
6720 /* Execute the function. */
6721 switch (hlua_ctx_resume(hlua, 1)) {
6722 /* finished. */
6723 case HLUA_E_OK:
6724 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6725 break;
6726
6727 /* yield. */
6728 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006729 if (hlua->wake_time != TICK_ETERNITY)
6730 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006731 return;
6732
6733 /* finished with error. */
6734 case HLUA_E_ERRMSG:
6735 /* Display log. */
6736 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6737 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6738 lua_pop(hlua->T, 1);
6739 goto error;
6740
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006741 case HLUA_E_ETMOUT:
6742 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
6743 rule->arg.hlua_rule->fcn.name);
6744 goto error;
6745
6746 case HLUA_E_NOMEM:
6747 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
6748 rule->arg.hlua_rule->fcn.name);
6749 goto error;
6750
6751 case HLUA_E_YIELD: /* unexpected */
6752 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
6753 rule->arg.hlua_rule->fcn.name);
6754 goto error;
6755
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006756 case HLUA_E_ERR:
6757 /* Display log. */
6758 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6759 rule->arg.hlua_rule->fcn.name);
6760 goto error;
6761
6762 default:
6763 goto error;
6764 }
6765 }
6766
6767 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6768
6769 /* We must send the final chunk. */
6770 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6771 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6772
6773 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006774 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006775
6776 /* critical error. */
6777 if (ret == -2 || ret == -3) {
6778 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6779 rule->arg.hlua_rule->fcn.name);
6780 goto error;
6781 }
6782
6783 /* no enough space error. */
6784 if (ret == -1) {
6785 si_applet_cant_put(si);
6786 return;
6787 }
6788
6789 /* set the last chunk sent. */
6790 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6791 }
6792
6793 /* close the connection. */
6794
Frédéric Lécaille83ed5d52018-07-18 14:25:26 +02006795 /* status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006796 strm->txn->status = ctx->ctx.hlua_apphttp.status;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006797
6798 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02006799 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006800 res->flags |= CF_READ_NULL;
6801 si_shutr(si);
6802
6803 return;
6804 }
6805
6806error:
6807
6808 /* If we are in HTTP mode, and we are not send any
6809 * data, return a 500 server error in best effort:
6810 * if there are no room avalaible in the buffer,
6811 * just close the connection.
6812 */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006813 ci_putblk(res, error_500, strlen(error_500));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006814 if (!(strm->flags & SF_ERR_MASK))
6815 strm->flags |= SF_ERR_RESOURCE;
6816 si_shutw(si);
6817 si_shutr(si);
6818 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6819}
6820
6821static void hlua_applet_http_release(struct appctx *ctx)
6822{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006823 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006824 task_free(ctx->ctx.hlua_apphttp.task);
6825 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006826 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006827 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006828}
6829
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006830/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6831 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006832 *
6833 * This function can fail with an abort() due to an Lua critical error.
6834 * We are in the configuration parsing process of HAProxy, this abort() is
6835 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006836 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006837static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6838 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006839{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006840 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006841 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006842
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006843 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006844 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006845 if (!rule->arg.hlua_rule) {
6846 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006847 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006848 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006849
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006850 /* Memory for arguments. */
6851 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6852 if (!rule->arg.hlua_rule->args) {
6853 memprintf(err, "out of memory error");
6854 return ACT_RET_PRS_ERR;
6855 }
6856
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006857 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006858 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006859
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006860 /* Expect some arguments */
6861 for (i = 0; i < fcn->nargs; i++) {
6862 if (*args[i+1] == '\0') {
6863 memprintf(err, "expect %d arguments", fcn->nargs);
6864 return ACT_RET_PRS_ERR;
6865 }
6866 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6867 if (!rule->arg.hlua_rule->args[i]) {
6868 memprintf(err, "out of memory error");
6869 return ACT_RET_PRS_ERR;
6870 }
6871 (*cur_arg)++;
6872 }
6873 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006874
Thierry FOURNIER42148732015-09-02 17:17:33 +02006875 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006876 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006877 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006878}
6879
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006880static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6881 struct act_rule *rule, char **err)
6882{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006883 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006884
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006885 /* HTTP applets are forbidden in tcp-request rules.
6886 * HTTP applet request requires everything initilized by
6887 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6888 * The applet will be immediately initilized, but its before
6889 * the call of this analyzer.
6890 */
6891 if (rule->from != ACT_F_HTTP_REQ) {
6892 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6893 return ACT_RET_PRS_ERR;
6894 }
6895
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006896 /* Memory for the rule. */
6897 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6898 if (!rule->arg.hlua_rule) {
6899 memprintf(err, "out of memory error");
6900 return ACT_RET_PRS_ERR;
6901 }
6902
6903 /* Reference the Lua function and store the reference. */
6904 rule->arg.hlua_rule->fcn = *fcn;
6905
6906 /* TODO: later accept arguments. */
6907 rule->arg.hlua_rule->args = NULL;
6908
6909 /* Add applet pointer in the rule. */
6910 rule->applet.obj_type = OBJ_TYPE_APPLET;
6911 rule->applet.name = fcn->name;
6912 rule->applet.init = hlua_applet_http_init;
6913 rule->applet.fct = hlua_applet_http_fct;
6914 rule->applet.release = hlua_applet_http_release;
6915 rule->applet.timeout = hlua_timeout_applet;
6916
6917 return ACT_RET_PRS_OK;
6918}
6919
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006920/* This function is an LUA binding used for registering
6921 * "sample-conv" functions. It expects a converter name used
6922 * in the haproxy configuration file, and an LUA function.
6923 */
6924__LJMP static int hlua_register_action(lua_State *L)
6925{
6926 struct action_kw_list *akl;
6927 const char *name;
6928 int ref;
6929 int len;
6930 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006931 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006932
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006933 /* Initialise the number of expected arguments at 0. */
6934 nargs = 0;
6935
6936 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6937 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006938
6939 /* First argument : converter name. */
6940 name = MAY_LJMP(luaL_checkstring(L, 1));
6941
6942 /* Second argument : environment. */
6943 if (lua_type(L, 2) != LUA_TTABLE)
6944 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6945
6946 /* Third argument : lua function. */
6947 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6948
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006949 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6950 if (lua_gettop(L) >= 4)
6951 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6952
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006953 /* browse the second argulent as an array. */
6954 lua_pushnil(L);
6955 while (lua_next(L, 2) != 0) {
6956 if (lua_type(L, -1) != LUA_TSTRING)
6957 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6958
6959 /* Check required environment. Only accepted "http" or "tcp". */
6960 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006961 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006962 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006963 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006964 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006965 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006966 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006967
6968 /* Fill fcn. */
6969 fcn->name = strdup(name);
6970 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006971 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006972 fcn->function_ref = ref;
6973
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006974 /* Set the expected number od arguments. */
6975 fcn->nargs = nargs;
6976
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006977 /* List head */
6978 akl->list.n = akl->list.p = NULL;
6979
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006980 /* action keyword. */
6981 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006982 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006983 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006984 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006985
6986 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6987
6988 akl->kw[0].match_pfx = 0;
6989 akl->kw[0].private = fcn;
6990 akl->kw[0].parse = action_register_lua;
6991
6992 /* select the action registering point. */
6993 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6994 tcp_req_cont_keywords_register(akl);
6995 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6996 tcp_res_cont_keywords_register(akl);
6997 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6998 http_req_keywords_register(akl);
6999 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
7000 http_res_keywords_register(akl);
7001 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007002 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007003 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
7004 "are expected.", lua_tostring(L, -1)));
7005
7006 /* pop the environment string. */
7007 lua_pop(L, 1);
7008 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007009 return ACT_RET_PRS_OK;
7010}
7011
7012static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7013 struct act_rule *rule, char **err)
7014{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007015 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007016
7017 /* Memory for the rule. */
7018 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7019 if (!rule->arg.hlua_rule) {
7020 memprintf(err, "out of memory error");
7021 return ACT_RET_PRS_ERR;
7022 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007023
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007024 /* Reference the Lua function and store the reference. */
7025 rule->arg.hlua_rule->fcn = *fcn;
7026
7027 /* TODO: later accept arguments. */
7028 rule->arg.hlua_rule->args = NULL;
7029
7030 /* Add applet pointer in the rule. */
7031 rule->applet.obj_type = OBJ_TYPE_APPLET;
7032 rule->applet.name = fcn->name;
7033 rule->applet.init = hlua_applet_tcp_init;
7034 rule->applet.fct = hlua_applet_tcp_fct;
7035 rule->applet.release = hlua_applet_tcp_release;
7036 rule->applet.timeout = hlua_timeout_applet;
7037
7038 return 0;
7039}
7040
7041/* This function is an LUA binding used for registering
7042 * "sample-conv" functions. It expects a converter name used
7043 * in the haproxy configuration file, and an LUA function.
7044 */
7045__LJMP static int hlua_register_service(lua_State *L)
7046{
7047 struct action_kw_list *akl;
7048 const char *name;
7049 const char *env;
7050 int ref;
7051 int len;
7052 struct hlua_function *fcn;
7053
7054 MAY_LJMP(check_args(L, 3, "register_service"));
7055
7056 /* First argument : converter name. */
7057 name = MAY_LJMP(luaL_checkstring(L, 1));
7058
7059 /* Second argument : environment. */
7060 env = MAY_LJMP(luaL_checkstring(L, 2));
7061
7062 /* Third argument : lua function. */
7063 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7064
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007065 /* Allocate and fill the sample fetch keyword struct. */
7066 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7067 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007068 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007069 fcn = calloc(1, sizeof(*fcn));
7070 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007071 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007072
7073 /* Fill fcn. */
7074 len = strlen("<lua.>") + strlen(name) + 1;
7075 fcn->name = calloc(1, len);
7076 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007077 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007078 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7079 fcn->function_ref = ref;
7080
7081 /* List head */
7082 akl->list.n = akl->list.p = NULL;
7083
7084 /* converter keyword. */
7085 len = strlen("lua.") + strlen(name) + 1;
7086 akl->kw[0].kw = calloc(1, len);
7087 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007088 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007089
7090 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7091
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007092 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007093 if (strcmp(env, "tcp") == 0)
7094 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007095 else if (strcmp(env, "http") == 0)
7096 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007097 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007098 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007099 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007100
7101 akl->kw[0].match_pfx = 0;
7102 akl->kw[0].private = fcn;
7103
7104 /* End of array. */
7105 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7106
7107 /* Register this new converter */
7108 service_keywords_register(akl);
7109
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007110 return 0;
7111}
7112
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007113/* This function initialises Lua cli handler. It copies the
7114 * arguments in the Lua stack and create channel IO objects.
7115 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007116static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007117{
7118 struct hlua *hlua;
7119 struct hlua_function *fcn;
7120 int i;
7121 const char *error;
7122
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007123 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007124 appctx->ctx.hlua_cli.fcn = private;
7125
Willy Tarreaubafbe012017-11-24 17:34:44 +01007126 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007127 if (!hlua) {
7128 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007129 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007130 }
7131 HLUA_INIT(hlua);
7132 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007133
7134 /* Create task used by signal to wakeup applets.
7135 * We use the same wakeup fonction than the Lua applet_tcp and
7136 * applet_http. It is absolutely compatible.
7137 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007138 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007139 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007140 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007141 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007142 }
7143 appctx->ctx.hlua_cli.task->nice = 0;
7144 appctx->ctx.hlua_cli.task->context = appctx;
7145 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7146
7147 /* Initialises the Lua context */
7148 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
7149 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007150 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007151 }
7152
7153 /* The following Lua calls can fail. */
7154 if (!SET_SAFE_LJMP(hlua->T)) {
7155 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7156 error = lua_tostring(hlua->T, -1);
7157 else
7158 error = "critical error";
7159 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7160 goto error;
7161 }
7162
7163 /* Check stack available size. */
7164 if (!lua_checkstack(hlua->T, 2)) {
7165 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7166 goto error;
7167 }
7168
7169 /* Restore the function in the stack. */
7170 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7171
7172 /* Once the arguments parsed, the CLI is like an AppletTCP,
7173 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007174 */
7175 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7176 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7177 goto error;
7178 }
7179 hlua->nargs = 1;
7180
7181 /* push keywords in the stack. */
7182 for (i = 0; *args[i]; i++) {
7183 /* Check stack available size. */
7184 if (!lua_checkstack(hlua->T, 1)) {
7185 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7186 goto error;
7187 }
7188 lua_pushstring(hlua->T, args[i]);
7189 hlua->nargs++;
7190 }
7191
7192 /* We must initialize the execution timeouts. */
7193 hlua->max_time = hlua_timeout_session;
7194
7195 /* At this point the execution is safe. */
7196 RESET_SAFE_LJMP(hlua->T);
7197
7198 /* It's ok */
7199 return 0;
7200
7201 /* It's not ok. */
7202error:
7203 RESET_SAFE_LJMP(hlua->T);
7204 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007205 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007206 return 1;
7207}
7208
7209static int hlua_cli_io_handler_fct(struct appctx *appctx)
7210{
7211 struct hlua *hlua;
7212 struct stream_interface *si;
7213 struct hlua_function *fcn;
7214
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007215 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007216 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007217 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007218
7219 /* If the stream is disconnect or closed, ldo nothing. */
7220 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7221 return 1;
7222
7223 /* Execute the function. */
7224 switch (hlua_ctx_resume(hlua, 1)) {
7225
7226 /* finished. */
7227 case HLUA_E_OK:
7228 return 1;
7229
7230 /* yield. */
7231 case HLUA_E_AGAIN:
7232 /* We want write. */
7233 if (HLUA_IS_WAKERESWR(hlua))
7234 si_applet_cant_put(si);
7235 /* Set the timeout. */
7236 if (hlua->wake_time != TICK_ETERNITY)
7237 task_schedule(hlua->task, hlua->wake_time);
7238 return 0;
7239
7240 /* finished with error. */
7241 case HLUA_E_ERRMSG:
7242 /* Display log. */
7243 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
7244 fcn->name, lua_tostring(hlua->T, -1));
7245 lua_pop(hlua->T, 1);
7246 return 1;
7247
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007248 case HLUA_E_ETMOUT:
7249 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
7250 fcn->name);
7251 return 1;
7252
7253 case HLUA_E_NOMEM:
7254 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
7255 fcn->name);
7256 return 1;
7257
7258 case HLUA_E_YIELD: /* unexpected */
7259 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
7260 fcn->name);
7261 return 1;
7262
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007263 case HLUA_E_ERR:
7264 /* Display log. */
7265 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
7266 fcn->name);
7267 return 1;
7268
7269 default:
7270 return 1;
7271 }
7272
7273 return 1;
7274}
7275
7276static void hlua_cli_io_release_fct(struct appctx *appctx)
7277{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007278 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007279 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007280}
7281
7282/* This function is an LUA binding used for registering
7283 * new keywords in the cli. It expects a list of keywords
7284 * which are the "path". It is limited to 5 keywords. A
7285 * description of the command, a function to be executed
7286 * for the parsing and a function for io handlers.
7287 */
7288__LJMP static int hlua_register_cli(lua_State *L)
7289{
7290 struct cli_kw_list *cli_kws;
7291 const char *message;
7292 int ref_io;
7293 int len;
7294 struct hlua_function *fcn;
7295 int index;
7296 int i;
7297
7298 MAY_LJMP(check_args(L, 3, "register_cli"));
7299
7300 /* First argument : an array of maximum 5 keywords. */
7301 if (!lua_istable(L, 1))
7302 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
7303
7304 /* Second argument : string with contextual message. */
7305 message = MAY_LJMP(luaL_checkstring(L, 2));
7306
7307 /* Third and fourth argument : lua function. */
7308 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
7309
7310 /* Allocate and fill the sample fetch keyword struct. */
7311 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
7312 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007313 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007314 fcn = calloc(1, sizeof(*fcn));
7315 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007316 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007317
7318 /* Fill path. */
7319 index = 0;
7320 lua_pushnil(L);
7321 while(lua_next(L, 1) != 0) {
7322 if (index >= 5)
7323 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
7324 if (lua_type(L, -1) != LUA_TSTRING)
7325 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
7326 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
7327 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007328 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007329 index++;
7330 lua_pop(L, 1);
7331 }
7332
7333 /* Copy help message. */
7334 cli_kws->kw[0].usage = strdup(message);
7335 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007336 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007337
7338 /* Fill fcn io handler. */
7339 len = strlen("<lua.cli>") + 1;
7340 for (i = 0; i < index; i++)
7341 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
7342 fcn->name = calloc(1, len);
7343 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007344 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007345 strncat((char *)fcn->name, "<lua.cli", len);
7346 for (i = 0; i < index; i++) {
7347 strncat((char *)fcn->name, ".", len);
7348 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
7349 }
7350 strncat((char *)fcn->name, ">", len);
7351 fcn->function_ref = ref_io;
7352
7353 /* Fill last entries. */
7354 cli_kws->kw[0].private = fcn;
7355 cli_kws->kw[0].parse = hlua_cli_parse_fct;
7356 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
7357 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
7358
7359 /* Register this new converter */
7360 cli_register_kw(cli_kws);
7361
7362 return 0;
7363}
7364
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007365static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7366 struct proxy *defpx, const char *file, int line,
7367 char **err, unsigned int *timeout)
7368{
7369 const char *error;
7370
7371 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
7372 if (error && *error != '\0') {
7373 memprintf(err, "%s: invalid timeout", args[0]);
7374 return -1;
7375 }
7376 return 0;
7377}
7378
7379static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7380 struct proxy *defpx, const char *file, int line,
7381 char **err)
7382{
7383 return hlua_read_timeout(args, section_type, curpx, defpx,
7384 file, line, err, &hlua_timeout_session);
7385}
7386
7387static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7388 struct proxy *defpx, const char *file, int line,
7389 char **err)
7390{
7391 return hlua_read_timeout(args, section_type, curpx, defpx,
7392 file, line, err, &hlua_timeout_task);
7393}
7394
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007395static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7396 struct proxy *defpx, const char *file, int line,
7397 char **err)
7398{
7399 return hlua_read_timeout(args, section_type, curpx, defpx,
7400 file, line, err, &hlua_timeout_applet);
7401}
7402
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007403static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7404 struct proxy *defpx, const char *file, int line,
7405 char **err)
7406{
7407 char *error;
7408
7409 hlua_nb_instruction = strtoll(args[1], &error, 10);
7410 if (*error != '\0') {
7411 memprintf(err, "%s: invalid number", args[0]);
7412 return -1;
7413 }
7414 return 0;
7415}
7416
Willy Tarreau32f61e22015-03-18 17:54:59 +01007417static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7418 struct proxy *defpx, const char *file, int line,
7419 char **err)
7420{
7421 char *error;
7422
7423 if (*(args[1]) == 0) {
7424 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7425 return -1;
7426 }
7427 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7428 if (*error != '\0') {
7429 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7430 return -1;
7431 }
7432 return 0;
7433}
7434
7435
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007436/* This function is called by the main configuration key "lua-load". It loads and
7437 * execute an lua file during the parsing of the HAProxy configuration file. It is
7438 * the main lua entry point.
7439 *
7440 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7441 * occured, otherwise it returns 0.
7442 *
7443 * In some error case, LUA set an error message in top of the stack. This function
7444 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007445 *
7446 * This function can fail with an abort() due to an Lua critical error.
7447 * We are in the configuration parsing process of HAProxy, this abort() is
7448 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007449 */
7450static int hlua_load(char **args, int section_type, struct proxy *curpx,
7451 struct proxy *defpx, const char *file, int line,
7452 char **err)
7453{
7454 int error;
7455
7456 /* Just load and compile the file. */
7457 error = luaL_loadfile(gL.T, args[1]);
7458 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007459 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007460 lua_pop(gL.T, 1);
7461 return -1;
7462 }
7463
7464 /* If no syntax error where detected, execute the code. */
7465 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7466 switch (error) {
7467 case LUA_OK:
7468 break;
7469 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007470 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007471 lua_pop(gL.T, 1);
7472 return -1;
7473 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007474 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007475 return -1;
7476 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007477 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007478 lua_pop(gL.T, 1);
7479 return -1;
7480 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007481 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007482 lua_pop(gL.T, 1);
7483 return -1;
7484 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007485 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007486 lua_pop(gL.T, 1);
7487 return -1;
7488 }
7489
7490 return 0;
7491}
7492
7493/* configuration keywords declaration */
7494static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007495 { CFG_GLOBAL, "lua-load", hlua_load },
7496 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7497 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007498 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007499 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007500 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007501 { 0, NULL, NULL },
7502}};
7503
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007504/* This function can fail with an abort() due to an Lua critical error.
7505 * We are in the initialisation process of HAProxy, this abort() is
7506 * tolerated.
7507 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007508int hlua_post_init()
7509{
7510 struct hlua_init_function *init;
7511 const char *msg;
7512 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007513 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007514
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007515 /* Call post initialisation function in safe environement. */
7516 if (!SET_SAFE_LJMP(gL.T)) {
7517 if (lua_type(gL.T, -1) == LUA_TSTRING)
7518 error = lua_tostring(gL.T, -1);
7519 else
7520 error = "critical error";
7521 fprintf(stderr, "Lua post-init: %s.\n", error);
7522 exit(1);
7523 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02007524
7525#if USE_OPENSSL
7526 /* Initialize SSL server. */
7527 if (socket_ssl.xprt->prepare_srv) {
7528 int saved_used_backed = global.ssl_used_backend;
7529 // don't affect maxconn automatic computation
7530 socket_ssl.xprt->prepare_srv(&socket_ssl);
7531 global.ssl_used_backend = saved_used_backed;
7532 }
7533#endif
7534
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007535 hlua_fcn_post_init(gL.T);
7536 RESET_SAFE_LJMP(gL.T);
7537
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007538 list_for_each_entry(init, &hlua_init_functions, l) {
7539 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7540 ret = hlua_ctx_resume(&gL, 0);
7541 switch (ret) {
7542 case HLUA_E_OK:
7543 lua_pop(gL.T, -1);
7544 return 1;
7545 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007546 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007547 return 0;
7548 case HLUA_E_ERRMSG:
7549 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01007550 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007551 return 0;
7552 case HLUA_E_ERR:
7553 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007554 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007555 return 0;
7556 }
7557 }
7558 return 1;
7559}
7560
Willy Tarreau32f61e22015-03-18 17:54:59 +01007561/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7562 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7563 * is the previously allocated size or the kind of object in case of a new
7564 * allocation. <nsize> is the requested new size.
7565 */
7566static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7567{
7568 struct hlua_mem_allocator *zone = ud;
7569
7570 if (nsize == 0) {
7571 /* it's a free */
7572 if (ptr)
7573 zone->allocated -= osize;
7574 free(ptr);
7575 return NULL;
7576 }
7577
7578 if (!ptr) {
7579 /* it's a new allocation */
7580 if (zone->limit && zone->allocated + nsize > zone->limit)
7581 return NULL;
7582
7583 ptr = malloc(nsize);
7584 if (ptr)
7585 zone->allocated += nsize;
7586 return ptr;
7587 }
7588
7589 /* it's a realloc */
7590 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7591 return NULL;
7592
7593 ptr = realloc(ptr, nsize);
7594 if (ptr)
7595 zone->allocated += nsize - osize;
7596 return ptr;
7597}
7598
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007599/* Ithis function can fail with an abort() due to an Lua critical error.
7600 * We are in the initialisation process of HAProxy, this abort() is
7601 * tolerated.
7602 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007603void hlua_init(void)
7604{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007605 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007606 int idx;
7607 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007608 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007609 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007610 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007611#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007612 struct srv_kw *kw;
7613 int tmp_error;
7614 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007615 char *args[] = { /* SSL client configuration. */
7616 "ssl",
7617 "verify",
7618 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007619 NULL
7620 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007621#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007622
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007623 HA_SPIN_INIT(&hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02007624
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007625 /* Initialise struct hlua and com signals pool */
Willy Tarreaubafbe012017-11-24 17:34:44 +01007626 pool_head_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007627
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007628 /* Register configuration keywords. */
7629 cfg_register_keywords(&cfg_kws);
7630
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007631 /* Init main lua stack. */
7632 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007633 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007634 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007635 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007636 hlua_sethlua(&gL);
7637 gL.Tref = LUA_REFNIL;
7638 gL.task = NULL;
7639
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007640 /* From this point, until the end of the initialisation fucntion,
7641 * the Lua function can fail with an abort. We are in the initialisation
7642 * process of HAProxy, this abort() is tolerated.
7643 */
7644
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007645 /* Initialise lua. */
7646 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007647
Thierry Fournier75933d42016-01-21 09:30:18 +01007648 /* Set safe environment for the initialisation. */
7649 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007650 if (lua_type(gL.T, -1) == LUA_TSTRING)
7651 error_msg = lua_tostring(gL.T, -1);
7652 else
7653 error_msg = "critical error";
7654 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007655 exit(1);
7656 }
7657
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007658 /*
7659 *
7660 * Create "core" object.
7661 *
7662 */
7663
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007664 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007665 lua_newtable(gL.T);
7666
7667 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007668 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007669 hlua_class_const_int(gL.T, log_levels[i], i);
7670
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007671 /* Register special functions. */
7672 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007673 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007674 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007675 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007676 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007677 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007678 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007679 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007680 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007681 hlua_class_function(gL.T, "sleep", hlua_sleep);
7682 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007683 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7684 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7685 hlua_class_function(gL.T, "set_map", hlua_set_map);
7686 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007687 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007688 hlua_class_function(gL.T, "log", hlua_log);
7689 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7690 hlua_class_function(gL.T, "Info", hlua_log_info);
7691 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7692 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007693 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007694 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007695
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007696 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007697
7698 /*
7699 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007700 * Register class Map
7701 *
7702 */
7703
7704 /* This table entry is the object "Map" base. */
7705 lua_newtable(gL.T);
7706
7707 /* register pattern types. */
7708 for (i=0; i<PAT_MATCH_NUM; i++)
7709 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007710 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007711 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
7712 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007713 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007714
7715 /* register constructor. */
7716 hlua_class_function(gL.T, "new", hlua_map_new);
7717
7718 /* Create and fill the metatable. */
7719 lua_newtable(gL.T);
7720
7721 /* Create and fille the __index entry. */
7722 lua_pushstring(gL.T, "__index");
7723 lua_newtable(gL.T);
7724
7725 /* Register . */
7726 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7727 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7728
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007729 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007730
Thierry Fournier45e78d72016-02-19 18:34:46 +01007731 /* Register previous table in the registry with reference and named entry.
7732 * The function hlua_register_metatable() pops the stack, so we
7733 * previously create a copy of the table.
7734 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007735 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007736 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007737
7738 /* Assign the metatable to the mai Map object. */
7739 lua_setmetatable(gL.T, -2);
7740
7741 /* Set a name to the table. */
7742 lua_setglobal(gL.T, "Map");
7743
7744 /*
7745 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007746 * Register class Channel
7747 *
7748 */
7749
7750 /* Create and fill the metatable. */
7751 lua_newtable(gL.T);
7752
7753 /* Create and fille the __index entry. */
7754 lua_pushstring(gL.T, "__index");
7755 lua_newtable(gL.T);
7756
7757 /* Register . */
7758 hlua_class_function(gL.T, "get", hlua_channel_get);
7759 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7760 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7761 hlua_class_function(gL.T, "set", hlua_channel_set);
7762 hlua_class_function(gL.T, "append", hlua_channel_append);
7763 hlua_class_function(gL.T, "send", hlua_channel_send);
7764 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7765 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7766 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007767 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007768
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007769 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007770
7771 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007772 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007773
7774 /*
7775 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007776 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007777 *
7778 */
7779
7780 /* Create and fill the metatable. */
7781 lua_newtable(gL.T);
7782
7783 /* Create and fille the __index entry. */
7784 lua_pushstring(gL.T, "__index");
7785 lua_newtable(gL.T);
7786
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007787 /* Browse existing fetches and create the associated
7788 * object method.
7789 */
7790 sf = NULL;
7791 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7792
7793 /* Dont register the keywork if the arguments check function are
7794 * not safe during the runtime.
7795 */
7796 if ((sf->val_args != NULL) &&
7797 (sf->val_args != val_payload_lv) &&
7798 (sf->val_args != val_hdr))
7799 continue;
7800
7801 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7802 * by an underscore.
7803 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007804 strncpy(trash.area, sf->kw, trash.size);
7805 trash.area[trash.size - 1] = '\0';
7806 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007807 if (*p == '.' || *p == '-' || *p == '+')
7808 *p = '_';
7809
7810 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007811 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007812 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007813 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007814 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007815 }
7816
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007817 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007818
7819 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007820 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007821
7822 /*
7823 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007824 * Register class Converters
7825 *
7826 */
7827
7828 /* Create and fill the metatable. */
7829 lua_newtable(gL.T);
7830
7831 /* Create and fill the __index entry. */
7832 lua_pushstring(gL.T, "__index");
7833 lua_newtable(gL.T);
7834
7835 /* Browse existing converters and create the associated
7836 * object method.
7837 */
7838 sc = NULL;
7839 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7840 /* Dont register the keywork if the arguments check function are
7841 * not safe during the runtime.
7842 */
7843 if (sc->val_args != NULL)
7844 continue;
7845
7846 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7847 * by an underscore.
7848 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007849 strncpy(trash.area, sc->kw, trash.size);
7850 trash.area[trash.size - 1] = '\0';
7851 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007852 if (*p == '.' || *p == '-' || *p == '+')
7853 *p = '_';
7854
7855 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007856 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007857 lua_pushlightuserdata(gL.T, sc);
7858 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007859 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007860 }
7861
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007862 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007863
7864 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007865 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007866
7867 /*
7868 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007869 * Register class HTTP
7870 *
7871 */
7872
7873 /* Create and fill the metatable. */
7874 lua_newtable(gL.T);
7875
7876 /* Create and fille the __index entry. */
7877 lua_pushstring(gL.T, "__index");
7878 lua_newtable(gL.T);
7879
7880 /* Register Lua functions. */
7881 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7882 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7883 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7884 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7885 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7886 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7887 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7888 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7889 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7890 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7891
7892 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7893 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7894 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7895 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7896 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7897 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007898 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007899
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007900 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007901
7902 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007903 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007904
7905 /*
7906 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007907 * Register class AppletTCP
7908 *
7909 */
7910
7911 /* Create and fill the metatable. */
7912 lua_newtable(gL.T);
7913
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007914 /* Create and fille the __index entry. */
7915 lua_pushstring(gL.T, "__index");
7916 lua_newtable(gL.T);
7917
7918 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007919 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7920 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7921 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7922 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7923 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007924 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7925 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7926 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007927
7928 lua_settable(gL.T, -3);
7929
7930 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007931 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007932
7933 /*
7934 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007935 * Register class AppletHTTP
7936 *
7937 */
7938
7939 /* Create and fill the metatable. */
7940 lua_newtable(gL.T);
7941
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007942 /* Create and fille the __index entry. */
7943 lua_pushstring(gL.T, "__index");
7944 lua_newtable(gL.T);
7945
7946 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007947 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7948 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007949 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7950 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7951 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007952 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7953 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7954 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7955 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7956 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7957 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7958
7959 lua_settable(gL.T, -3);
7960
7961 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007962 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007963
7964 /*
7965 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007966 * Register class TXN
7967 *
7968 */
7969
7970 /* Create and fill the metatable. */
7971 lua_newtable(gL.T);
7972
7973 /* Create and fille the __index entry. */
7974 lua_pushstring(gL.T, "__index");
7975 lua_newtable(gL.T);
7976
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007977 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04007978 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7979 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
7980 hlua_class_function(gL.T, "set_var", hlua_set_var);
7981 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
7982 hlua_class_function(gL.T, "get_var", hlua_get_var);
7983 hlua_class_function(gL.T, "done", hlua_txn_done);
7984 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
7985 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7986 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
7987 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
7988 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
7989 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7990 hlua_class_function(gL.T, "log", hlua_txn_log);
7991 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7992 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7993 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7994 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007995
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007996 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007997
7998 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007999 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008000
8001 /*
8002 *
8003 * Register class Socket
8004 *
8005 */
8006
8007 /* Create and fill the metatable. */
8008 lua_newtable(gL.T);
8009
8010 /* Create and fille the __index entry. */
8011 lua_pushstring(gL.T, "__index");
8012 lua_newtable(gL.T);
8013
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008014#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008015 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008016#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008017 hlua_class_function(gL.T, "connect", hlua_socket_connect);
8018 hlua_class_function(gL.T, "send", hlua_socket_send);
8019 hlua_class_function(gL.T, "receive", hlua_socket_receive);
8020 hlua_class_function(gL.T, "close", hlua_socket_close);
8021 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
8022 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8023 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8024 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8025
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008026 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008027
8028 /* Register the garbage collector entry. */
8029 lua_pushstring(gL.T, "__gc");
8030 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008031 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008032
8033 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008034 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008035
8036 /* Proxy and server configuration initialisation. */
8037 memset(&socket_proxy, 0, sizeof(socket_proxy));
8038 init_new_proxy(&socket_proxy);
8039 socket_proxy.parent = NULL;
8040 socket_proxy.last_change = now.tv_sec;
8041 socket_proxy.id = "LUA-SOCKET";
8042 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8043 socket_proxy.maxconn = 0;
8044 socket_proxy.accept = NULL;
8045 socket_proxy.options2 |= PR_O2_INDEPSTR;
8046 socket_proxy.srv = NULL;
8047 socket_proxy.conn_retries = 0;
8048 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8049
8050 /* Init TCP server: unchanged parameters */
8051 memset(&socket_tcp, 0, sizeof(socket_tcp));
8052 socket_tcp.next = NULL;
8053 socket_tcp.proxy = &socket_proxy;
8054 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8055 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008056 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008057 socket_tcp.priv_conns = NULL;
8058 socket_tcp.idle_conns = NULL;
8059 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008060 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008061 socket_tcp.last_change = 0;
8062 socket_tcp.id = "LUA-TCP-CONN";
8063 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8064 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8065 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
8066
8067 /* XXX: Copy default parameter from default server,
8068 * but the default server is not initialized.
8069 */
8070 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
8071 socket_tcp.minconn = socket_proxy.defsrv.minconn;
8072 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
8073 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
8074 socket_tcp.onerror = socket_proxy.defsrv.onerror;
8075 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8076 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
8077 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8078 socket_tcp.uweight = socket_proxy.defsrv.iweight;
8079 socket_tcp.iweight = socket_proxy.defsrv.iweight;
8080
8081 socket_tcp.check.status = HCHK_STATUS_INI;
8082 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
8083 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
8084 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
8085 socket_tcp.check.server = &socket_tcp;
8086
8087 socket_tcp.agent.status = HCHK_STATUS_INI;
8088 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
8089 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
8090 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
8091 socket_tcp.agent.server = &socket_tcp;
8092
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008093 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008094
8095#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008096 /* Init TCP server: unchanged parameters */
8097 memset(&socket_ssl, 0, sizeof(socket_ssl));
8098 socket_ssl.next = NULL;
8099 socket_ssl.proxy = &socket_proxy;
8100 socket_ssl.obj_type = OBJ_TYPE_SERVER;
8101 LIST_INIT(&socket_ssl.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008102 socket_ssl.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008103 socket_tcp.priv_conns = NULL;
8104 socket_tcp.idle_conns = NULL;
8105 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008106 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008107 socket_ssl.last_change = 0;
8108 socket_ssl.id = "LUA-SSL-CONN";
8109 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8110 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8111 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8112
8113 /* XXX: Copy default parameter from default server,
8114 * but the default server is not initialized.
8115 */
8116 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8117 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8118 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8119 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8120 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8121 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8122 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8123 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8124 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8125 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8126
8127 socket_ssl.check.status = HCHK_STATUS_INI;
8128 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8129 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8130 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8131 socket_ssl.check.server = &socket_ssl;
8132
8133 socket_ssl.agent.status = HCHK_STATUS_INI;
8134 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8135 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8136 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8137 socket_ssl.agent.server = &socket_ssl;
8138
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008139 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008140 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008141
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008142 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008143 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8144 /*
8145 *
8146 * If the keyword is not known, we can search in the registered
8147 * server keywords. This is usefull to configure special SSL
8148 * features like client certificates and ssl_verify.
8149 *
8150 */
8151 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8152 if (tmp_error != 0) {
8153 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8154 abort(); /* This must be never arrives because the command line
8155 not editable by the user. */
8156 }
8157 idx += kw->skip;
8158 }
8159 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008160#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008161
8162 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008163}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008164
8165__attribute__((constructor))
8166static void __hlua_init(void)
8167{
8168 char *ptr = NULL;
8169 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8170 hap_register_build_opts(ptr, 1);
8171}