blob: aaa884073df8678ec1c2a8ef22a52c3af17b57c2 [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
70#define WILL_LJMP(func) func
71#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. */
872 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
873}
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))
1023 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
1024
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);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001886 WILL_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);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002085 WILL_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
Thierry FOURNIER2da788e2017-09-11 18:37:23 +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);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002378 WILL_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);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +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
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002496 WILL_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)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002832 WILL_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))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002858 WILL_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)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002896 WILL_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));
2945 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2946 }
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;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002959 WILL_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)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002975 WILL_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));
3039 WILL_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);
3095 WILL_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. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01003159 WILL_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);
3665 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3666 }
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);
3720 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3721 }
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);
3743 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3744
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);
3767 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3768 }
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);
3836 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3837 }
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);
4133 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4134 }
4135 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4136 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004137
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004138 /* 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);
4150 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4151 }
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);
4219 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4220 }
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);
4230 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4231 }
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);
4265 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4266 }
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);
4331 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
4332 }
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);
4471 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4472 }
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)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005543 WILL_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
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005558 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5559 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
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005573 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5574 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{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005588 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5589 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);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005726 task->context = hlua;
5727 task->process = hlua_process_task;
5728
5729 if (!hlua_ctx_init(hlua, task))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005730 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005731
5732 /* Restore the function in the stack. */
5733 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5734 hlua->nargs = 0;
5735
5736 /* Schedule task. */
5737 task_schedule(task, now_ms);
5738
5739 return 0;
5740}
5741
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005742/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5743 * doesn't allow "yield" functions because the HAProxy engine cannot
5744 * resume converters.
5745 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005746static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005747{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005748 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005749 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005750 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005751
Willy Tarreaube508f12016-03-10 11:47:01 +01005752 if (!stream)
5753 return 0;
5754
Willy Tarreau87b09662015-04-03 00:22:06 +02005755 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005756 * Lua context can be not initialized. This behavior
5757 * permits to save performances because a systematic
5758 * Lua initialization cause 5% performances loss.
5759 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005760 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005761 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005762 if (!stream->hlua) {
5763 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5764 return 0;
5765 }
5766 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5767 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5768 return 0;
5769 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005770 }
5771
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005772 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005773 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005774
5775 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005776 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5777 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5778 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005779 else
5780 error = "critical error";
5781 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005782 return 0;
5783 }
5784
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005785 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005786 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005787 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005788 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005789 return 0;
5790 }
5791
5792 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005793 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005794
5795 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005796 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005797 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005798 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005799 return 0;
5800 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005801 hlua_smp2lua(stream->hlua->T, smp);
5802 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005803
5804 /* push keywords in the stack. */
5805 if (arg_p) {
5806 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005807 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005808 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005809 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005810 return 0;
5811 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005812 hlua_arg2lua(stream->hlua->T, arg_p);
5813 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005814 }
5815 }
5816
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005817 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005818 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005819
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005820 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005821 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005822 }
5823
5824 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005825 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005826 /* finished. */
5827 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005828 /* If the stack is empty, the function fails. */
5829 if (lua_gettop(stream->hlua->T) <= 0)
5830 return 0;
5831
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005832 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005833 hlua_lua2smp(stream->hlua->T, -1, smp);
5834 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005835 return 1;
5836
5837 /* yield. */
5838 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005839 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005840 return 0;
5841
5842 /* finished with error. */
5843 case HLUA_E_ERRMSG:
5844 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005845 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005846 fcn->name, lua_tostring(stream->hlua->T, -1));
5847 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005848 return 0;
5849
Thierry Fournierd5b073c2018-05-21 19:42:47 +02005850 case HLUA_E_ETMOUT:
5851 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
5852 return 0;
5853
5854 case HLUA_E_NOMEM:
5855 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
5856 return 0;
5857
5858 case HLUA_E_YIELD:
5859 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
5860 return 0;
5861
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005862 case HLUA_E_ERR:
5863 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005864 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005865
5866 default:
5867 return 0;
5868 }
5869}
5870
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005871/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5872 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005873 * resume sample-fetches. This function will be called by the sample
5874 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005875 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005876static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5877 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005878{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005879 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005880 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005881 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02005882 const struct buffer msg = { };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005883
Willy Tarreaube508f12016-03-10 11:47:01 +01005884 if (!stream)
5885 return 0;
5886
Willy Tarreau87b09662015-04-03 00:22:06 +02005887 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005888 * Lua context can be not initialized. This behavior
5889 * permits to save performances because a systematic
5890 * Lua initialization cause 5% performances loss.
5891 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005892 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005893 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005894 if (!stream->hlua) {
5895 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5896 return 0;
5897 }
5898 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5899 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5900 return 0;
5901 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005902 }
5903
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005904 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005905
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005906 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005907 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005908
5909 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005910 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5911 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5912 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005913 else
5914 error = "critical error";
5915 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005916 return 0;
5917 }
5918
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005919 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005920 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005921 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005922 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005923 return 0;
5924 }
5925
5926 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005927 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005928
5929 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005930 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005931 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005932 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005933 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005934 return 0;
5935 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005936 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005937
5938 /* push keywords in the stack. */
5939 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5940 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005941 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005942 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005943 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005944 return 0;
5945 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005946 hlua_arg2lua(stream->hlua->T, arg_p);
5947 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005948 }
5949
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005950 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005951 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005952
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005953 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005954 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005955 }
5956
5957 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005958 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005959 /* finished. */
5960 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005961 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005962 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005963 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005964 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005965 /* If the stack is empty, the function fails. */
5966 if (lua_gettop(stream->hlua->T) <= 0)
5967 return 0;
5968
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005969 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005970 hlua_lua2smp(stream->hlua->T, -1, smp);
5971 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005972
5973 /* Set the end of execution flag. */
5974 smp->flags &= ~SMP_F_MAY_CHANGE;
5975 return 1;
5976
5977 /* yield. */
5978 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005979 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005980 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005981 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005982 return 0;
5983
5984 /* finished with error. */
5985 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005986 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005987 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005988 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005989 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005990 fcn->name, lua_tostring(stream->hlua->T, -1));
5991 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005992 return 0;
5993
Thierry Fournierd5b073c2018-05-21 19:42:47 +02005994 case HLUA_E_ETMOUT:
5995 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
5996 stream_int_retnclose(&stream->si[0], &msg);
5997 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
5998 return 0;
5999
6000 case HLUA_E_NOMEM:
6001 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
6002 stream_int_retnclose(&stream->si[0], &msg);
6003 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
6004 return 0;
6005
6006 case HLUA_E_YIELD:
6007 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
6008 stream_int_retnclose(&stream->si[0], &msg);
6009 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
6010 return 0;
6011
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006012 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006013 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006014 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006015 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006016 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006017
6018 default:
6019 return 0;
6020 }
6021}
6022
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006023/* This function is an LUA binding used for registering
6024 * "sample-conv" functions. It expects a converter name used
6025 * in the haproxy configuration file, and an LUA function.
6026 */
6027__LJMP static int hlua_register_converters(lua_State *L)
6028{
6029 struct sample_conv_kw_list *sck;
6030 const char *name;
6031 int ref;
6032 int len;
6033 struct hlua_function *fcn;
6034
6035 MAY_LJMP(check_args(L, 2, "register_converters"));
6036
6037 /* First argument : converter name. */
6038 name = MAY_LJMP(luaL_checkstring(L, 1));
6039
6040 /* Second argument : lua function. */
6041 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6042
6043 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006044 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006045 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006046 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006047 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006048 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006049 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006050
6051 /* Fill fcn. */
6052 fcn->name = strdup(name);
6053 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006054 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006055 fcn->function_ref = ref;
6056
6057 /* List head */
6058 sck->list.n = sck->list.p = NULL;
6059
6060 /* converter keyword. */
6061 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006062 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006063 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006064 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006065
6066 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6067 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006068 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 +01006069 sck->kw[0].val_args = NULL;
6070 sck->kw[0].in_type = SMP_T_STR;
6071 sck->kw[0].out_type = SMP_T_STR;
6072 sck->kw[0].private = fcn;
6073
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006074 /* Register this new converter */
6075 sample_register_convs(sck);
6076
6077 return 0;
6078}
6079
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006080/* This fucntion is an LUA binding used for registering
6081 * "sample-fetch" functions. It expects a converter name used
6082 * in the haproxy configuration file, and an LUA function.
6083 */
6084__LJMP static int hlua_register_fetches(lua_State *L)
6085{
6086 const char *name;
6087 int ref;
6088 int len;
6089 struct sample_fetch_kw_list *sfk;
6090 struct hlua_function *fcn;
6091
6092 MAY_LJMP(check_args(L, 2, "register_fetches"));
6093
6094 /* First argument : sample-fetch name. */
6095 name = MAY_LJMP(luaL_checkstring(L, 1));
6096
6097 /* Second argument : lua function. */
6098 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6099
6100 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006101 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006102 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006103 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006104 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006105 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006106 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006107
6108 /* Fill fcn. */
6109 fcn->name = strdup(name);
6110 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006111 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006112 fcn->function_ref = ref;
6113
6114 /* List head */
6115 sfk->list.n = sfk->list.p = NULL;
6116
6117 /* sample-fetch keyword. */
6118 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006119 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006120 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006121 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006122
6123 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6124 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006125 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 +01006126 sfk->kw[0].val_args = NULL;
6127 sfk->kw[0].out_type = SMP_T_STR;
6128 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6129 sfk->kw[0].val = 0;
6130 sfk->kw[0].private = fcn;
6131
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006132 /* Register this new fetch. */
6133 sample_register_fetches(sfk);
6134
6135 return 0;
6136}
6137
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006138/* This function is a wrapper to execute each LUA function declared
6139 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006140 * return ACT_RET_CONT if the processing is finished (with or without
6141 * error) and return ACT_RET_YIELD if the function must be called again
6142 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006143 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006144static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006145 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006146{
6147 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006148 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006149 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006150 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006151 const struct buffer msg = { };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006152
6153 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01006154 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
6155 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
6156 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
6157 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006158 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006159 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006160 return ACT_RET_CONT;
6161 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006162
Willy Tarreau87b09662015-04-03 00:22:06 +02006163 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006164 * Lua context can be not initialized. This behavior
6165 * permits to save performances because a systematic
6166 * Lua initialization cause 5% performances loss.
6167 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006168 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006169 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006170 if (!s->hlua) {
6171 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6172 rule->arg.hlua_rule->fcn.name);
6173 return ACT_RET_CONT;
6174 }
6175 if (!hlua_ctx_init(s->hlua, s->task)) {
6176 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6177 rule->arg.hlua_rule->fcn.name);
6178 return ACT_RET_CONT;
6179 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006180 }
6181
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006182 consistency_set(s, dir, &s->hlua->cons);
6183
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006184 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006185 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006186
6187 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006188 if (!SET_SAFE_LJMP(s->hlua->T)) {
6189 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6190 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006191 else
6192 error = "critical error";
6193 SEND_ERR(px, "Lua function '%s': %s.\n",
6194 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006195 return ACT_RET_CONT;
6196 }
6197
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006198 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006199 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006200 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006201 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006202 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006203 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006204 }
6205
6206 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006207 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006208
Willy Tarreau87b09662015-04-03 00:22:06 +02006209 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006210 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006211 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006212 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006213 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006214 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006215 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006216 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006217
6218 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006219 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006220 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006221 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006222 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006223 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006224 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006225 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006226 lua_pushstring(s->hlua->T, *arg);
6227 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006228 }
6229
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006230 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006231 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006232
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006233 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006234 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006235 }
6236
6237 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006238 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006239 /* finished. */
6240 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006241 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006242 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006243 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006244 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006245 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006246 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006247 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006248
6249 /* yield. */
6250 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006251 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006252 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006253 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006254 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006255 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006256 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006257 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006258 /* Some actions can be wake up when a "write" event
6259 * is detected on a response channel. This is useful
6260 * only for actions targetted on the requests.
6261 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006262 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006263 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01006264 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006265 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006266 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006267 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006268 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006269 /* We can quit the fcuntion without consistency check
6270 * because HAProxy is not able to manipulate data, it
6271 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006272 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006273
6274 /* finished with error. */
6275 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006276 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006277 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006278 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006279 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006280 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006281 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006282 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6283 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006284 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006285
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006286 case HLUA_E_ETMOUT:
6287 if (!consistency_check(s, dir, &s->hlua->cons)) {
6288 stream_int_retnclose(&s->si[0], &msg);
6289 return ACT_RET_ERR;
6290 }
6291 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
6292 return 0;
6293
6294 case HLUA_E_NOMEM:
6295 if (!consistency_check(s, dir, &s->hlua->cons)) {
6296 stream_int_retnclose(&s->si[0], &msg);
6297 return ACT_RET_ERR;
6298 }
6299 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
6300 return 0;
6301
6302 case HLUA_E_YIELD:
6303 if (!consistency_check(s, dir, &s->hlua->cons)) {
6304 stream_int_retnclose(&s->si[0], &msg);
6305 return ACT_RET_ERR;
6306 }
6307 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6308 rule->arg.hlua_rule->fcn.name);
6309 return 0;
6310
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006311 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006312 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006313 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006314 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006315 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006316 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006317 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006318 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006319
6320 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006321 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006322 }
6323}
6324
Olivier Houchard9f6af332018-05-25 14:04:04 +02006325struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006326{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006327 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006328 struct stream_interface *si = ctx->owner;
6329
6330 /* If the applet is wake up without any expected work, the sheduler
6331 * remove it from the run queue. This flag indicate that the applet
6332 * is waiting for write. If the buffer is full, the main processing
6333 * will send some data and after call the applet, otherwise it call
6334 * the applet ASAP.
6335 */
6336 si_applet_cant_put(si);
6337 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006338 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006339 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006340}
6341
6342static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6343{
6344 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006345 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006346 struct task *task;
6347 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006348 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006349
Willy Tarreaubafbe012017-11-24 17:34:44 +01006350 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006351 if (!hlua) {
6352 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6353 ctx->rule->arg.hlua_rule->fcn.name);
6354 return 0;
6355 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006356 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006357 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006358 ctx->ctx.hlua_apptcp.flags = 0;
6359
6360 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006361 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006362 if (!task) {
6363 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6364 ctx->rule->arg.hlua_rule->fcn.name);
6365 return 0;
6366 }
6367 task->nice = 0;
6368 task->context = ctx;
6369 task->process = hlua_applet_wakeup;
6370 ctx->ctx.hlua_apptcp.task = task;
6371
6372 /* In the execution wrappers linked with a stream, the
6373 * Lua context can be not initialized. This behavior
6374 * permits to save performances because a systematic
6375 * Lua initialization cause 5% performances loss.
6376 */
6377 if (!hlua_ctx_init(hlua, task)) {
6378 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6379 ctx->rule->arg.hlua_rule->fcn.name);
6380 return 0;
6381 }
6382
6383 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006384 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006385
6386 /* The following Lua calls can fail. */
6387 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006388 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6389 error = lua_tostring(hlua->T, -1);
6390 else
6391 error = "critical error";
6392 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6393 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006394 return 0;
6395 }
6396
6397 /* Check stack available size. */
6398 if (!lua_checkstack(hlua->T, 1)) {
6399 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6400 ctx->rule->arg.hlua_rule->fcn.name);
6401 RESET_SAFE_LJMP(hlua->T);
6402 return 0;
6403 }
6404
6405 /* Restore the function in the stack. */
6406 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6407
6408 /* Create and and push object stream in the stack. */
6409 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6410 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6411 ctx->rule->arg.hlua_rule->fcn.name);
6412 RESET_SAFE_LJMP(hlua->T);
6413 return 0;
6414 }
6415 hlua->nargs = 1;
6416
6417 /* push keywords in the stack. */
6418 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6419 if (!lua_checkstack(hlua->T, 1)) {
6420 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6421 ctx->rule->arg.hlua_rule->fcn.name);
6422 RESET_SAFE_LJMP(hlua->T);
6423 return 0;
6424 }
6425 lua_pushstring(hlua->T, *arg);
6426 hlua->nargs++;
6427 }
6428
6429 RESET_SAFE_LJMP(hlua->T);
6430
6431 /* Wakeup the applet ASAP. */
6432 si_applet_cant_get(si);
6433 si_applet_cant_put(si);
6434
6435 return 1;
6436}
6437
6438static void hlua_applet_tcp_fct(struct appctx *ctx)
6439{
6440 struct stream_interface *si = ctx->owner;
6441 struct stream *strm = si_strm(si);
6442 struct channel *res = si_ic(si);
6443 struct act_rule *rule = ctx->rule;
6444 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006445 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006446
6447 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02006448 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
6449 /* eat the whole request */
6450 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006451 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02006452 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006453
6454 /* If the stream is disconnect or closed, ldo nothing. */
6455 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6456 return;
6457
6458 /* Execute the function. */
6459 switch (hlua_ctx_resume(hlua, 1)) {
6460 /* finished. */
6461 case HLUA_E_OK:
6462 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6463
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006464 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02006465 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006466 res->flags |= CF_READ_NULL;
6467 si_shutr(si);
6468 return;
6469
6470 /* yield. */
6471 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006472 if (hlua->wake_time != TICK_ETERNITY)
6473 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006474 return;
6475
6476 /* finished with error. */
6477 case HLUA_E_ERRMSG:
6478 /* Display log. */
6479 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6480 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6481 lua_pop(hlua->T, 1);
6482 goto error;
6483
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006484 case HLUA_E_ETMOUT:
6485 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
6486 rule->arg.hlua_rule->fcn.name);
6487 goto error;
6488
6489 case HLUA_E_NOMEM:
6490 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
6491 rule->arg.hlua_rule->fcn.name);
6492 goto error;
6493
6494 case HLUA_E_YIELD: /* unexpected */
6495 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
6496 rule->arg.hlua_rule->fcn.name);
6497 goto error;
6498
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006499 case HLUA_E_ERR:
6500 /* Display log. */
6501 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6502 rule->arg.hlua_rule->fcn.name);
6503 goto error;
6504
6505 default:
6506 goto error;
6507 }
6508
6509error:
6510
6511 /* For all other cases, just close the stream. */
6512 si_shutw(si);
6513 si_shutr(si);
6514 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6515}
6516
6517static void hlua_applet_tcp_release(struct appctx *ctx)
6518{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006519 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006520 task_free(ctx->ctx.hlua_apptcp.task);
6521 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006522 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006523 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006524}
6525
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006526/* The function returns 1 if the initialisation is complete, 0 if
6527 * an errors occurs and -1 if more data are required for initializing
6528 * the applet.
6529 */
6530static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6531{
6532 struct stream_interface *si = ctx->owner;
6533 struct channel *req = si_oc(si);
6534 struct http_msg *msg;
6535 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006536 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006537 char **arg;
6538 struct hdr_ctx hdr;
6539 struct task *task;
6540 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006541 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006542
6543 /* Wait for a full HTTP request. */
6544 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6545 if (smp.flags & SMP_F_MAY_CHANGE)
6546 return -1;
6547 return 0;
6548 }
6549 txn = strm->txn;
6550 msg = &txn->req;
6551
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006552 /* We want two things in HTTP mode :
6553 * - enforce server-close mode if we were in keep-alive, so that the
6554 * applet is released after each response ;
6555 * - enable request body transfer to the applet in order to resync
6556 * with the response body.
6557 */
6558 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6559 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006560
Willy Tarreaubafbe012017-11-24 17:34:44 +01006561 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006562 if (!hlua) {
6563 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6564 ctx->rule->arg.hlua_rule->fcn.name);
6565 return 0;
6566 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006567 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006568 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006569 ctx->ctx.hlua_apphttp.left_bytes = -1;
6570 ctx->ctx.hlua_apphttp.flags = 0;
6571
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006572 if (txn->req.flags & HTTP_MSGF_VER_11)
6573 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6574
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006575 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006576 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006577 if (!task) {
6578 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6579 ctx->rule->arg.hlua_rule->fcn.name);
6580 return 0;
6581 }
6582 task->nice = 0;
6583 task->context = ctx;
6584 task->process = hlua_applet_wakeup;
6585 ctx->ctx.hlua_apphttp.task = task;
6586
6587 /* In the execution wrappers linked with a stream, the
6588 * Lua context can be not initialized. This behavior
6589 * permits to save performances because a systematic
6590 * Lua initialization cause 5% performances loss.
6591 */
6592 if (!hlua_ctx_init(hlua, task)) {
6593 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6594 ctx->rule->arg.hlua_rule->fcn.name);
6595 return 0;
6596 }
6597
6598 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006599 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006600
6601 /* The following Lua calls can fail. */
6602 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006603 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6604 error = lua_tostring(hlua->T, -1);
6605 else
6606 error = "critical error";
6607 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6608 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006609 return 0;
6610 }
6611
6612 /* Check stack available size. */
6613 if (!lua_checkstack(hlua->T, 1)) {
6614 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6615 ctx->rule->arg.hlua_rule->fcn.name);
6616 RESET_SAFE_LJMP(hlua->T);
6617 return 0;
6618 }
6619
6620 /* Restore the function in the stack. */
6621 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6622
6623 /* Create and and push object stream in the stack. */
6624 if (!hlua_applet_http_new(hlua->T, ctx)) {
6625 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6626 ctx->rule->arg.hlua_rule->fcn.name);
6627 RESET_SAFE_LJMP(hlua->T);
6628 return 0;
6629 }
6630 hlua->nargs = 1;
6631
6632 /* Look for a 100-continue expected. */
6633 if (msg->flags & HTTP_MSGF_VER_11) {
6634 hdr.idx = 0;
Willy Tarreaua79021a2018-06-15 18:07:57 +02006635 if (http_find_header2("Expect", 6, ci_head(req), &txn->hdr_idx, &hdr) &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006636 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6637 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6638 }
6639
6640 /* push keywords in the stack. */
6641 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6642 if (!lua_checkstack(hlua->T, 1)) {
6643 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6644 ctx->rule->arg.hlua_rule->fcn.name);
6645 RESET_SAFE_LJMP(hlua->T);
6646 return 0;
6647 }
6648 lua_pushstring(hlua->T, *arg);
6649 hlua->nargs++;
6650 }
6651
6652 RESET_SAFE_LJMP(hlua->T);
6653
6654 /* Wakeup the applet when data is ready for read. */
6655 si_applet_cant_get(si);
6656
6657 return 1;
6658}
6659
6660static void hlua_applet_http_fct(struct appctx *ctx)
6661{
6662 struct stream_interface *si = ctx->owner;
6663 struct stream *strm = si_strm(si);
6664 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006665 struct act_rule *rule = ctx->rule;
6666 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006667 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Willy Tarreau206ba832018-06-14 15:27:31 +02006668 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02006669 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02006670 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02006671 size_t len2;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006672 int ret;
6673
6674 /* If the stream is disconnect or closed, ldo nothing. */
6675 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6676 return;
6677
6678 /* Set the currently running flag. */
6679 if (!HLUA_IS_RUNNING(hlua) &&
6680 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6681
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006682 /* Wait for full HTTP analysys. */
6683 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6684 si_applet_cant_get(si);
6685 return;
6686 }
6687
6688 /* Store the max amount of bytes that we can read. */
6689 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6690
6691 /* We need to flush the request header. This left the body
6692 * for the Lua.
6693 */
6694
6695 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006696 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006697 if (ret == -1)
6698 return;
6699
6700 /* No data available, ask for more data. */
6701 if (ret == 1)
6702 len2 = 0;
6703 if (ret == 0)
6704 len1 = 0;
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02006705 if (len1 + len2 < strm->txn->req.eoh + strm->txn->req.eol) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006706 si_applet_cant_get(si);
6707 return;
6708 }
6709
6710 /* skip the requests bytes. */
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02006711 co_skip(si_oc(si), strm->txn->req.eoh + strm->txn->req.eol);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006712 }
6713
6714 /* Executes The applet if it is not done. */
6715 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6716
6717 /* Execute the function. */
6718 switch (hlua_ctx_resume(hlua, 1)) {
6719 /* finished. */
6720 case HLUA_E_OK:
6721 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6722 break;
6723
6724 /* yield. */
6725 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006726 if (hlua->wake_time != TICK_ETERNITY)
6727 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006728 return;
6729
6730 /* finished with error. */
6731 case HLUA_E_ERRMSG:
6732 /* Display log. */
6733 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6734 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6735 lua_pop(hlua->T, 1);
6736 goto error;
6737
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006738 case HLUA_E_ETMOUT:
6739 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
6740 rule->arg.hlua_rule->fcn.name);
6741 goto error;
6742
6743 case HLUA_E_NOMEM:
6744 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
6745 rule->arg.hlua_rule->fcn.name);
6746 goto error;
6747
6748 case HLUA_E_YIELD: /* unexpected */
6749 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
6750 rule->arg.hlua_rule->fcn.name);
6751 goto error;
6752
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006753 case HLUA_E_ERR:
6754 /* Display log. */
6755 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6756 rule->arg.hlua_rule->fcn.name);
6757 goto error;
6758
6759 default:
6760 goto error;
6761 }
6762 }
6763
6764 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6765
6766 /* We must send the final chunk. */
6767 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6768 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6769
6770 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006771 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006772
6773 /* critical error. */
6774 if (ret == -2 || ret == -3) {
6775 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6776 rule->arg.hlua_rule->fcn.name);
6777 goto error;
6778 }
6779
6780 /* no enough space error. */
6781 if (ret == -1) {
6782 si_applet_cant_put(si);
6783 return;
6784 }
6785
6786 /* set the last chunk sent. */
6787 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6788 }
6789
6790 /* close the connection. */
6791
Frédéric Lécaille83ed5d52018-07-18 14:25:26 +02006792 /* status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006793 strm->txn->status = ctx->ctx.hlua_apphttp.status;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006794
6795 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02006796 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006797 res->flags |= CF_READ_NULL;
6798 si_shutr(si);
6799
6800 return;
6801 }
6802
6803error:
6804
6805 /* If we are in HTTP mode, and we are not send any
6806 * data, return a 500 server error in best effort:
6807 * if there are no room avalaible in the buffer,
6808 * just close the connection.
6809 */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006810 ci_putblk(res, error_500, strlen(error_500));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006811 if (!(strm->flags & SF_ERR_MASK))
6812 strm->flags |= SF_ERR_RESOURCE;
6813 si_shutw(si);
6814 si_shutr(si);
6815 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6816}
6817
6818static void hlua_applet_http_release(struct appctx *ctx)
6819{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006820 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006821 task_free(ctx->ctx.hlua_apphttp.task);
6822 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006823 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006824 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006825}
6826
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006827/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6828 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006829 *
6830 * This function can fail with an abort() due to an Lua critical error.
6831 * We are in the configuration parsing process of HAProxy, this abort() is
6832 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006833 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006834static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6835 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006836{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006837 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006838 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006839
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006840 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006841 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006842 if (!rule->arg.hlua_rule) {
6843 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006844 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006845 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006846
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006847 /* Memory for arguments. */
6848 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6849 if (!rule->arg.hlua_rule->args) {
6850 memprintf(err, "out of memory error");
6851 return ACT_RET_PRS_ERR;
6852 }
6853
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006854 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006855 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006856
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006857 /* Expect some arguments */
6858 for (i = 0; i < fcn->nargs; i++) {
6859 if (*args[i+1] == '\0') {
6860 memprintf(err, "expect %d arguments", fcn->nargs);
6861 return ACT_RET_PRS_ERR;
6862 }
6863 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6864 if (!rule->arg.hlua_rule->args[i]) {
6865 memprintf(err, "out of memory error");
6866 return ACT_RET_PRS_ERR;
6867 }
6868 (*cur_arg)++;
6869 }
6870 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006871
Thierry FOURNIER42148732015-09-02 17:17:33 +02006872 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006873 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006874 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006875}
6876
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006877static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6878 struct act_rule *rule, char **err)
6879{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006880 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006881
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006882 /* HTTP applets are forbidden in tcp-request rules.
6883 * HTTP applet request requires everything initilized by
6884 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6885 * The applet will be immediately initilized, but its before
6886 * the call of this analyzer.
6887 */
6888 if (rule->from != ACT_F_HTTP_REQ) {
6889 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6890 return ACT_RET_PRS_ERR;
6891 }
6892
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006893 /* Memory for the rule. */
6894 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6895 if (!rule->arg.hlua_rule) {
6896 memprintf(err, "out of memory error");
6897 return ACT_RET_PRS_ERR;
6898 }
6899
6900 /* Reference the Lua function and store the reference. */
6901 rule->arg.hlua_rule->fcn = *fcn;
6902
6903 /* TODO: later accept arguments. */
6904 rule->arg.hlua_rule->args = NULL;
6905
6906 /* Add applet pointer in the rule. */
6907 rule->applet.obj_type = OBJ_TYPE_APPLET;
6908 rule->applet.name = fcn->name;
6909 rule->applet.init = hlua_applet_http_init;
6910 rule->applet.fct = hlua_applet_http_fct;
6911 rule->applet.release = hlua_applet_http_release;
6912 rule->applet.timeout = hlua_timeout_applet;
6913
6914 return ACT_RET_PRS_OK;
6915}
6916
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006917/* This function is an LUA binding used for registering
6918 * "sample-conv" functions. It expects a converter name used
6919 * in the haproxy configuration file, and an LUA function.
6920 */
6921__LJMP static int hlua_register_action(lua_State *L)
6922{
6923 struct action_kw_list *akl;
6924 const char *name;
6925 int ref;
6926 int len;
6927 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006928 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006929
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006930 /* Initialise the number of expected arguments at 0. */
6931 nargs = 0;
6932
6933 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6934 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006935
6936 /* First argument : converter name. */
6937 name = MAY_LJMP(luaL_checkstring(L, 1));
6938
6939 /* Second argument : environment. */
6940 if (lua_type(L, 2) != LUA_TTABLE)
6941 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6942
6943 /* Third argument : lua function. */
6944 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6945
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006946 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6947 if (lua_gettop(L) >= 4)
6948 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6949
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006950 /* browse the second argulent as an array. */
6951 lua_pushnil(L);
6952 while (lua_next(L, 2) != 0) {
6953 if (lua_type(L, -1) != LUA_TSTRING)
6954 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6955
6956 /* Check required environment. Only accepted "http" or "tcp". */
6957 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006958 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006959 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006960 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006961 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006962 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006963 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006964
6965 /* Fill fcn. */
6966 fcn->name = strdup(name);
6967 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006968 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006969 fcn->function_ref = ref;
6970
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006971 /* Set the expected number od arguments. */
6972 fcn->nargs = nargs;
6973
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006974 /* List head */
6975 akl->list.n = akl->list.p = NULL;
6976
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006977 /* action keyword. */
6978 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006979 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006980 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006981 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006982
6983 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6984
6985 akl->kw[0].match_pfx = 0;
6986 akl->kw[0].private = fcn;
6987 akl->kw[0].parse = action_register_lua;
6988
6989 /* select the action registering point. */
6990 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6991 tcp_req_cont_keywords_register(akl);
6992 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6993 tcp_res_cont_keywords_register(akl);
6994 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6995 http_req_keywords_register(akl);
6996 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6997 http_res_keywords_register(akl);
6998 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006999 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007000 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
7001 "are expected.", lua_tostring(L, -1)));
7002
7003 /* pop the environment string. */
7004 lua_pop(L, 1);
7005 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007006 return ACT_RET_PRS_OK;
7007}
7008
7009static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7010 struct act_rule *rule, char **err)
7011{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007012 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007013
7014 /* Memory for the rule. */
7015 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7016 if (!rule->arg.hlua_rule) {
7017 memprintf(err, "out of memory error");
7018 return ACT_RET_PRS_ERR;
7019 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007020
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007021 /* Reference the Lua function and store the reference. */
7022 rule->arg.hlua_rule->fcn = *fcn;
7023
7024 /* TODO: later accept arguments. */
7025 rule->arg.hlua_rule->args = NULL;
7026
7027 /* Add applet pointer in the rule. */
7028 rule->applet.obj_type = OBJ_TYPE_APPLET;
7029 rule->applet.name = fcn->name;
7030 rule->applet.init = hlua_applet_tcp_init;
7031 rule->applet.fct = hlua_applet_tcp_fct;
7032 rule->applet.release = hlua_applet_tcp_release;
7033 rule->applet.timeout = hlua_timeout_applet;
7034
7035 return 0;
7036}
7037
7038/* This function is an LUA binding used for registering
7039 * "sample-conv" functions. It expects a converter name used
7040 * in the haproxy configuration file, and an LUA function.
7041 */
7042__LJMP static int hlua_register_service(lua_State *L)
7043{
7044 struct action_kw_list *akl;
7045 const char *name;
7046 const char *env;
7047 int ref;
7048 int len;
7049 struct hlua_function *fcn;
7050
7051 MAY_LJMP(check_args(L, 3, "register_service"));
7052
7053 /* First argument : converter name. */
7054 name = MAY_LJMP(luaL_checkstring(L, 1));
7055
7056 /* Second argument : environment. */
7057 env = MAY_LJMP(luaL_checkstring(L, 2));
7058
7059 /* Third argument : lua function. */
7060 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7061
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007062 /* Allocate and fill the sample fetch keyword struct. */
7063 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7064 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007065 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007066 fcn = calloc(1, sizeof(*fcn));
7067 if (!fcn)
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
7070 /* Fill fcn. */
7071 len = strlen("<lua.>") + strlen(name) + 1;
7072 fcn->name = calloc(1, len);
7073 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007074 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007075 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7076 fcn->function_ref = ref;
7077
7078 /* List head */
7079 akl->list.n = akl->list.p = NULL;
7080
7081 /* converter keyword. */
7082 len = strlen("lua.") + strlen(name) + 1;
7083 akl->kw[0].kw = calloc(1, len);
7084 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007085 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007086
7087 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7088
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007089 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007090 if (strcmp(env, "tcp") == 0)
7091 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007092 else if (strcmp(env, "http") == 0)
7093 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007094 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007095 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007096 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007097
7098 akl->kw[0].match_pfx = 0;
7099 akl->kw[0].private = fcn;
7100
7101 /* End of array. */
7102 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7103
7104 /* Register this new converter */
7105 service_keywords_register(akl);
7106
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007107 return 0;
7108}
7109
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007110/* This function initialises Lua cli handler. It copies the
7111 * arguments in the Lua stack and create channel IO objects.
7112 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007113static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007114{
7115 struct hlua *hlua;
7116 struct hlua_function *fcn;
7117 int i;
7118 const char *error;
7119
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007120 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007121 appctx->ctx.hlua_cli.fcn = private;
7122
Willy Tarreaubafbe012017-11-24 17:34:44 +01007123 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007124 if (!hlua) {
7125 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007126 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007127 }
7128 HLUA_INIT(hlua);
7129 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007130
7131 /* Create task used by signal to wakeup applets.
7132 * We use the same wakeup fonction than the Lua applet_tcp and
7133 * applet_http. It is absolutely compatible.
7134 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007135 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007136 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007137 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007138 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007139 }
7140 appctx->ctx.hlua_cli.task->nice = 0;
7141 appctx->ctx.hlua_cli.task->context = appctx;
7142 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7143
7144 /* Initialises the Lua context */
7145 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
7146 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007147 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007148 }
7149
7150 /* The following Lua calls can fail. */
7151 if (!SET_SAFE_LJMP(hlua->T)) {
7152 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7153 error = lua_tostring(hlua->T, -1);
7154 else
7155 error = "critical error";
7156 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7157 goto error;
7158 }
7159
7160 /* Check stack available size. */
7161 if (!lua_checkstack(hlua->T, 2)) {
7162 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7163 goto error;
7164 }
7165
7166 /* Restore the function in the stack. */
7167 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7168
7169 /* Once the arguments parsed, the CLI is like an AppletTCP,
7170 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007171 */
7172 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7173 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7174 goto error;
7175 }
7176 hlua->nargs = 1;
7177
7178 /* push keywords in the stack. */
7179 for (i = 0; *args[i]; i++) {
7180 /* Check stack available size. */
7181 if (!lua_checkstack(hlua->T, 1)) {
7182 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7183 goto error;
7184 }
7185 lua_pushstring(hlua->T, args[i]);
7186 hlua->nargs++;
7187 }
7188
7189 /* We must initialize the execution timeouts. */
7190 hlua->max_time = hlua_timeout_session;
7191
7192 /* At this point the execution is safe. */
7193 RESET_SAFE_LJMP(hlua->T);
7194
7195 /* It's ok */
7196 return 0;
7197
7198 /* It's not ok. */
7199error:
7200 RESET_SAFE_LJMP(hlua->T);
7201 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007202 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007203 return 1;
7204}
7205
7206static int hlua_cli_io_handler_fct(struct appctx *appctx)
7207{
7208 struct hlua *hlua;
7209 struct stream_interface *si;
7210 struct hlua_function *fcn;
7211
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007212 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007213 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007214 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007215
7216 /* If the stream is disconnect or closed, ldo nothing. */
7217 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7218 return 1;
7219
7220 /* Execute the function. */
7221 switch (hlua_ctx_resume(hlua, 1)) {
7222
7223 /* finished. */
7224 case HLUA_E_OK:
7225 return 1;
7226
7227 /* yield. */
7228 case HLUA_E_AGAIN:
7229 /* We want write. */
7230 if (HLUA_IS_WAKERESWR(hlua))
7231 si_applet_cant_put(si);
7232 /* Set the timeout. */
7233 if (hlua->wake_time != TICK_ETERNITY)
7234 task_schedule(hlua->task, hlua->wake_time);
7235 return 0;
7236
7237 /* finished with error. */
7238 case HLUA_E_ERRMSG:
7239 /* Display log. */
7240 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
7241 fcn->name, lua_tostring(hlua->T, -1));
7242 lua_pop(hlua->T, 1);
7243 return 1;
7244
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007245 case HLUA_E_ETMOUT:
7246 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
7247 fcn->name);
7248 return 1;
7249
7250 case HLUA_E_NOMEM:
7251 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
7252 fcn->name);
7253 return 1;
7254
7255 case HLUA_E_YIELD: /* unexpected */
7256 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
7257 fcn->name);
7258 return 1;
7259
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007260 case HLUA_E_ERR:
7261 /* Display log. */
7262 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
7263 fcn->name);
7264 return 1;
7265
7266 default:
7267 return 1;
7268 }
7269
7270 return 1;
7271}
7272
7273static void hlua_cli_io_release_fct(struct appctx *appctx)
7274{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007275 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007276 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007277}
7278
7279/* This function is an LUA binding used for registering
7280 * new keywords in the cli. It expects a list of keywords
7281 * which are the "path". It is limited to 5 keywords. A
7282 * description of the command, a function to be executed
7283 * for the parsing and a function for io handlers.
7284 */
7285__LJMP static int hlua_register_cli(lua_State *L)
7286{
7287 struct cli_kw_list *cli_kws;
7288 const char *message;
7289 int ref_io;
7290 int len;
7291 struct hlua_function *fcn;
7292 int index;
7293 int i;
7294
7295 MAY_LJMP(check_args(L, 3, "register_cli"));
7296
7297 /* First argument : an array of maximum 5 keywords. */
7298 if (!lua_istable(L, 1))
7299 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
7300
7301 /* Second argument : string with contextual message. */
7302 message = MAY_LJMP(luaL_checkstring(L, 2));
7303
7304 /* Third and fourth argument : lua function. */
7305 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
7306
7307 /* Allocate and fill the sample fetch keyword struct. */
7308 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
7309 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007310 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007311 fcn = calloc(1, sizeof(*fcn));
7312 if (!fcn)
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
7315 /* Fill path. */
7316 index = 0;
7317 lua_pushnil(L);
7318 while(lua_next(L, 1) != 0) {
7319 if (index >= 5)
7320 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
7321 if (lua_type(L, -1) != LUA_TSTRING)
7322 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
7323 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
7324 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007325 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007326 index++;
7327 lua_pop(L, 1);
7328 }
7329
7330 /* Copy help message. */
7331 cli_kws->kw[0].usage = strdup(message);
7332 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007333 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007334
7335 /* Fill fcn io handler. */
7336 len = strlen("<lua.cli>") + 1;
7337 for (i = 0; i < index; i++)
7338 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
7339 fcn->name = calloc(1, len);
7340 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007341 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007342 strncat((char *)fcn->name, "<lua.cli", len);
7343 for (i = 0; i < index; i++) {
7344 strncat((char *)fcn->name, ".", len);
7345 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
7346 }
7347 strncat((char *)fcn->name, ">", len);
7348 fcn->function_ref = ref_io;
7349
7350 /* Fill last entries. */
7351 cli_kws->kw[0].private = fcn;
7352 cli_kws->kw[0].parse = hlua_cli_parse_fct;
7353 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
7354 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
7355
7356 /* Register this new converter */
7357 cli_register_kw(cli_kws);
7358
7359 return 0;
7360}
7361
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007362static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7363 struct proxy *defpx, const char *file, int line,
7364 char **err, unsigned int *timeout)
7365{
7366 const char *error;
7367
7368 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
7369 if (error && *error != '\0') {
7370 memprintf(err, "%s: invalid timeout", args[0]);
7371 return -1;
7372 }
7373 return 0;
7374}
7375
7376static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7377 struct proxy *defpx, const char *file, int line,
7378 char **err)
7379{
7380 return hlua_read_timeout(args, section_type, curpx, defpx,
7381 file, line, err, &hlua_timeout_session);
7382}
7383
7384static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7385 struct proxy *defpx, const char *file, int line,
7386 char **err)
7387{
7388 return hlua_read_timeout(args, section_type, curpx, defpx,
7389 file, line, err, &hlua_timeout_task);
7390}
7391
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007392static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7393 struct proxy *defpx, const char *file, int line,
7394 char **err)
7395{
7396 return hlua_read_timeout(args, section_type, curpx, defpx,
7397 file, line, err, &hlua_timeout_applet);
7398}
7399
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007400static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7401 struct proxy *defpx, const char *file, int line,
7402 char **err)
7403{
7404 char *error;
7405
7406 hlua_nb_instruction = strtoll(args[1], &error, 10);
7407 if (*error != '\0') {
7408 memprintf(err, "%s: invalid number", args[0]);
7409 return -1;
7410 }
7411 return 0;
7412}
7413
Willy Tarreau32f61e22015-03-18 17:54:59 +01007414static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7415 struct proxy *defpx, const char *file, int line,
7416 char **err)
7417{
7418 char *error;
7419
7420 if (*(args[1]) == 0) {
7421 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7422 return -1;
7423 }
7424 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7425 if (*error != '\0') {
7426 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7427 return -1;
7428 }
7429 return 0;
7430}
7431
7432
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007433/* This function is called by the main configuration key "lua-load". It loads and
7434 * execute an lua file during the parsing of the HAProxy configuration file. It is
7435 * the main lua entry point.
7436 *
7437 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7438 * occured, otherwise it returns 0.
7439 *
7440 * In some error case, LUA set an error message in top of the stack. This function
7441 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007442 *
7443 * This function can fail with an abort() due to an Lua critical error.
7444 * We are in the configuration parsing process of HAProxy, this abort() is
7445 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007446 */
7447static int hlua_load(char **args, int section_type, struct proxy *curpx,
7448 struct proxy *defpx, const char *file, int line,
7449 char **err)
7450{
7451 int error;
7452
7453 /* Just load and compile the file. */
7454 error = luaL_loadfile(gL.T, args[1]);
7455 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007456 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007457 lua_pop(gL.T, 1);
7458 return -1;
7459 }
7460
7461 /* If no syntax error where detected, execute the code. */
7462 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7463 switch (error) {
7464 case LUA_OK:
7465 break;
7466 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007467 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007468 lua_pop(gL.T, 1);
7469 return -1;
7470 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007471 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007472 return -1;
7473 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007474 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007475 lua_pop(gL.T, 1);
7476 return -1;
7477 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007478 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007479 lua_pop(gL.T, 1);
7480 return -1;
7481 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007482 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007483 lua_pop(gL.T, 1);
7484 return -1;
7485 }
7486
7487 return 0;
7488}
7489
7490/* configuration keywords declaration */
7491static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007492 { CFG_GLOBAL, "lua-load", hlua_load },
7493 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7494 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007495 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007496 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007497 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007498 { 0, NULL, NULL },
7499}};
7500
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007501/* This function can fail with an abort() due to an Lua critical error.
7502 * We are in the initialisation process of HAProxy, this abort() is
7503 * tolerated.
7504 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007505int hlua_post_init()
7506{
7507 struct hlua_init_function *init;
7508 const char *msg;
7509 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007510 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007511
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007512 /* Call post initialisation function in safe environement. */
7513 if (!SET_SAFE_LJMP(gL.T)) {
7514 if (lua_type(gL.T, -1) == LUA_TSTRING)
7515 error = lua_tostring(gL.T, -1);
7516 else
7517 error = "critical error";
7518 fprintf(stderr, "Lua post-init: %s.\n", error);
7519 exit(1);
7520 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02007521
7522#if USE_OPENSSL
7523 /* Initialize SSL server. */
7524 if (socket_ssl.xprt->prepare_srv) {
7525 int saved_used_backed = global.ssl_used_backend;
7526 // don't affect maxconn automatic computation
7527 socket_ssl.xprt->prepare_srv(&socket_ssl);
7528 global.ssl_used_backend = saved_used_backed;
7529 }
7530#endif
7531
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007532 hlua_fcn_post_init(gL.T);
7533 RESET_SAFE_LJMP(gL.T);
7534
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007535 list_for_each_entry(init, &hlua_init_functions, l) {
7536 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7537 ret = hlua_ctx_resume(&gL, 0);
7538 switch (ret) {
7539 case HLUA_E_OK:
7540 lua_pop(gL.T, -1);
7541 return 1;
7542 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007543 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007544 return 0;
7545 case HLUA_E_ERRMSG:
7546 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01007547 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007548 return 0;
7549 case HLUA_E_ERR:
7550 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007551 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007552 return 0;
7553 }
7554 }
7555 return 1;
7556}
7557
Willy Tarreau32f61e22015-03-18 17:54:59 +01007558/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7559 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7560 * is the previously allocated size or the kind of object in case of a new
7561 * allocation. <nsize> is the requested new size.
7562 */
7563static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7564{
7565 struct hlua_mem_allocator *zone = ud;
7566
7567 if (nsize == 0) {
7568 /* it's a free */
7569 if (ptr)
7570 zone->allocated -= osize;
7571 free(ptr);
7572 return NULL;
7573 }
7574
7575 if (!ptr) {
7576 /* it's a new allocation */
7577 if (zone->limit && zone->allocated + nsize > zone->limit)
7578 return NULL;
7579
7580 ptr = malloc(nsize);
7581 if (ptr)
7582 zone->allocated += nsize;
7583 return ptr;
7584 }
7585
7586 /* it's a realloc */
7587 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7588 return NULL;
7589
7590 ptr = realloc(ptr, nsize);
7591 if (ptr)
7592 zone->allocated += nsize - osize;
7593 return ptr;
7594}
7595
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007596/* Ithis function can fail with an abort() due to an Lua critical error.
7597 * We are in the initialisation process of HAProxy, this abort() is
7598 * tolerated.
7599 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007600void hlua_init(void)
7601{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007602 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007603 int idx;
7604 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007605 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007606 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007607 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007608#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007609 struct srv_kw *kw;
7610 int tmp_error;
7611 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007612 char *args[] = { /* SSL client configuration. */
7613 "ssl",
7614 "verify",
7615 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007616 NULL
7617 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007618#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007619
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007620 HA_SPIN_INIT(&hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02007621
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007622 /* Initialise struct hlua and com signals pool */
Willy Tarreaubafbe012017-11-24 17:34:44 +01007623 pool_head_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007624
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007625 /* Register configuration keywords. */
7626 cfg_register_keywords(&cfg_kws);
7627
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007628 /* Init main lua stack. */
7629 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007630 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007631 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007632 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007633 hlua_sethlua(&gL);
7634 gL.Tref = LUA_REFNIL;
7635 gL.task = NULL;
7636
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007637 /* From this point, until the end of the initialisation fucntion,
7638 * the Lua function can fail with an abort. We are in the initialisation
7639 * process of HAProxy, this abort() is tolerated.
7640 */
7641
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007642 /* Initialise lua. */
7643 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007644
Thierry Fournier75933d42016-01-21 09:30:18 +01007645 /* Set safe environment for the initialisation. */
7646 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007647 if (lua_type(gL.T, -1) == LUA_TSTRING)
7648 error_msg = lua_tostring(gL.T, -1);
7649 else
7650 error_msg = "critical error";
7651 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007652 exit(1);
7653 }
7654
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007655 /*
7656 *
7657 * Create "core" object.
7658 *
7659 */
7660
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007661 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007662 lua_newtable(gL.T);
7663
7664 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007665 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007666 hlua_class_const_int(gL.T, log_levels[i], i);
7667
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007668 /* Register special functions. */
7669 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007670 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007671 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007672 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007673 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007674 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007675 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007676 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007677 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007678 hlua_class_function(gL.T, "sleep", hlua_sleep);
7679 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007680 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7681 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7682 hlua_class_function(gL.T, "set_map", hlua_set_map);
7683 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007684 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007685 hlua_class_function(gL.T, "log", hlua_log);
7686 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7687 hlua_class_function(gL.T, "Info", hlua_log_info);
7688 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7689 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007690 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007691 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007692
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007693 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007694
7695 /*
7696 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007697 * Register class Map
7698 *
7699 */
7700
7701 /* This table entry is the object "Map" base. */
7702 lua_newtable(gL.T);
7703
7704 /* register pattern types. */
7705 for (i=0; i<PAT_MATCH_NUM; i++)
7706 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007707 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007708 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
7709 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007710 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007711
7712 /* register constructor. */
7713 hlua_class_function(gL.T, "new", hlua_map_new);
7714
7715 /* Create and fill the metatable. */
7716 lua_newtable(gL.T);
7717
7718 /* Create and fille the __index entry. */
7719 lua_pushstring(gL.T, "__index");
7720 lua_newtable(gL.T);
7721
7722 /* Register . */
7723 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7724 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7725
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007726 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007727
Thierry Fournier45e78d72016-02-19 18:34:46 +01007728 /* Register previous table in the registry with reference and named entry.
7729 * The function hlua_register_metatable() pops the stack, so we
7730 * previously create a copy of the table.
7731 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007732 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007733 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007734
7735 /* Assign the metatable to the mai Map object. */
7736 lua_setmetatable(gL.T, -2);
7737
7738 /* Set a name to the table. */
7739 lua_setglobal(gL.T, "Map");
7740
7741 /*
7742 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007743 * Register class Channel
7744 *
7745 */
7746
7747 /* Create and fill the metatable. */
7748 lua_newtable(gL.T);
7749
7750 /* Create and fille the __index entry. */
7751 lua_pushstring(gL.T, "__index");
7752 lua_newtable(gL.T);
7753
7754 /* Register . */
7755 hlua_class_function(gL.T, "get", hlua_channel_get);
7756 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7757 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7758 hlua_class_function(gL.T, "set", hlua_channel_set);
7759 hlua_class_function(gL.T, "append", hlua_channel_append);
7760 hlua_class_function(gL.T, "send", hlua_channel_send);
7761 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7762 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7763 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007764 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007765
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007766 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007767
7768 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007769 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007770
7771 /*
7772 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007773 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007774 *
7775 */
7776
7777 /* Create and fill the metatable. */
7778 lua_newtable(gL.T);
7779
7780 /* Create and fille the __index entry. */
7781 lua_pushstring(gL.T, "__index");
7782 lua_newtable(gL.T);
7783
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007784 /* Browse existing fetches and create the associated
7785 * object method.
7786 */
7787 sf = NULL;
7788 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7789
7790 /* Dont register the keywork if the arguments check function are
7791 * not safe during the runtime.
7792 */
7793 if ((sf->val_args != NULL) &&
7794 (sf->val_args != val_payload_lv) &&
7795 (sf->val_args != val_hdr))
7796 continue;
7797
7798 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7799 * by an underscore.
7800 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007801 strncpy(trash.area, sf->kw, trash.size);
7802 trash.area[trash.size - 1] = '\0';
7803 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007804 if (*p == '.' || *p == '-' || *p == '+')
7805 *p = '_';
7806
7807 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007808 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007809 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007810 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007811 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007812 }
7813
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007814 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007815
7816 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007817 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007818
7819 /*
7820 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007821 * Register class Converters
7822 *
7823 */
7824
7825 /* Create and fill the metatable. */
7826 lua_newtable(gL.T);
7827
7828 /* Create and fill the __index entry. */
7829 lua_pushstring(gL.T, "__index");
7830 lua_newtable(gL.T);
7831
7832 /* Browse existing converters and create the associated
7833 * object method.
7834 */
7835 sc = NULL;
7836 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7837 /* Dont register the keywork if the arguments check function are
7838 * not safe during the runtime.
7839 */
7840 if (sc->val_args != NULL)
7841 continue;
7842
7843 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7844 * by an underscore.
7845 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007846 strncpy(trash.area, sc->kw, trash.size);
7847 trash.area[trash.size - 1] = '\0';
7848 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007849 if (*p == '.' || *p == '-' || *p == '+')
7850 *p = '_';
7851
7852 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007853 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007854 lua_pushlightuserdata(gL.T, sc);
7855 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007856 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007857 }
7858
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007859 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007860
7861 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007862 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007863
7864 /*
7865 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007866 * Register class HTTP
7867 *
7868 */
7869
7870 /* Create and fill the metatable. */
7871 lua_newtable(gL.T);
7872
7873 /* Create and fille the __index entry. */
7874 lua_pushstring(gL.T, "__index");
7875 lua_newtable(gL.T);
7876
7877 /* Register Lua functions. */
7878 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7879 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7880 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7881 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7882 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7883 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7884 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7885 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7886 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7887 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7888
7889 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7890 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7891 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7892 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7893 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7894 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007895 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007896
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007897 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007898
7899 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007900 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007901
7902 /*
7903 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007904 * Register class AppletTCP
7905 *
7906 */
7907
7908 /* Create and fill the metatable. */
7909 lua_newtable(gL.T);
7910
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007911 /* Create and fille the __index entry. */
7912 lua_pushstring(gL.T, "__index");
7913 lua_newtable(gL.T);
7914
7915 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007916 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7917 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7918 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7919 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7920 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007921 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7922 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7923 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007924
7925 lua_settable(gL.T, -3);
7926
7927 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007928 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007929
7930 /*
7931 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007932 * Register class AppletHTTP
7933 *
7934 */
7935
7936 /* Create and fill the metatable. */
7937 lua_newtable(gL.T);
7938
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007939 /* Create and fille the __index entry. */
7940 lua_pushstring(gL.T, "__index");
7941 lua_newtable(gL.T);
7942
7943 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007944 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7945 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007946 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7947 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7948 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007949 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7950 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7951 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7952 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7953 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7954 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7955
7956 lua_settable(gL.T, -3);
7957
7958 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007959 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007960
7961 /*
7962 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007963 * Register class TXN
7964 *
7965 */
7966
7967 /* Create and fill the metatable. */
7968 lua_newtable(gL.T);
7969
7970 /* Create and fille the __index entry. */
7971 lua_pushstring(gL.T, "__index");
7972 lua_newtable(gL.T);
7973
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007974 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04007975 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7976 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
7977 hlua_class_function(gL.T, "set_var", hlua_set_var);
7978 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
7979 hlua_class_function(gL.T, "get_var", hlua_get_var);
7980 hlua_class_function(gL.T, "done", hlua_txn_done);
7981 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
7982 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7983 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
7984 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
7985 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
7986 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7987 hlua_class_function(gL.T, "log", hlua_txn_log);
7988 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7989 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7990 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7991 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007992
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007993 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007994
7995 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007996 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007997
7998 /*
7999 *
8000 * Register class Socket
8001 *
8002 */
8003
8004 /* Create and fill the metatable. */
8005 lua_newtable(gL.T);
8006
8007 /* Create and fille the __index entry. */
8008 lua_pushstring(gL.T, "__index");
8009 lua_newtable(gL.T);
8010
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008011#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008012 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008013#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008014 hlua_class_function(gL.T, "connect", hlua_socket_connect);
8015 hlua_class_function(gL.T, "send", hlua_socket_send);
8016 hlua_class_function(gL.T, "receive", hlua_socket_receive);
8017 hlua_class_function(gL.T, "close", hlua_socket_close);
8018 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
8019 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8020 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8021 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8022
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008023 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008024
8025 /* Register the garbage collector entry. */
8026 lua_pushstring(gL.T, "__gc");
8027 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008028 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008029
8030 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008031 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008032
8033 /* Proxy and server configuration initialisation. */
8034 memset(&socket_proxy, 0, sizeof(socket_proxy));
8035 init_new_proxy(&socket_proxy);
8036 socket_proxy.parent = NULL;
8037 socket_proxy.last_change = now.tv_sec;
8038 socket_proxy.id = "LUA-SOCKET";
8039 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8040 socket_proxy.maxconn = 0;
8041 socket_proxy.accept = NULL;
8042 socket_proxy.options2 |= PR_O2_INDEPSTR;
8043 socket_proxy.srv = NULL;
8044 socket_proxy.conn_retries = 0;
8045 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8046
8047 /* Init TCP server: unchanged parameters */
8048 memset(&socket_tcp, 0, sizeof(socket_tcp));
8049 socket_tcp.next = NULL;
8050 socket_tcp.proxy = &socket_proxy;
8051 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8052 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008053 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008054 socket_tcp.priv_conns = NULL;
8055 socket_tcp.idle_conns = NULL;
8056 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008057 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008058 socket_tcp.last_change = 0;
8059 socket_tcp.id = "LUA-TCP-CONN";
8060 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8061 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8062 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
8063
8064 /* XXX: Copy default parameter from default server,
8065 * but the default server is not initialized.
8066 */
8067 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
8068 socket_tcp.minconn = socket_proxy.defsrv.minconn;
8069 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
8070 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
8071 socket_tcp.onerror = socket_proxy.defsrv.onerror;
8072 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8073 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
8074 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8075 socket_tcp.uweight = socket_proxy.defsrv.iweight;
8076 socket_tcp.iweight = socket_proxy.defsrv.iweight;
8077
8078 socket_tcp.check.status = HCHK_STATUS_INI;
8079 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
8080 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
8081 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
8082 socket_tcp.check.server = &socket_tcp;
8083
8084 socket_tcp.agent.status = HCHK_STATUS_INI;
8085 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
8086 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
8087 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
8088 socket_tcp.agent.server = &socket_tcp;
8089
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008090 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008091
8092#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008093 /* Init TCP server: unchanged parameters */
8094 memset(&socket_ssl, 0, sizeof(socket_ssl));
8095 socket_ssl.next = NULL;
8096 socket_ssl.proxy = &socket_proxy;
8097 socket_ssl.obj_type = OBJ_TYPE_SERVER;
8098 LIST_INIT(&socket_ssl.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008099 socket_ssl.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008100 socket_tcp.priv_conns = NULL;
8101 socket_tcp.idle_conns = NULL;
8102 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008103 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008104 socket_ssl.last_change = 0;
8105 socket_ssl.id = "LUA-SSL-CONN";
8106 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8107 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8108 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8109
8110 /* XXX: Copy default parameter from default server,
8111 * but the default server is not initialized.
8112 */
8113 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8114 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8115 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8116 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8117 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8118 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8119 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8120 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8121 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8122 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8123
8124 socket_ssl.check.status = HCHK_STATUS_INI;
8125 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8126 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8127 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8128 socket_ssl.check.server = &socket_ssl;
8129
8130 socket_ssl.agent.status = HCHK_STATUS_INI;
8131 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8132 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8133 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8134 socket_ssl.agent.server = &socket_ssl;
8135
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008136 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008137 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008138
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008139 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008140 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8141 /*
8142 *
8143 * If the keyword is not known, we can search in the registered
8144 * server keywords. This is usefull to configure special SSL
8145 * features like client certificates and ssl_verify.
8146 *
8147 */
8148 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8149 if (tmp_error != 0) {
8150 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8151 abort(); /* This must be never arrives because the command line
8152 not editable by the user. */
8153 }
8154 idx += kw->skip;
8155 }
8156 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008157#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008158
8159 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008160}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008161
8162__attribute__((constructor))
8163static void __hlua_init(void)
8164{
8165 char *ptr = NULL;
8166 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8167 hap_register_build_opts(ptr, 1);
8168}