blob: 2364317745a9e378aebf8db94f68f36b1f7d7267 [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>
Willy Tarreaub059b892018-10-16 17:57:36 +020028#include <common/compiler.h>
Thierry FOURNIER2da788e2017-09-11 18:37:23 +020029#include <common/xref.h>
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +020030#include <common/hathreads.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010031
William Lallemand9ed62032016-11-21 17:49:11 +010032#include <types/cli.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010033#include <types/hlua.h>
34#include <types/proxy.h>
William Lallemand9ed62032016-11-21 17:49:11 +010035#include <types/stats.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010036
Thierry FOURNIER55da1652015-01-23 11:36:30 +010037#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020038#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010039#include <proto/channel.h>
William Lallemand9ed62032016-11-21 17:49:11 +010040#include <proto/cli.h>
Willy Tarreaua71f6422016-11-16 17:00:14 +010041#include <proto/connection.h>
William Lallemand9ed62032016-11-21 17:49:11 +010042#include <proto/stats.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010043#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010044#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010045#include <proto/hlua_fcn.h>
Willy Tarreau79e57332018-10-02 16:01:16 +020046#include <proto/http_fetch.h>
Willy Tarreau61c112a2018-10-02 16:43:32 +020047#include <proto/http_rules.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020048#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010049#include <proto/obj_type.h>
Patrick Hemmer268a7072018-05-11 12:52:31 -040050#include <proto/queue.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010051#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010052#include <proto/payload.h>
53#include <proto/proto_http.h>
54#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010055#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020056#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020057#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010058#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010059#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010060#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020061#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010062
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010063/* Lua uses longjmp to perform yield or throwing errors. This
64 * macro is used only for identifying the function that can
65 * not return because a longjmp is executed.
66 * __LJMP marks a prototype of hlua file that can use longjmp.
67 * WILL_LJMP() marks an lua function that will use longjmp.
68 * MAY_LJMP() marks an lua function that may use longjmp.
69 */
70#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020071#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010072#define MAY_LJMP(func) func
73
Thierry FOURNIERbabae282015-09-17 11:36:37 +020074/* This couple of function executes securely some Lua calls outside of
75 * the lua runtime environment. Each Lua call can return a longjmp
76 * if it encounter a memory error.
77 *
78 * Lua documentation extract:
79 *
80 * If an error happens outside any protected environment, Lua calls
81 * a panic function (see lua_atpanic) and then calls abort, thus
82 * exiting the host application. Your panic function can avoid this
83 * exit by never returning (e.g., doing a long jump to your own
84 * recovery point outside Lua).
85 *
86 * The panic function runs as if it were a message handler (see
87 * §2.3); in particular, the error message is at the top of the
88 * stack. However, there is no guarantee about stack space. To push
89 * anything on the stack, the panic function must first check the
90 * available space (see §4.2).
91 *
92 * We must check all the Lua entry point. This includes:
93 * - The include/proto/hlua.h exported functions
94 * - the task wrapper function
95 * - The action wrapper function
96 * - The converters wrapper function
97 * - The sample-fetch wrapper functions
98 *
99 * It is tolerated that the initilisation function returns an abort.
100 * Before each Lua abort, an error message is writed on stderr.
101 *
102 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
103 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
104 * because they must be exists in the program stack when the longjmp
105 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200106 *
107 * Note that the Lua processing is not really thread safe. It provides
108 * heavy system which consists to add our own lock function in the Lua
109 * code and recompile the library. This system will probably not accepted
110 * by maintainers of various distribs.
111 *
112 * Our main excution point of the Lua is the function lua_resume(). A
113 * quick looking on the Lua sources displays a lua_lock() a the start
114 * of function and a lua_unlock() at the end of the function. So I
115 * conclude that the Lua thread safe mode just perform a mutex around
116 * all execution. So I prefer to do this in the HAProxy code, it will be
117 * easier for distro maintainers.
118 *
119 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
120 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
121 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200122 */
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100123__decl_hathreads(HA_SPINLOCK_T hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200124THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200125static int hlua_panic_safe(lua_State *L) { return 0; }
126static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
127
128#define SET_SAFE_LJMP(__L) \
129 ({ \
130 int ret; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100131 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200132 if (setjmp(safe_ljmp_env) != 0) { \
133 lua_atpanic(__L, hlua_panic_safe); \
134 ret = 0; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100135 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200136 } else { \
137 lua_atpanic(__L, hlua_panic_ljmp); \
138 ret = 1; \
139 } \
140 ret; \
141 })
142
143/* If we are the last function catching Lua errors, we
144 * must reset the panic function.
145 */
146#define RESET_SAFE_LJMP(__L) \
147 do { \
148 lua_atpanic(__L, hlua_panic_safe); \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100149 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200150 } while(0)
151
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200152/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200153#define APPLET_DONE 0x01 /* applet processing is done. */
154#define APPLET_100C 0x02 /* 100 continue expected. */
155#define APPLET_HDR_SENT 0x04 /* Response header sent. */
156#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
157#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100158#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200159
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100160/* The main Lua execution context. */
161struct hlua gL;
162
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100163/* This is the memory pool containing struct lua for applets
164 * (including cli).
165 */
Willy Tarreaubafbe012017-11-24 17:34:44 +0100166struct pool_head *pool_head_hlua;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100167
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100168/* Used for Socket connection. */
169static struct proxy socket_proxy;
170static struct server socket_tcp;
171#ifdef USE_OPENSSL
172static struct server socket_ssl;
173#endif
174
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100175/* List head of the function called at the initialisation time. */
176struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
177
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100178/* The following variables contains the reference of the different
179 * Lua classes. These references are useful for identify metadata
180 * associated with an object.
181 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100182static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100183static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100184static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100185static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100186static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100187static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200188static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200189static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200190static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100191
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100192/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200193 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100194 * short timeout. Lua linked with tasks doesn't have a timeout
195 * because a task may remain alive during all the haproxy execution.
196 */
197static unsigned int hlua_timeout_session = 4000; /* session timeout. */
198static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200199static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100200
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100201/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
202 * it is used for preventing infinite loops.
203 *
204 * I test the scheer with an infinite loop containing one incrementation
205 * and one test. I run this loop between 10 seconds, I raise a ceil of
206 * 710M loops from one interrupt each 9000 instructions, so I fix the value
207 * to one interrupt each 10 000 instructions.
208 *
209 * configured | Number of
210 * instructions | loops executed
211 * between two | in milions
212 * forced yields |
213 * ---------------+---------------
214 * 10 | 160
215 * 500 | 670
216 * 1000 | 680
217 * 5000 | 700
218 * 7000 | 700
219 * 8000 | 700
220 * 9000 | 710 <- ceil
221 * 10000 | 710
222 * 100000 | 710
223 * 1000000 | 710
224 *
225 */
226static unsigned int hlua_nb_instruction = 10000;
227
Willy Tarreau32f61e22015-03-18 17:54:59 +0100228/* Descriptor for the memory allocation state. If limit is not null, it will
229 * be enforced on any memory allocation.
230 */
231struct hlua_mem_allocator {
232 size_t allocated;
233 size_t limit;
234};
235
236static struct hlua_mem_allocator hlua_global_allocator;
237
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200238static const char error_500[] =
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200239 "HTTP/1.0 500 Internal Server Error\r\n"
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200240 "Cache-Control: no-cache\r\n"
241 "Connection: close\r\n"
242 "Content-Type: text/html\r\n"
243 "\r\n"
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200244 "<html><body><h1>500 Internal Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200245
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100246/* These functions converts types between HAProxy internal args or
247 * sample and LUA types. Another function permits to check if the
248 * LUA stack contains arguments according with an required ARG_T
249 * format.
250 */
251static int hlua_arg2lua(lua_State *L, const struct arg *arg);
252static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100253__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100254 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100255static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100256static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100257static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
258
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200259__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
260
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200261#define SEND_ERR(__be, __fmt, __args...) \
262 do { \
263 send_log(__be, LOG_ERR, __fmt, ## __args); \
264 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100265 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200266 } while (0)
267
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100268/* Used to check an Lua function type in the stack. It creates and
269 * returns a reference of the function. This function throws an
270 * error if the rgument is not a "function".
271 */
272__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
273{
274 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100275 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100276 WILL_LJMP(luaL_argerror(L, argno, msg));
277 }
278 lua_pushvalue(L, argno);
279 return luaL_ref(L, LUA_REGISTRYINDEX);
280}
281
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200282/* Return the string that is of the top of the stack. */
283const char *hlua_get_top_error_string(lua_State *L)
284{
285 if (lua_gettop(L) < 1)
286 return "unknown error";
287 if (lua_type(L, -1) != LUA_TSTRING)
288 return "unknown error";
289 return lua_tostring(L, -1);
290}
291
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200292__LJMP static const char *hlua_traceback(lua_State *L)
293{
294 lua_Debug ar;
295 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200296 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200297 int filled = 0;
298
299 while (lua_getstack(L, level++, &ar)) {
300
301 /* Add separator */
302 if (filled)
303 chunk_appendf(msg, ", ");
304 filled = 1;
305
306 /* Fill fields:
307 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
308 * 'l': fills in the field currentline;
309 * 'n': fills in the field name and namewhat;
310 * 't': fills in the field istailcall;
311 */
312 lua_getinfo(L, "Slnt", &ar);
313
314 /* Append code localisation */
315 if (ar.currentline > 0)
316 chunk_appendf(msg, "%s:%d ", ar.short_src, ar.currentline);
317 else
318 chunk_appendf(msg, "%s ", ar.short_src);
319
320 /*
321 * Get function name
322 *
323 * if namewhat is no empty, name is defined.
324 * what contains "Lua" for Lua function, "C" for C function,
325 * or "main" for main code.
326 */
327 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
328 chunk_appendf(msg, "%s '%s'", ar.namewhat, ar.name); /* use it */
329
330 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
331 chunk_appendf(msg, "main chunk");
332
333 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
334 chunk_appendf(msg, "C function line %d", ar.linedefined);
335
336 else /* nothing left... */
337 chunk_appendf(msg, "?");
338
339
340 /* Display tailed call */
341 if (ar.istailcall)
342 chunk_appendf(msg, " ...");
343 }
344
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200345 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200346}
347
348
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100349/* This function check the number of arguments available in the
350 * stack. If the number of arguments available is not the same
351 * then <nb> an error is throwed.
352 */
353__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
354{
355 if (lua_gettop(L) == nb)
356 return;
357 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
358}
359
Mark Lakes22154b42018-01-29 14:38:40 -0800360/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100361 * and the line number where the error is encountered.
362 */
363static int hlua_pusherror(lua_State *L, const char *fmt, ...)
364{
365 va_list argp;
366 va_start(argp, fmt);
367 luaL_where(L, 1);
368 lua_pushvfstring(L, fmt, argp);
369 va_end(argp);
370 lua_concat(L, 2);
371 return 1;
372}
373
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100374/* This functions is used with sample fetch and converters. It
375 * converts the HAProxy configuration argument in a lua stack
376 * values.
377 *
378 * It takes an array of "arg", and each entry of the array is
379 * converted and pushed in the LUA stack.
380 */
381static int hlua_arg2lua(lua_State *L, const struct arg *arg)
382{
383 switch (arg->type) {
384 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100385 case ARGT_TIME:
386 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100387 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100388 break;
389
390 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200391 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100392 break;
393
394 case ARGT_IPV4:
395 case ARGT_IPV6:
396 case ARGT_MSK4:
397 case ARGT_MSK6:
398 case ARGT_FE:
399 case ARGT_BE:
400 case ARGT_TAB:
401 case ARGT_SRV:
402 case ARGT_USR:
403 case ARGT_MAP:
404 default:
405 lua_pushnil(L);
406 break;
407 }
408 return 1;
409}
410
411/* This function take one entrie in an LUA stack at the index "ud",
412 * and try to convert it in an HAProxy argument entry. This is useful
413 * with sample fetch wrappers. The input arguments are gived to the
414 * lua wrapper and converted as arg list by thi function.
415 */
416static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
417{
418 switch (lua_type(L, ud)) {
419
420 case LUA_TNUMBER:
421 case LUA_TBOOLEAN:
422 arg->type = ARGT_SINT;
423 arg->data.sint = lua_tointeger(L, ud);
424 break;
425
426 case LUA_TSTRING:
427 arg->type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200428 arg->data.str.area = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100429 break;
430
431 case LUA_TUSERDATA:
432 case LUA_TNIL:
433 case LUA_TTABLE:
434 case LUA_TFUNCTION:
435 case LUA_TTHREAD:
436 case LUA_TLIGHTUSERDATA:
437 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200438 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100439 break;
440 }
441 return 1;
442}
443
444/* the following functions are used to convert a struct sample
445 * in Lua type. This useful to convert the return of the
446 * fetchs or converters.
447 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100448static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100449{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200450 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100451 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100452 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200453 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100454 break;
455
456 case SMP_T_BIN:
457 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200458 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100459 break;
460
461 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200462 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100463 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
464 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
465 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
466 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
467 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
468 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
469 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
470 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
471 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200472 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100473 break;
474 default:
475 lua_pushnil(L);
476 break;
477 }
478 break;
479
480 case SMP_T_IPV4:
481 case SMP_T_IPV6:
482 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200483 if (sample_casts[smp->data.type][SMP_T_STR] &&
484 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200485 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100486 else
487 lua_pushnil(L);
488 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100489 default:
490 lua_pushnil(L);
491 break;
492 }
493 return 1;
494}
495
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100496/* the following functions are used to convert a struct sample
497 * in Lua strings. This is useful to convert the return of the
498 * fetchs or converters.
499 */
500static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
501{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200502 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100503
504 case SMP_T_BIN:
505 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200506 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100507 break;
508
509 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200510 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100511 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
512 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
513 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
514 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
515 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
516 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
517 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
518 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
519 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200520 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100521 break;
522 default:
523 lua_pushstring(L, "");
524 break;
525 }
526 break;
527
528 case SMP_T_SINT:
529 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100530 case SMP_T_IPV4:
531 case SMP_T_IPV6:
532 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200533 if (sample_casts[smp->data.type][SMP_T_STR] &&
534 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200535 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100536 else
537 lua_pushstring(L, "");
538 break;
539 default:
540 lua_pushstring(L, "");
541 break;
542 }
543 return 1;
544}
545
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100546/* the following functions are used to convert an Lua type in a
547 * struct sample. This is useful to provide data from a converter
548 * to the LUA code.
549 */
550static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
551{
552 switch (lua_type(L, ud)) {
553
554 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200555 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200556 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100557 break;
558
559
560 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200561 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200562 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100563 break;
564
565 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200566 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100567 smp->flags |= SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200568 smp->data.u.str.area = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100569 break;
570
571 case LUA_TUSERDATA:
572 case LUA_TNIL:
573 case LUA_TTABLE:
574 case LUA_TFUNCTION:
575 case LUA_TTHREAD:
576 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200577 case LUA_TNONE:
578 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200579 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200580 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100581 break;
582 }
583 return 1;
584}
585
586/* This function check the "argp" builded by another conversion function
587 * is in accord with the expected argp defined by the "mask". The fucntion
588 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100589 *
590 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
591 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100592 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100593__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100594 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100595{
596 int min_arg;
597 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100598 struct proxy *px;
599 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100600
601 idx = 0;
602 min_arg = ARGM(mask);
603 mask >>= ARGM_BITS;
604
605 while (1) {
606
607 /* Check oversize. */
608 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100609 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100610 }
611
612 /* Check for mandatory arguments. */
613 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100614 if (idx < min_arg) {
615
616 /* If miss other argument than the first one, we return an error. */
617 if (idx > 0)
618 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
619
620 /* If first argument have a certain type, some default values
621 * may be used. See the function smp_resolve_args().
622 */
623 switch (mask & ARGT_MASK) {
624
625 case ARGT_FE:
626 if (!(p->cap & PR_CAP_FE))
627 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
628 argp[idx].data.prx = p;
629 argp[idx].type = ARGT_FE;
630 argp[idx+1].type = ARGT_STOP;
631 break;
632
633 case ARGT_BE:
634 if (!(p->cap & PR_CAP_BE))
635 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
636 argp[idx].data.prx = p;
637 argp[idx].type = ARGT_BE;
638 argp[idx+1].type = ARGT_STOP;
639 break;
640
641 case ARGT_TAB:
642 argp[idx].data.prx = p;
643 argp[idx].type = ARGT_TAB;
644 argp[idx+1].type = ARGT_STOP;
645 break;
646
647 default:
648 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
649 break;
650 }
651 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100652 return 0;
653 }
654
655 /* Check for exceed the number of requiered argument. */
656 if ((mask & ARGT_MASK) == ARGT_STOP &&
657 argp[idx].type != ARGT_STOP) {
658 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
659 }
660
661 if ((mask & ARGT_MASK) == ARGT_STOP &&
662 argp[idx].type == ARGT_STOP) {
663 return 0;
664 }
665
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100666 /* Convert some argument types. */
667 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100668 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100669 if (argp[idx].type != ARGT_SINT)
670 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
671 argp[idx].type = ARGT_SINT;
672 break;
673
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100674 case ARGT_TIME:
675 if (argp[idx].type != ARGT_SINT)
676 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200677 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100678 break;
679
680 case ARGT_SIZE:
681 if (argp[idx].type != ARGT_SINT)
682 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200683 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100684 break;
685
686 case ARGT_FE:
687 if (argp[idx].type != ARGT_STR)
688 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200689 memcpy(trash.area, argp[idx].data.str.area,
690 argp[idx].data.str.data);
691 trash.area[argp[idx].data.str.data] = 0;
692 argp[idx].data.prx = proxy_fe_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100693 if (!argp[idx].data.prx)
694 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
695 argp[idx].type = ARGT_FE;
696 break;
697
698 case ARGT_BE:
699 if (argp[idx].type != ARGT_STR)
700 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200701 memcpy(trash.area, argp[idx].data.str.area,
702 argp[idx].data.str.data);
703 trash.area[argp[idx].data.str.data] = 0;
704 argp[idx].data.prx = proxy_be_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100705 if (!argp[idx].data.prx)
706 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
707 argp[idx].type = ARGT_BE;
708 break;
709
710 case ARGT_TAB:
711 if (argp[idx].type != ARGT_STR)
712 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200713 memcpy(trash.area, argp[idx].data.str.area,
714 argp[idx].data.str.data);
715 trash.area[argp[idx].data.str.data] = 0;
716 argp[idx].data.prx = proxy_tbl_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100717 if (!argp[idx].data.prx)
718 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
719 argp[idx].type = ARGT_TAB;
720 break;
721
722 case ARGT_SRV:
723 if (argp[idx].type != ARGT_STR)
724 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200725 memcpy(trash.area, argp[idx].data.str.area,
726 argp[idx].data.str.data);
727 trash.area[argp[idx].data.str.data] = 0;
728 sname = strrchr(trash.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100729 if (sname) {
730 *sname++ = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200731 pname = trash.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200732 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100733 if (!px)
734 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
735 }
736 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200737 sname = trash.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100738 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100739 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100740 argp[idx].data.srv = findserver(px, sname);
741 if (!argp[idx].data.srv)
742 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
743 argp[idx].type = ARGT_SRV;
744 break;
745
746 case ARGT_IPV4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200747 memcpy(trash.area, argp[idx].data.str.area,
748 argp[idx].data.str.data);
749 trash.area[argp[idx].data.str.data] = 0;
750 if (inet_pton(AF_INET, trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100751 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
752 argp[idx].type = ARGT_IPV4;
753 break;
754
755 case ARGT_MSK4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200756 memcpy(trash.area, argp[idx].data.str.area,
757 argp[idx].data.str.data);
758 trash.area[argp[idx].data.str.data] = 0;
759 if (!str2mask(trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100760 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
761 argp[idx].type = ARGT_MSK4;
762 break;
763
764 case ARGT_IPV6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200765 memcpy(trash.area, argp[idx].data.str.area,
766 argp[idx].data.str.data);
767 trash.area[argp[idx].data.str.data] = 0;
768 if (inet_pton(AF_INET6, trash.area, &argp[idx].data.ipv6))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100769 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
770 argp[idx].type = ARGT_IPV6;
771 break;
772
773 case ARGT_MSK6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200774 memcpy(trash.area, argp[idx].data.str.area,
775 argp[idx].data.str.data);
776 trash.area[argp[idx].data.str.data] = 0;
777 if (!str2mask6(trash.area, &argp[idx].data.ipv6))
Tim Duesterhusb814da62018-01-25 16:24:50 +0100778 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 mask"));
779 argp[idx].type = ARGT_MSK6;
780 break;
781
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100782 case ARGT_MAP:
783 case ARGT_REG:
784 case ARGT_USR:
785 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100786 break;
787 }
788
789 /* Check for type of argument. */
790 if ((mask & ARGT_MASK) != argp[idx].type) {
791 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
792 arg_type_names[(mask & ARGT_MASK)],
793 arg_type_names[argp[idx].type & ARGT_MASK]);
794 WILL_LJMP(luaL_argerror(L, first + idx, msg));
795 }
796
797 /* Next argument. */
798 mask >>= ARGT_BITS;
799 idx++;
800 }
801}
802
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100803/*
804 * The following functions are used to make correspondance between the the
805 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100806 *
807 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100808 * - hlua_sethlua : create the association between hlua context and lua_state.
809 */
810static inline struct hlua *hlua_gethlua(lua_State *L)
811{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100812 struct hlua **hlua = lua_getextraspace(L);
813 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100814}
815static inline void hlua_sethlua(struct hlua *hlua)
816{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100817 struct hlua **hlua_store = lua_getextraspace(hlua->T);
818 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100819}
820
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100821/* This function is used to send logs. It try to send on screen (stderr)
822 * and on the default syslog server.
823 */
824static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
825{
826 struct tm tm;
827 char *p;
828
829 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200830 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100831 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200832 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200833 /* Break the message if exceed the buffer size. */
834 *(p-4) = ' ';
835 *(p-3) = '.';
836 *(p-2) = '.';
837 *(p-1) = '.';
838 break;
839 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100840 if (isprint(*msg))
841 *p = *msg;
842 else
843 *p = '.';
844 }
845 *p = '\0';
846
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200847 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100848 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200849 get_localtime(date.tv_sec, &tm);
850 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100851 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200852 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100853 fflush(stderr);
854 }
855}
856
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100857/* This function just ensure that the yield will be always
858 * returned with a timeout and permit to set some flags
859 */
860__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100861 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100862{
863 struct hlua *hlua = hlua_gethlua(L);
864
865 /* Set the wake timeout. If timeout is required, we set
866 * the expiration time.
867 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200868 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100869
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100870 hlua->flags |= flags;
871
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100872 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +0200873 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100874}
875
Willy Tarreau87b09662015-04-03 00:22:06 +0200876/* This function initialises the Lua environment stored in the stream.
877 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100878 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200879 *
880 * This function is particular. it initialises a new Lua thread. If the
881 * initialisation fails (example: out of memory error), the lua function
882 * throws an error (longjmp).
883 *
884 * This function manipulates two Lua stack: the main and the thread. Only
885 * the main stack can fail. The thread is not manipulated. This function
886 * MUST NOT manipulate the created thread stack state, because is not
887 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100888 */
889int hlua_ctx_init(struct hlua *lua, struct task *task)
890{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200891 if (!SET_SAFE_LJMP(gL.T)) {
892 lua->Tref = LUA_REFNIL;
893 return 0;
894 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100895 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100896 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100897 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100898 lua->T = lua_newthread(gL.T);
899 if (!lua->T) {
900 lua->Tref = LUA_REFNIL;
Thierry FOURNIER0a976202017-07-12 11:18:00 +0200901 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100902 return 0;
903 }
904 hlua_sethlua(lua);
905 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
906 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200907 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100908 return 1;
909}
910
Willy Tarreau87b09662015-04-03 00:22:06 +0200911/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100912 * is destroyed. The destroy also the memory context. The struct "lua"
913 * is not freed.
914 */
915void hlua_ctx_destroy(struct hlua *lua)
916{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100917 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100918 return;
919
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100920 if (!lua->T)
921 goto end;
922
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100923 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +0200924 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100925
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200926 if (!SET_SAFE_LJMP(lua->T))
927 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100928 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200929 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200930
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200931 if (!SET_SAFE_LJMP(gL.T))
932 return;
933 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
934 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200935 /* Forces a garbage collecting process. If the Lua program is finished
936 * without error, we run the GC on the thread pointer. Its freed all
937 * the unused memory.
938 * If the thread is finnish with an error or is currently yielded,
939 * it seems that the GC applied on the thread doesn't clean anything,
940 * so e run the GC on the main thread.
941 * NOTE: maybe this action locks all the Lua threads untiml the en of
942 * the garbage collection.
943 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200944 if (lua->flags & HLUA_MUST_GC) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200945 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200946 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200947 lua_gc(gL.T, LUA_GCCOLLECT, 0);
948 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200949 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200950
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200951 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100952
953end:
Willy Tarreaubafbe012017-11-24 17:34:44 +0100954 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100955}
956
957/* This function is used to restore the Lua context when a coroutine
958 * fails. This function copy the common memory between old coroutine
959 * and the new coroutine. The old coroutine is destroyed, and its
960 * replaced by the new coroutine.
961 * If the flag "keep_msg" is set, the last entry of the old is assumed
962 * as string error message and it is copied in the new stack.
963 */
964static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
965{
966 lua_State *T;
967 int new_ref;
968
969 /* Renew the main LUA stack doesn't have sense. */
970 if (lua == &gL)
971 return 0;
972
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100973 /* New Lua coroutine. */
974 T = lua_newthread(gL.T);
975 if (!T)
976 return 0;
977
978 /* Copy last error message. */
979 if (keep_msg)
980 lua_xmove(lua->T, T, 1);
981
982 /* Copy data between the coroutines. */
983 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
984 lua_xmove(lua->T, T, 1);
985 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
986
987 /* Destroy old data. */
988 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
989
990 /* The thread is garbage collected by Lua. */
991 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
992
993 /* Fill the struct with the new coroutine values. */
994 lua->Mref = new_ref;
995 lua->T = T;
996 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
997
998 /* Set context. */
999 hlua_sethlua(lua);
1000
1001 return 1;
1002}
1003
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001004void hlua_hook(lua_State *L, lua_Debug *ar)
1005{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001006 struct hlua *hlua = hlua_gethlua(L);
1007
1008 /* Lua cannot yield when its returning from a function,
1009 * so, we can fix the interrupt hook to 1 instruction,
1010 * expecting that the function is finnished.
1011 */
1012 if (lua_gethookmask(L) & LUA_MASKRET) {
1013 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1014 return;
1015 }
1016
1017 /* restore the interrupt condition. */
1018 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1019
1020 /* If we interrupt the Lua processing in yieldable state, we yield.
1021 * If the state is not yieldable, trying yield causes an error.
1022 */
1023 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001024 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001025
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001026 /* If we cannot yield, update the clock and check the timeout. */
1027 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001028 hlua->run_time += now_ms - hlua->start_time;
1029 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001030 lua_pushfstring(L, "execution timeout");
1031 WILL_LJMP(lua_error(L));
1032 }
1033
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001034 /* Update the start time. */
1035 hlua->start_time = now_ms;
1036
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001037 /* Try to interrupt the process at the end of the current
1038 * unyieldable function.
1039 */
1040 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001041}
1042
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001043/* This function start or resumes the Lua stack execution. If the flag
1044 * "yield_allowed" if no set and the LUA stack execution returns a yield
1045 * The function return an error.
1046 *
1047 * The function can returns 4 values:
1048 * - HLUA_E_OK : The execution is terminated without any errors.
1049 * - HLUA_E_AGAIN : The execution must continue at the next associated
1050 * task wakeup.
1051 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
1052 * the top of the stack.
1053 * - HLUA_E_ERR : An error has occured without error message.
1054 *
1055 * If an error occured, the stack is renewed and it is ready to run new
1056 * LUA code.
1057 */
1058static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1059{
1060 int ret;
1061 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001062 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001063
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001064 /* Initialise run time counter. */
1065 if (!HLUA_IS_RUNNING(lua))
1066 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001067
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001068 /* Lock the whole Lua execution. This lock must be before the
1069 * label "resume_execution".
1070 */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001071 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001072
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001073resume_execution:
1074
1075 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1076 * instructions. it is used for preventing infinite loops.
1077 */
1078 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1079
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001080 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001081 HLUA_SET_RUN(lua);
1082 HLUA_CLR_CTRLYIELD(lua);
1083 HLUA_CLR_WAKERESWR(lua);
1084 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001085
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001086 /* Update the start time. */
1087 lua->start_time = now_ms;
1088
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001089 /* Call the function. */
1090 ret = lua_resume(lua->T, gL.T, lua->nargs);
1091 switch (ret) {
1092
1093 case LUA_OK:
1094 ret = HLUA_E_OK;
1095 break;
1096
1097 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001098 /* Check if the execution timeout is expired. It it is the case, we
1099 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001100 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001101 tv_update_date(0, 1);
1102 lua->run_time += now_ms - lua->start_time;
1103 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001104 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001105 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001106 break;
1107 }
1108 /* Process the forced yield. if the general yield is not allowed or
1109 * if no task were associated this the current Lua execution
1110 * coroutine, we resume the execution. Else we want to return in the
1111 * scheduler and we want to be waked up again, to continue the
1112 * current Lua execution. So we schedule our own task.
1113 */
1114 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001115 if (!yield_allowed || !lua->task)
1116 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001117 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001118 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001119 if (!yield_allowed) {
1120 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001121 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001122 break;
1123 }
1124 ret = HLUA_E_AGAIN;
1125 break;
1126
1127 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001128
1129 /* Special exit case. The traditionnal exit is returned as an error
1130 * because the errors ares the only one mean to return immediately
1131 * from and lua execution.
1132 */
1133 if (lua->flags & HLUA_EXIT) {
1134 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001135 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001136 break;
1137 }
1138
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001139 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001140 if (!lua_checkstack(lua->T, 1)) {
1141 ret = HLUA_E_ERR;
1142 break;
1143 }
1144 msg = lua_tostring(lua->T, -1);
1145 lua_settop(lua->T, 0); /* Empty the stack. */
1146 lua_pop(lua->T, 1);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001147 trace = hlua_traceback(lua->T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001148 if (msg)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001149 lua_pushfstring(lua->T, "runtime error: %s from %s", msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001150 else
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001151 lua_pushfstring(lua->T, "unknown runtime error from %s", trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001152 ret = HLUA_E_ERRMSG;
1153 break;
1154
1155 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001156 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001157 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001158 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001159 break;
1160
1161 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001162 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001163 if (!lua_checkstack(lua->T, 1)) {
1164 ret = HLUA_E_ERR;
1165 break;
1166 }
1167 msg = lua_tostring(lua->T, -1);
1168 lua_settop(lua->T, 0); /* Empty the stack. */
1169 lua_pop(lua->T, 1);
1170 if (msg)
1171 lua_pushfstring(lua->T, "message handler error: %s", msg);
1172 else
1173 lua_pushfstring(lua->T, "message handler error");
1174 ret = HLUA_E_ERRMSG;
1175 break;
1176
1177 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001178 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001179 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001180 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001181 break;
1182 }
1183
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001184 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001185 if (lua->flags & HLUA_MUST_GC &&
1186 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001187 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1188
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001189 switch (ret) {
1190 case HLUA_E_AGAIN:
1191 break;
1192
1193 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001194 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001195 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001196 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001197 break;
1198
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001199 case HLUA_E_ETMOUT:
1200 case HLUA_E_NOMEM:
1201 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001202 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001203 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001204 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001205 hlua_ctx_renew(lua, 0);
1206 break;
1207
1208 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001209 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001210 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001211 break;
1212 }
1213
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001214 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001215 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001216
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001217 return ret;
1218}
1219
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001220/* This function exit the current code. */
1221__LJMP static int hlua_done(lua_State *L)
1222{
1223 struct hlua *hlua = hlua_gethlua(L);
1224
1225 hlua->flags |= HLUA_EXIT;
1226 WILL_LJMP(lua_error(L));
1227
1228 return 0;
1229}
1230
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001231/* This function is an LUA binding. It provides a function
1232 * for deleting ACL from a referenced ACL file.
1233 */
1234__LJMP static int hlua_del_acl(lua_State *L)
1235{
1236 const char *name;
1237 const char *key;
1238 struct pat_ref *ref;
1239
1240 MAY_LJMP(check_args(L, 2, "del_acl"));
1241
1242 name = MAY_LJMP(luaL_checkstring(L, 1));
1243 key = MAY_LJMP(luaL_checkstring(L, 2));
1244
1245 ref = pat_ref_lookup(name);
1246 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001247 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001248
1249 pat_ref_delete(ref, key);
1250 return 0;
1251}
1252
1253/* This function is an LUA binding. It provides a function
1254 * for deleting map entry from a referenced map file.
1255 */
1256static int hlua_del_map(lua_State *L)
1257{
1258 const char *name;
1259 const char *key;
1260 struct pat_ref *ref;
1261
1262 MAY_LJMP(check_args(L, 2, "del_map"));
1263
1264 name = MAY_LJMP(luaL_checkstring(L, 1));
1265 key = MAY_LJMP(luaL_checkstring(L, 2));
1266
1267 ref = pat_ref_lookup(name);
1268 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001269 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001270
1271 pat_ref_delete(ref, key);
1272 return 0;
1273}
1274
1275/* This function is an LUA binding. It provides a function
1276 * for adding ACL pattern from a referenced ACL file.
1277 */
1278static int hlua_add_acl(lua_State *L)
1279{
1280 const char *name;
1281 const char *key;
1282 struct pat_ref *ref;
1283
1284 MAY_LJMP(check_args(L, 2, "add_acl"));
1285
1286 name = MAY_LJMP(luaL_checkstring(L, 1));
1287 key = MAY_LJMP(luaL_checkstring(L, 2));
1288
1289 ref = pat_ref_lookup(name);
1290 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001291 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001292
1293 if (pat_ref_find_elt(ref, key) == NULL)
1294 pat_ref_add(ref, key, NULL, NULL);
1295 return 0;
1296}
1297
1298/* This function is an LUA binding. It provides a function
1299 * for setting map pattern and sample from a referenced map
1300 * file.
1301 */
1302static int hlua_set_map(lua_State *L)
1303{
1304 const char *name;
1305 const char *key;
1306 const char *value;
1307 struct pat_ref *ref;
1308
1309 MAY_LJMP(check_args(L, 3, "set_map"));
1310
1311 name = MAY_LJMP(luaL_checkstring(L, 1));
1312 key = MAY_LJMP(luaL_checkstring(L, 2));
1313 value = MAY_LJMP(luaL_checkstring(L, 3));
1314
1315 ref = pat_ref_lookup(name);
1316 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001317 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001318
1319 if (pat_ref_find_elt(ref, key) != NULL)
1320 pat_ref_set(ref, key, value, NULL);
1321 else
1322 pat_ref_add(ref, key, value, NULL);
1323 return 0;
1324}
1325
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001326/* A class is a lot of memory that contain data. This data can be a table,
1327 * an integer or user data. This data is associated with a metatable. This
1328 * metatable have an original version registred in the global context with
1329 * the name of the object (_G[<name>] = <metable> ).
1330 *
1331 * A metable is a table that modify the standard behavior of a standard
1332 * access to the associated data. The entries of this new metatable are
1333 * defined as is:
1334 *
1335 * http://lua-users.org/wiki/MetatableEvents
1336 *
1337 * __index
1338 *
1339 * we access an absent field in a table, the result is nil. This is
1340 * true, but it is not the whole truth. Actually, such access triggers
1341 * the interpreter to look for an __index metamethod: If there is no
1342 * such method, as usually happens, then the access results in nil;
1343 * otherwise, the metamethod will provide the result.
1344 *
1345 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1346 * the key does not appear in the table, but the metatable has an __index
1347 * property:
1348 *
1349 * - if the value is a function, the function is called, passing in the
1350 * table and the key; the return value of that function is returned as
1351 * the result.
1352 *
1353 * - if the value is another table, the value of the key in that table is
1354 * asked for and returned (and if it doesn't exist in that table, but that
1355 * table's metatable has an __index property, then it continues on up)
1356 *
1357 * - Use "rawget(myTable,key)" to skip this metamethod.
1358 *
1359 * http://www.lua.org/pil/13.4.1.html
1360 *
1361 * __newindex
1362 *
1363 * Like __index, but control property assignment.
1364 *
1365 * __mode - Control weak references. A string value with one or both
1366 * of the characters 'k' and 'v' which specifies that the the
1367 * keys and/or values in the table are weak references.
1368 *
1369 * __call - Treat a table like a function. When a table is followed by
1370 * parenthesis such as "myTable( 'foo' )" and the metatable has
1371 * a __call key pointing to a function, that function is invoked
1372 * (passing any specified arguments) and the return value is
1373 * returned.
1374 *
1375 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1376 * called, if the metatable for myTable has a __metatable
1377 * key, the value of that key is returned instead of the
1378 * actual metatable.
1379 *
1380 * __tostring - Control string representation. When the builtin
1381 * "tostring( myTable )" function is called, if the metatable
1382 * for myTable has a __tostring property set to a function,
1383 * that function is invoked (passing myTable to it) and the
1384 * return value is used as the string representation.
1385 *
1386 * __len - Control table length. When the table length is requested using
1387 * the length operator ( '#' ), if the metatable for myTable has
1388 * a __len key pointing to a function, that function is invoked
1389 * (passing myTable to it) and the return value used as the value
1390 * of "#myTable".
1391 *
1392 * __gc - Userdata finalizer code. When userdata is set to be garbage
1393 * collected, if the metatable has a __gc field pointing to a
1394 * function, that function is first invoked, passing the userdata
1395 * to it. The __gc metamethod is not called for tables.
1396 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1397 *
1398 * Special metamethods for redefining standard operators:
1399 * http://www.lua.org/pil/13.1.html
1400 *
1401 * __add "+"
1402 * __sub "-"
1403 * __mul "*"
1404 * __div "/"
1405 * __unm "!"
1406 * __pow "^"
1407 * __concat ".."
1408 *
1409 * Special methods for redfining standar relations
1410 * http://www.lua.org/pil/13.2.html
1411 *
1412 * __eq "=="
1413 * __lt "<"
1414 * __le "<="
1415 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001416
1417/*
1418 *
1419 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001420 * Class Map
1421 *
1422 *
1423 */
1424
1425/* Returns a struct hlua_map if the stack entry "ud" is
1426 * a class session, otherwise it throws an error.
1427 */
1428__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1429{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001430 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001431}
1432
1433/* This function is the map constructor. It don't need
1434 * the class Map object. It creates and return a new Map
1435 * object. It must be called only during "body" or "init"
1436 * context because it process some filesystem accesses.
1437 */
1438__LJMP static int hlua_map_new(struct lua_State *L)
1439{
1440 const char *fn;
1441 int match = PAT_MATCH_STR;
1442 struct sample_conv conv;
1443 const char *file = "";
1444 int line = 0;
1445 lua_Debug ar;
1446 char *err = NULL;
1447 struct arg args[2];
1448
1449 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1450 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1451
1452 fn = MAY_LJMP(luaL_checkstring(L, 1));
1453
1454 if (lua_gettop(L) >= 2) {
1455 match = MAY_LJMP(luaL_checkinteger(L, 2));
1456 if (match < 0 || match >= PAT_MATCH_NUM)
1457 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1458 }
1459
1460 /* Get Lua filename and line number. */
1461 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1462 lua_getinfo(L, "Sl", &ar); /* get info about it */
1463 if (ar.currentline > 0) { /* is there info? */
1464 file = ar.short_src;
1465 line = ar.currentline;
1466 }
1467 }
1468
1469 /* fill fake sample_conv struct. */
1470 conv.kw = ""; /* unused. */
1471 conv.process = NULL; /* unused. */
1472 conv.arg_mask = 0; /* unused. */
1473 conv.val_args = NULL; /* unused. */
1474 conv.out_type = SMP_T_STR;
1475 conv.private = (void *)(long)match;
1476 switch (match) {
1477 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1478 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1479 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1480 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1481 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1482 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1483 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001484 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001485 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1486 default:
1487 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1488 }
1489
1490 /* fill fake args. */
1491 args[0].type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001492 args[0].data.str.area = (char *)fn;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001493 args[1].type = ARGT_STOP;
1494
1495 /* load the map. */
1496 if (!sample_load_map(args, &conv, file, line, &err)) {
1497 /* error case: we cant use luaL_error because we must
1498 * free the err variable.
1499 */
1500 luaL_where(L, 1);
1501 lua_pushfstring(L, "'new': %s.", err);
1502 lua_concat(L, 2);
1503 free(err);
1504 WILL_LJMP(lua_error(L));
1505 }
1506
1507 /* create the lua object. */
1508 lua_newtable(L);
1509 lua_pushlightuserdata(L, args[0].data.map);
1510 lua_rawseti(L, -2, 0);
1511
1512 /* Pop a class Map metatable and affect it to the userdata. */
1513 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1514 lua_setmetatable(L, -2);
1515
1516
1517 return 1;
1518}
1519
1520__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1521{
1522 struct map_descriptor *desc;
1523 struct pattern *pat;
1524 struct sample smp;
1525
1526 MAY_LJMP(check_args(L, 2, "lookup"));
1527 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001528 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001529 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001530 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001531 }
1532 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001533 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001534 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001535 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 +02001536 }
1537
1538 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001539 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001540 if (str)
1541 lua_pushstring(L, "");
1542 else
1543 lua_pushnil(L);
1544 return 1;
1545 }
1546
1547 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001548 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001549 return 1;
1550}
1551
1552__LJMP static int hlua_map_lookup(struct lua_State *L)
1553{
1554 return _hlua_map_lookup(L, 0);
1555}
1556
1557__LJMP static int hlua_map_slookup(struct lua_State *L)
1558{
1559 return _hlua_map_lookup(L, 1);
1560}
1561
1562/*
1563 *
1564 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001565 * Class Socket
1566 *
1567 *
1568 */
1569
1570__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1571{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001572 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001573}
1574
1575/* This function is the handler called for each I/O on the established
1576 * connection. It is used for notify space avalaible to send or data
1577 * received.
1578 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001579static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001580{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001581 struct stream_interface *si = appctx->owner;
Olivier Houchard9aaf7782017-09-13 18:30:23 +02001582 struct connection *c = cs_conn(objt_cs(si_opposite(si)->end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001583
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001584 if (appctx->ctx.hlua_cosocket.die) {
1585 si_shutw(si);
1586 si_shutr(si);
1587 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001588 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1589 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001590 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1591 }
1592
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001593 /* If the connection object is not avalaible, close all the
1594 * streams and wakeup everithing waiting for.
1595 */
1596 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001597 si_shutw(si);
1598 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001599 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001600 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1601 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001602 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001603 }
1604
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001605 /* If we cant write, wakeup the pending write signals. */
1606 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001607 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001608
1609 /* If we cant read, wakeup the pending read signals. */
1610 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001611 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001612
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001613 /* if the connection is not estabkished, inform the stream that we want
1614 * to be notified whenever the connection completes.
1615 */
1616 if (!(c->flags & CO_FL_CONNECTED)) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01001617 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01001618 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001619 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001620 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001621
1622 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001623 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001624
1625 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001626 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001627 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001628
1629 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001630 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001631 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001632
1633 /* Some data were injected in the buffer, notify the stream
1634 * interface.
1635 */
1636 if (!channel_is_empty(si_ic(si)))
1637 stream_int_update(si);
1638
1639 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001640 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001641 */
1642 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01001643 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001644}
1645
Willy Tarreau87b09662015-04-03 00:22:06 +02001646/* This function is called when the "struct stream" is destroyed.
1647 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001648 * Wake all the pending signals.
1649 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001650static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001651{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001652 struct xref *peer;
1653
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001654 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001655 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1656 if (peer)
1657 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001658
1659 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001660 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1661 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001662}
1663
1664/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001665 * uses this object. If the stream does not exists, just quit.
1666 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001667 * pending signal can rest in the read and write lists. destroy
1668 * it.
1669 */
1670__LJMP static int hlua_socket_gc(lua_State *L)
1671{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001672 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001673 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001674 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001675
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001676 MAY_LJMP(check_args(L, 1, "__gc"));
1677
1678 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001679 peer = xref_get_peer_and_lock(&socket->xref);
1680 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001681 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001682 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001683
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001684 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001685 appctx->ctx.hlua_cosocket.die = 1;
1686 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001687
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001688 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001689 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001690 return 0;
1691}
1692
1693/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001694 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001695 */
sada05ed3302018-05-11 11:48:18 -07001696__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001697{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001698 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001699 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001700 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001701
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001702 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001703
1704 /* Check if we run on the same thread than the xreator thread.
1705 * We cannot access to the socket if the thread is different.
1706 */
1707 if (socket->tid != tid)
1708 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1709
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001710 peer = xref_get_peer_and_lock(&socket->xref);
1711 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001712 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001713 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001714
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001715 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001716 appctx->ctx.hlua_cosocket.die = 1;
1717 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001718
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001719 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001720 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001721 return 0;
1722}
1723
sada05ed3302018-05-11 11:48:18 -07001724/* The close function calls close_helper.
1725 */
1726__LJMP static int hlua_socket_close(lua_State *L)
1727{
1728 MAY_LJMP(check_args(L, 1, "close"));
1729 return hlua_socket_close_helper(L);
1730}
1731
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001732/* This Lua function assumes that the stack contain three parameters.
1733 * 1 - USERDATA containing a struct socket
1734 * 2 - INTEGER with values of the macro defined below
1735 * If the integer is -1, we must read at most one line.
1736 * If the integer is -2, we ust read all the data until the
1737 * end of the stream.
1738 * If the integer is positive value, we must read a number of
1739 * bytes corresponding to this value.
1740 */
1741#define HLSR_READ_LINE (-1)
1742#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001743__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001744{
1745 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1746 int wanted = lua_tointeger(L, 2);
1747 struct hlua *hlua = hlua_gethlua(L);
1748 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001749 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001750 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02001751 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001752 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02001753 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001754 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001755 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001756 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001757 struct stream_interface *si;
1758 struct stream *s;
1759 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001760 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001761
1762 /* Check if this lua stack is schedulable. */
1763 if (!hlua || !hlua->task)
1764 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1765 "'frontend', 'backend' or 'task'"));
1766
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001767 /* Check if we run on the same thread than the xreator thread.
1768 * We cannot access to the socket if the thread is different.
1769 */
1770 if (socket->tid != tid)
1771 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1772
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001773 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001774 peer = xref_get_peer_and_lock(&socket->xref);
1775 if (!peer)
1776 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001777 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1778 si = appctx->owner;
1779 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001780
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001781 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001782 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001783 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001784 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001785 if (nblk < 0) /* Connection close. */
1786 goto connection_closed;
1787 if (nblk == 0) /* No data avalaible. */
1788 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001789
1790 /* remove final \r\n. */
1791 if (nblk == 1) {
1792 if (blk1[len1-1] == '\n') {
1793 len1--;
1794 skip_at_end++;
1795 if (blk1[len1-1] == '\r') {
1796 len1--;
1797 skip_at_end++;
1798 }
1799 }
1800 }
1801 else {
1802 if (blk2[len2-1] == '\n') {
1803 len2--;
1804 skip_at_end++;
1805 if (blk2[len2-1] == '\r') {
1806 len2--;
1807 skip_at_end++;
1808 }
1809 }
1810 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001811 }
1812
1813 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001814 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001815 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001816 if (nblk < 0) /* Connection close. */
1817 goto connection_closed;
1818 if (nblk == 0) /* No data avalaible. */
1819 goto connection_empty;
1820 }
1821
1822 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001823 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001824 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001825 if (nblk < 0) /* Connection close. */
1826 goto connection_closed;
1827 if (nblk == 0) /* No data avalaible. */
1828 goto connection_empty;
1829
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001830 missing_bytes = wanted - socket->b.n;
1831 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001832 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001833 len1 = missing_bytes;
1834 } if (nblk == 2 && len1 + len2 > missing_bytes)
1835 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001836 }
1837
1838 len = len1;
1839
1840 luaL_addlstring(&socket->b, blk1, len1);
1841 if (nblk == 2) {
1842 len += len2;
1843 luaL_addlstring(&socket->b, blk2, len2);
1844 }
1845
1846 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001847 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001848
1849 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02001850 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001851
1852 /* If the pattern reclaim to read all the data
1853 * in the connection, got out.
1854 */
1855 if (wanted == HLSR_READ_ALL)
1856 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001857 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001858 goto connection_empty;
1859
1860 /* Return result. */
1861 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001862 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001863 return 1;
1864
1865connection_closed:
1866
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001867 xref_unlock(&socket->xref, peer);
1868
1869no_peer:
1870
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001871 /* If the buffer containds data. */
1872 if (socket->b.n > 0) {
1873 luaL_pushresult(&socket->b);
1874 return 1;
1875 }
1876 lua_pushnil(L);
1877 lua_pushstring(L, "connection closed.");
1878 return 2;
1879
1880connection_empty:
1881
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001882 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1883 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001884 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001885 }
1886 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02001887 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001888 return 0;
1889}
1890
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001891/* This Lua function gets two parameters. The first one can be string
1892 * or a number. If the string is "*l", the user requires one line. If
1893 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001894 * If the value is a number, the user require a number of bytes equal
1895 * to the value. The default value is "*l" (a line).
1896 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001897 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001898 * integer takes this values:
1899 * -1 : read a line
1900 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001901 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001902 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001903 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001904 * concatenated with the read data.
1905 */
1906__LJMP static int hlua_socket_receive(struct lua_State *L)
1907{
1908 int wanted = HLSR_READ_LINE;
1909 const char *pattern;
1910 int type;
1911 char *error;
1912 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001913 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001914
1915 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1916 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1917
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001918 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001919
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001920 /* Check if we run on the same thread than the xreator thread.
1921 * We cannot access to the socket if the thread is different.
1922 */
1923 if (socket->tid != tid)
1924 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1925
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001926 /* check for pattern. */
1927 if (lua_gettop(L) >= 2) {
1928 type = lua_type(L, 2);
1929 if (type == LUA_TSTRING) {
1930 pattern = lua_tostring(L, 2);
1931 if (strcmp(pattern, "*a") == 0)
1932 wanted = HLSR_READ_ALL;
1933 else if (strcmp(pattern, "*l") == 0)
1934 wanted = HLSR_READ_LINE;
1935 else {
1936 wanted = strtoll(pattern, &error, 10);
1937 if (*error != '\0')
1938 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1939 }
1940 }
1941 else if (type == LUA_TNUMBER) {
1942 wanted = lua_tointeger(L, 2);
1943 if (wanted < 0)
1944 WILL_LJMP(luaL_error(L, "Unsupported size."));
1945 }
1946 }
1947
1948 /* Set pattern. */
1949 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01001950
1951 /* Check if we would replace the top by itself. */
1952 if (lua_gettop(L) != 2)
1953 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001954
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001955 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001956 luaL_buffinit(L, &socket->b);
1957
1958 /* Check prefix. */
1959 if (lua_gettop(L) >= 3) {
1960 if (lua_type(L, 3) != LUA_TSTRING)
1961 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1962 pattern = lua_tolstring(L, 3, &len);
1963 luaL_addlstring(&socket->b, pattern, len);
1964 }
1965
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001966 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001967}
1968
1969/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08001970 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001971 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001972static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001973{
1974 struct hlua_socket *socket;
1975 struct hlua *hlua = hlua_gethlua(L);
1976 struct appctx *appctx;
1977 size_t buf_len;
1978 const char *buf;
1979 int len;
1980 int send_len;
1981 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001982 struct xref *peer;
1983 struct stream_interface *si;
1984 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001985
1986 /* Check if this lua stack is schedulable. */
1987 if (!hlua || !hlua->task)
1988 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1989 "'frontend', 'backend' or 'task'"));
1990
1991 /* Get object */
1992 socket = MAY_LJMP(hlua_checksocket(L, 1));
1993 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001994 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001995
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001996 /* Check if we run on the same thread than the xreator thread.
1997 * We cannot access to the socket if the thread is different.
1998 */
1999 if (socket->tid != tid)
2000 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2001
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002002 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002003 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002004 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002005 lua_pushinteger(L, -1);
2006 return 1;
2007 }
2008 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2009 si = appctx->owner;
2010 s = si_strm(si);
2011
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002012 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002013 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002014 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002015 lua_pushinteger(L, -1);
2016 return 1;
2017 }
2018
2019 /* Update the input buffer data. */
2020 buf += sent;
2021 send_len = buf_len - sent;
2022
2023 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002024 if (sent >= buf_len) {
2025 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002026 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002027 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002028
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002029 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2030 * the request buffer if its not required.
2031 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002032 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002033 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002034 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002035 }
2036
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002037 /* Check for avalaible space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002038 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002039 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002040 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002041 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002042
2043 /* send data */
2044 if (len < send_len)
2045 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002046 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002047
2048 /* "Not enough space" (-1), "Buffer too little to contain
2049 * the data" (-2) are not expected because the available length
2050 * is tested.
2051 * Other unknown error are also not expected.
2052 */
2053 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002054 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002055 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002056
sada05ed3302018-05-11 11:48:18 -07002057 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002058 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002059 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002060 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002061 return 1;
2062 }
2063
2064 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002065 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002066
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002067 s->req.rex = TICK_ETERNITY;
2068 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002069
2070 /* Update length sent. */
2071 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002072 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002073
2074 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002075 if (sent + len >= buf_len) {
2076 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002077 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002078 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002079
2080hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002081 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2082 xref_unlock(&socket->xref, peer);
2083 WILL_LJMP(luaL_error(L, "out of memory"));
2084 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002085 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002086 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002087 return 0;
2088}
2089
2090/* This function initiate the send of data. It just check the input
2091 * parameters and push an integer in the Lua stack that contain the
2092 * amount of data writed in the buffer. This is used by the function
2093 * "hlua_socket_write_yield" that can yield.
2094 *
2095 * The Lua function gets between 3 and 4 parameters. The first one is
2096 * the associated object. The second is a string buffer. The third is
2097 * a facultative integer that represents where is the buffer position
2098 * of the start of the data that can send. The first byte is the
2099 * position "1". The default value is "1". The fourth argument is a
2100 * facultative integer that represents where is the buffer position
2101 * of the end of the data that can send. The default is the last byte.
2102 */
2103static int hlua_socket_send(struct lua_State *L)
2104{
2105 int i;
2106 int j;
2107 const char *buf;
2108 size_t buf_len;
2109
2110 /* Check number of arguments. */
2111 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2112 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2113
2114 /* Get the string. */
2115 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2116
2117 /* Get and check j. */
2118 if (lua_gettop(L) == 4) {
2119 j = MAY_LJMP(luaL_checkinteger(L, 4));
2120 if (j < 0)
2121 j = buf_len + j + 1;
2122 if (j > buf_len)
2123 j = buf_len + 1;
2124 lua_pop(L, 1);
2125 }
2126 else
2127 j = buf_len;
2128
2129 /* Get and check i. */
2130 if (lua_gettop(L) == 3) {
2131 i = MAY_LJMP(luaL_checkinteger(L, 3));
2132 if (i < 0)
2133 i = buf_len + i + 1;
2134 if (i > buf_len)
2135 i = buf_len + 1;
2136 lua_pop(L, 1);
2137 } else
2138 i = 1;
2139
2140 /* Check bth i and j. */
2141 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002142 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002143 return 1;
2144 }
2145 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002146 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002147 return 1;
2148 }
2149 if (i == 0)
2150 i = 1;
2151 if (j == 0)
2152 j = 1;
2153
2154 /* Pop the string. */
2155 lua_pop(L, 1);
2156
2157 /* Update the buffer length. */
2158 buf += i - 1;
2159 buf_len = j - i + 1;
2160 lua_pushlstring(L, buf, buf_len);
2161
2162 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002163 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002164
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002165 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002166}
2167
Willy Tarreau22b0a682015-06-17 19:43:49 +02002168#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002169__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2170{
2171 static char buffer[SOCKET_INFO_MAX_LEN];
2172 int ret;
2173 int len;
2174 char *p;
2175
2176 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2177 if (ret <= 0) {
2178 lua_pushnil(L);
2179 return 1;
2180 }
2181
2182 if (ret == AF_UNIX) {
2183 lua_pushstring(L, buffer+1);
2184 return 1;
2185 }
2186 else if (ret == AF_INET6) {
2187 buffer[0] = '[';
2188 len = strlen(buffer);
2189 buffer[len] = ']';
2190 len++;
2191 buffer[len] = ':';
2192 len++;
2193 p = buffer;
2194 }
2195 else if (ret == AF_INET) {
2196 p = buffer + 1;
2197 len = strlen(p);
2198 p[len] = ':';
2199 len++;
2200 }
2201 else {
2202 lua_pushnil(L);
2203 return 1;
2204 }
2205
2206 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2207 lua_pushnil(L);
2208 return 1;
2209 }
2210
2211 lua_pushstring(L, p);
2212 return 1;
2213}
2214
2215/* Returns information about the peer of the connection. */
2216__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2217{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002218 struct hlua_socket *socket;
2219 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002220 struct xref *peer;
2221 struct appctx *appctx;
2222 struct stream_interface *si;
2223 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002224 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002225
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226 MAY_LJMP(check_args(L, 1, "getpeername"));
2227
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002228 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002229
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002230 /* Check if we run on the same thread than the xreator thread.
2231 * We cannot access to the socket if the thread is different.
2232 */
2233 if (socket->tid != tid)
2234 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2235
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002236 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002237 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002238 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002239 lua_pushnil(L);
2240 return 1;
2241 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002242 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2243 si = appctx->owner;
2244 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002245
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002246 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002247 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002248 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002249 lua_pushnil(L);
2250 return 1;
2251 }
2252
Willy Tarreaua71f6422016-11-16 17:00:14 +01002253 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002254 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002255 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002256 lua_pushnil(L);
2257 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002258 }
2259
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002260 ret = MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2261 xref_unlock(&socket->xref, peer);
2262 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002263}
2264
2265/* Returns information about my connection side. */
2266static int hlua_socket_getsockname(struct lua_State *L)
2267{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002268 struct hlua_socket *socket;
2269 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002270 struct appctx *appctx;
2271 struct xref *peer;
2272 struct stream_interface *si;
2273 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002274 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002275
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002276 MAY_LJMP(check_args(L, 1, "getsockname"));
2277
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002278 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002279
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002280 /* Check if we run on the same thread than the xreator thread.
2281 * We cannot access to the socket if the thread is different.
2282 */
2283 if (socket->tid != tid)
2284 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2285
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002286 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002287 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002288 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002289 lua_pushnil(L);
2290 return 1;
2291 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002292 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2293 si = appctx->owner;
2294 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002295
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002296 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002297 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002298 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002299 lua_pushnil(L);
2300 return 1;
2301 }
2302
Willy Tarreaua71f6422016-11-16 17:00:14 +01002303 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002304 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002305 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002306 lua_pushnil(L);
2307 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002308 }
2309
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002310 ret = hlua_socket_info(L, &conn->addr.from);
2311 xref_unlock(&socket->xref, peer);
2312 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313}
2314
2315/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002316static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002317 .obj_type = OBJ_TYPE_APPLET,
2318 .name = "<LUA_TCP>",
2319 .fct = hlua_socket_handler,
2320 .release = hlua_socket_release,
2321};
2322
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002323__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002324{
2325 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2326 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002327 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002328 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002329 struct stream_interface *si;
2330 struct stream *s;
2331
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002332 /* Check if we run on the same thread than the xreator thread.
2333 * We cannot access to the socket if the thread is different.
2334 */
2335 if (socket->tid != tid)
2336 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2337
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002338 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002339 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002340 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002341 lua_pushnil(L);
2342 lua_pushstring(L, "Can't connect");
2343 return 2;
2344 }
2345 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2346 si = appctx->owner;
2347 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002348
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002349 /* Check if we run on the same thread than the xreator thread.
2350 * We cannot access to the socket if the thread is different.
2351 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002352 if (socket->tid != tid) {
2353 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002354 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002355 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002356
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002357 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002358 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002359 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002360 lua_pushnil(L);
2361 lua_pushstring(L, "Can't connect");
2362 return 2;
2363 }
2364
Willy Tarreaue09101e2018-10-16 17:37:12 +02002365 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002366
2367 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002368 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002369 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002370 lua_pushinteger(L, 1);
2371 return 1;
2372 }
2373
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002374 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2375 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002376 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002377 }
2378 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002379 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002380 return 0;
2381}
2382
2383/* This function fail or initite the connection. */
2384__LJMP static int hlua_socket_connect(struct lua_State *L)
2385{
2386 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002387 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002388 const char *ip;
2389 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002390 struct hlua *hlua;
2391 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002392 int low, high;
2393 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002394 struct xref *peer;
2395 struct stream_interface *si;
2396 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002397
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002398 if (lua_gettop(L) < 2)
2399 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002400
2401 /* Get args. */
2402 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002403
2404 /* Check if we run on the same thread than the xreator thread.
2405 * We cannot access to the socket if the thread is different.
2406 */
2407 if (socket->tid != tid)
2408 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2409
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002410 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002411 if (lua_gettop(L) >= 3) {
2412 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002413 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002414
Tim Duesterhus6edab862018-01-06 19:04:45 +01002415 /* Force the ip to end with a colon, to support IPv6 addresses
2416 * that are not enclosed within square brackets.
2417 */
2418 if (port > 0) {
2419 luaL_buffinit(L, &b);
2420 luaL_addstring(&b, ip);
2421 luaL_addchar(&b, ':');
2422 luaL_pushresult(&b);
2423 ip = lua_tolstring(L, lua_gettop(L), NULL);
2424 }
2425 }
2426
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002427 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002428 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002429 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002430 lua_pushnil(L);
2431 return 1;
2432 }
2433 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2434 si = appctx->owner;
2435 s = si_strm(si);
2436
2437 /* Initialise connection. */
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002438 conn = cs_conn(si_alloc_cs(&s->si[1], NULL));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002439 if (!conn) {
2440 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002441 WILL_LJMP(luaL_error(L, "connect: internal error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002442 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002443
Willy Tarreau3adac082015-09-26 17:51:09 +02002444 /* needed for the connection not to be closed */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002445 conn->target = s->target;
Willy Tarreau3adac082015-09-26 17:51:09 +02002446
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002447 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002448 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002449 if (!addr) {
2450 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002451 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002452 }
2453 if (low != high) {
2454 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002455 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002456 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002457 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002458
2459 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002460 if (low == 0) {
2461 if (conn->addr.to.ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002462 if (port == -1) {
2463 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002464 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002465 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002466 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2467 } else if (conn->addr.to.ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002468 if (port == -1) {
2469 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002470 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002471 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002472 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2473 }
2474 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002475
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002476 hlua = hlua_gethlua(L);
Willy Tarreaue09101e2018-10-16 17:37:12 +02002477 appctx = __objt_appctx(s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002478
2479 /* inform the stream that we want to be notified whenever the
2480 * connection completes.
2481 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002482 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002483 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002484 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002485
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002486 hlua->flags |= HLUA_MUST_GC;
2487
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002488 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2489 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002490 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002491 }
2492 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002493
2494 task_wakeup(s->task, TASK_WOKEN_INIT);
2495 /* Return yield waiting for connection. */
2496
Willy Tarreau9635e032018-10-16 17:52:55 +02002497 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002498
2499 return 0;
2500}
2501
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002502#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002503__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2504{
2505 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002506 struct xref *peer;
2507 struct appctx *appctx;
2508 struct stream_interface *si;
2509 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002510
2511 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2512 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002513
2514 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002515 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002516 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002517 lua_pushnil(L);
2518 return 1;
2519 }
2520 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2521 si = appctx->owner;
2522 s = si_strm(si);
2523
2524 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002525 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002526 return MAY_LJMP(hlua_socket_connect(L));
2527}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002528#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002529
2530__LJMP static int hlua_socket_setoption(struct lua_State *L)
2531{
2532 return 0;
2533}
2534
2535__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2536{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002537 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002538 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002539 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002540 struct xref *peer;
2541 struct appctx *appctx;
2542 struct stream_interface *si;
2543 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002544
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002545 MAY_LJMP(check_args(L, 2, "settimeout"));
2546
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002547 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002548
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002549 /* convert the timeout to millis */
2550 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002551
Thierry Fournier17a921b2018-03-08 09:59:02 +01002552 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002553 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002554 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2555
Mark Lakes56cc1252018-03-27 09:48:06 +02002556 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002557 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002558
2559 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002560 if (tmout == 0)
2561 tmout++; /* very small timeouts are adjusted to a minium of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002562
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002563 /* Check if we run on the same thread than the xreator thread.
2564 * We cannot access to the socket if the thread is different.
2565 */
2566 if (socket->tid != tid)
2567 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2568
Mark Lakes56cc1252018-03-27 09:48:06 +02002569 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002570 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002571 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002572 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2573 WILL_LJMP(lua_error(L));
2574 return 0;
2575 }
2576 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2577 si = appctx->owner;
2578 s = si_strm(si);
2579
Cyril Bonté7bb63452018-08-17 23:51:02 +02002580 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002581 s->req.rto = tmout;
2582 s->req.wto = tmout;
2583 s->res.rto = tmout;
2584 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002585 s->req.rex = tick_add_ifset(now_ms, tmout);
2586 s->req.wex = tick_add_ifset(now_ms, tmout);
2587 s->res.rex = tick_add_ifset(now_ms, tmout);
2588 s->res.wex = tick_add_ifset(now_ms, tmout);
2589
2590 s->task->expire = tick_add_ifset(now_ms, tmout);
2591 task_queue(s->task);
2592
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002593 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002594
Thierry Fourniere9636f12018-03-08 09:54:32 +01002595 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002596 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002597}
2598
2599__LJMP static int hlua_socket_new(lua_State *L)
2600{
2601 struct hlua_socket *socket;
2602 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002603 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002604 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002605
2606 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002607 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002608 hlua_pusherror(L, "socket: full stack");
2609 goto out_fail_conf;
2610 }
2611
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002612 /* Create the object: obj[0] = userdata. */
2613 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002614 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002615 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002616 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002617 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002618
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002619 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002620 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002621 hlua_pusherror(L, "socket: uninitialized pools.");
2622 goto out_fail_conf;
2623 }
2624
Willy Tarreau87b09662015-04-03 00:22:06 +02002625 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002626 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2627 lua_setmetatable(L, -2);
2628
Willy Tarreaud420a972015-04-06 00:39:18 +02002629 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002630 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002631 if (!appctx) {
2632 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002633 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002634 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002635
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002636 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002637 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002638 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2639 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002640
Willy Tarreaud420a972015-04-06 00:39:18 +02002641 /* Now create a session, task and stream for this applet */
2642 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2643 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002644 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002645 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002646 }
2647
Willy Tarreau87787ac2017-08-28 16:22:54 +02002648 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002649 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002650 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002651 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002652 }
2653
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002654 /* Initialise cross reference between stream and Lua socket object. */
2655 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002656
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002657 /* Configure "right" stream interface. this "si" is used to connect
2658 * and retrieve data from the server. The connection is initialized
2659 * with the "struct server".
2660 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002661 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002662
2663 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002664 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2665 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002666
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002667 return 1;
2668
Willy Tarreaud420a972015-04-06 00:39:18 +02002669 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002670 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002671 out_fail_sess:
2672 appctx_free(appctx);
2673 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002674 WILL_LJMP(lua_error(L));
2675 return 0;
2676}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002677
2678/*
2679 *
2680 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002681 * Class Channel
2682 *
2683 *
2684 */
2685
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002686/* The state between the channel data and the HTTP parser state can be
2687 * unconsistent, so reset the parser and call it again. Warning, this
2688 * action not revalidate the request and not send a 400 if the modified
2689 * resuest is not valid.
2690 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002691 * This function never fails. The direction is set using dir, which equals
2692 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002693 */
2694static void hlua_resynchonize_proto(struct stream *stream, int dir)
2695{
2696 /* Protocol HTTP. */
2697 if (stream->be->mode == PR_MODE_HTTP) {
2698
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002699 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002700 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002701 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002702 http_txn_reset_res(stream->txn);
2703
2704 if (stream->txn->hdr_idx.v)
2705 hdr_idx_init(&stream->txn->hdr_idx);
2706
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002707 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002708 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002709 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002710 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2711 }
2712}
2713
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002714/* This function is called before the Lua execution. It stores
2715 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002716 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002717static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002718{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002719 c->mode = stream->be->mode;
2720 switch (c->mode) {
2721 case PR_MODE_HTTP:
2722 c->data.http.dir = opt & SMP_OPT_DIR;
2723 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2724 c->data.http.state = stream->txn->req.msg_state;
2725 else
2726 c->data.http.state = stream->txn->rsp.msg_state;
2727 break;
2728 default:
2729 break;
2730 }
2731}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002732
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002733/* This function is called after the Lua execution. it
2734 * returns true if the parser state is consistent, otherwise,
2735 * it return false.
2736 *
2737 * In HTTP mode, the parser state must be in the same state
2738 * or greater when we exit the function. Even if we do a
2739 * control yield. This prevent to break the HTTP message
2740 * from the Lua code.
2741 */
2742static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2743{
2744 if (c->mode != stream->be->mode)
2745 return 0;
2746
2747 switch (c->mode) {
2748 case PR_MODE_HTTP:
2749 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002750 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002751 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2752 return stream->txn->req.msg_state >= c->data.http.state;
2753 else
2754 return stream->txn->rsp.msg_state >= c->data.http.state;
2755 default:
2756 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002757 }
2758 return 1;
2759}
2760
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002761/* Returns the struct hlua_channel join to the class channel in the
2762 * stack entry "ud" or throws an argument error.
2763 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002764__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002765{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002766 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002767}
2768
Willy Tarreau47860ed2015-03-10 14:07:50 +01002769/* Pushes the channel onto the top of the stack. If the stask does not have a
2770 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002771 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002772static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002773{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002774 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002775 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002776 return 0;
2777
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002778 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002779 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002780 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002781
2782 /* Pop a class sesison metatable and affect it to the userdata. */
2783 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2784 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002785 return 1;
2786}
2787
2788/* Duplicate all the data present in the input channel and put it
2789 * in a string LUA variables. Returns -1 and push a nil value in
2790 * the stack if the channel is closed and all the data are consumed,
2791 * returns 0 if no data are available, otherwise it returns the length
2792 * of the builded string.
2793 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002794static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002795{
2796 char *blk1;
2797 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002798 size_t len1;
2799 size_t len2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002800 int ret;
2801 luaL_Buffer b;
2802
Willy Tarreau06d80a92017-10-19 14:32:15 +02002803 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002804 if (unlikely(ret == 0))
2805 return 0;
2806
2807 if (unlikely(ret < 0)) {
2808 lua_pushnil(L);
2809 return -1;
2810 }
2811
2812 luaL_buffinit(L, &b);
2813 luaL_addlstring(&b, blk1, len1);
2814 if (unlikely(ret == 2))
2815 luaL_addlstring(&b, blk2, len2);
2816 luaL_pushresult(&b);
2817
2818 if (unlikely(ret == 2))
2819 return len1 + len2;
2820 return len1;
2821}
2822
2823/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2824 * a yield. This function keep the data in the buffer.
2825 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002826__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002827{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002828 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002829
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002830 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2831
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002832 if (_hlua_channel_dup(chn, L) == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002833 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002834 return 1;
2835}
2836
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002837/* Check arguments for the function "hlua_channel_dup_yield". */
2838__LJMP static int hlua_channel_dup(lua_State *L)
2839{
2840 MAY_LJMP(check_args(L, 1, "dup"));
2841 MAY_LJMP(hlua_checkchannel(L, 1));
2842 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2843}
2844
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002845/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2846 * a yield. This function consumes the data in the buffer. It returns
2847 * a string containing the data or a nil pointer if no data are available
2848 * and the channel is closed.
2849 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002850__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002851{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002852 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002853 int ret;
2854
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002855 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002856
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002857 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002858 if (unlikely(ret == 0))
Willy Tarreau9635e032018-10-16 17:52:55 +02002859 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002860
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002861 if (unlikely(ret == -1))
2862 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002863
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002864 b_sub(&chn->buf, ret);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002865 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002866 return 1;
2867}
2868
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002869/* Check arguments for the fucntion "hlua_channel_get_yield". */
2870__LJMP static int hlua_channel_get(lua_State *L)
2871{
2872 MAY_LJMP(check_args(L, 1, "get"));
2873 MAY_LJMP(hlua_checkchannel(L, 1));
2874 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2875}
2876
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002877/* This functions consumes and returns one line. If the channel is closed,
2878 * and the last data does not contains a final '\n', the data are returned
2879 * without the final '\n'. When no more data are avalaible, it returns nil
2880 * value.
2881 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002882__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002883{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002884 char *blk1;
2885 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002886 size_t len1;
2887 size_t len2;
2888 size_t len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002889 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002890 int ret;
2891 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002892
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002893 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2894
Willy Tarreau06d80a92017-10-19 14:32:15 +02002895 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002896 if (ret == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002897 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002898
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002899 if (ret == -1) {
2900 lua_pushnil(L);
2901 return 1;
2902 }
2903
2904 luaL_buffinit(L, &b);
2905 luaL_addlstring(&b, blk1, len1);
2906 len = len1;
2907 if (unlikely(ret == 2)) {
2908 luaL_addlstring(&b, blk2, len2);
2909 len += len2;
2910 }
2911 luaL_pushresult(&b);
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002912 b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn) + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002913 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002914 return 1;
2915}
2916
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002917/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2918__LJMP static int hlua_channel_getline(lua_State *L)
2919{
2920 MAY_LJMP(check_args(L, 1, "getline"));
2921 MAY_LJMP(hlua_checkchannel(L, 1));
2922 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2923}
2924
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002925/* This function takes a string as input, and append it at the
2926 * input side of channel. If the data is too big, but a space
2927 * is probably available after sending some data, the function
2928 * yield. If the data is bigger than the buffer, or if the
2929 * channel is closed, it returns -1. otherwise, it returns the
2930 * amount of data writed.
2931 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002932__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002933{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002934 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002935 size_t len;
2936 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2937 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2938 int ret;
2939 int max;
2940
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002941 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2942 * the request buffer if its not required.
2943 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002944 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01002945 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02002946 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002947 }
2948
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002949 max = channel_recv_limit(chn) - b_data(&chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002950 if (max > len - l)
2951 max = len - l;
2952
Willy Tarreau06d80a92017-10-19 14:32:15 +02002953 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002954 if (ret == -2 || ret == -3) {
2955 lua_pushinteger(L, -1);
2956 return 1;
2957 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002958 if (ret == -1) {
2959 chn->flags |= CF_WAKE_WRITE;
Willy Tarreau9635e032018-10-16 17:52:55 +02002960 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002961 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002962 l += ret;
2963 lua_pop(L, 1);
2964 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002965 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002966
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002967 max = channel_recv_limit(chn) - b_data(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02002968 if (max == 0 && co_data(chn) == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002969 /* There are no space avalaible, and the output buffer is empty.
2970 * in this case, we cannot add more data, so we cannot yield,
2971 * we return the amount of copyied data.
2972 */
2973 return 1;
2974 }
2975 if (l < len)
Willy Tarreau9635e032018-10-16 17:52:55 +02002976 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002977 return 1;
2978}
2979
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002980/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002981 * of the writed string, or -1 if the channel is closed or if the
2982 * buffer size is too little for the data.
2983 */
2984__LJMP static int hlua_channel_append(lua_State *L)
2985{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002986 size_t len;
2987
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002988 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002989 MAY_LJMP(hlua_checkchannel(L, 1));
2990 MAY_LJMP(luaL_checklstring(L, 2, &len));
2991 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002992 lua_pushinteger(L, 0);
2993
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002994 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002995}
2996
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002997/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002998 * his process by cleaning the buffer. The result is a replacement
2999 * of the current data. It returns the length of the writed string,
3000 * or -1 if the channel is closed or if the buffer size is too
3001 * little for the data.
3002 */
3003__LJMP static int hlua_channel_set(lua_State *L)
3004{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003005 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003006
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003007 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003008 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003009 lua_pushinteger(L, 0);
3010
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003011 b_set_data(&chn->buf, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003012
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003013 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003014}
3015
3016/* Append data in the output side of the buffer. This data is immediatly
3017 * sent. The fcuntion returns the ammount of data writed. If the buffer
3018 * cannot contains the data, the function yield. The function returns -1
3019 * if the channel is closed.
3020 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003021__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003022{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003023 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003024 size_t len;
3025 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3026 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3027 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003028 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003029
Willy Tarreau47860ed2015-03-10 14:07:50 +01003030 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003031 lua_pushinteger(L, -1);
3032 return 1;
3033 }
3034
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003035 /* Check if the buffer is avalaible because HAProxy doesn't allocate
3036 * the request buffer if its not required.
3037 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003038 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01003039 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02003040 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003041 }
3042
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003043 /* the writed data will be immediatly sent, so we can check
3044 * the avalaible space without taking in account the reserve.
3045 * The reserve is guaranted for the processing of incoming
3046 * data, because the buffer will be flushed.
3047 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003048 max = b_room(&chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003049
3050 /* If there are no space avalaible, and the output buffer is empty.
3051 * in this case, we cannot add more data, so we cannot yield,
3052 * we return the amount of copyied data.
3053 */
Willy Tarreaua79021a2018-06-15 18:07:57 +02003054 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003055 return 1;
3056
3057 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003058 if (max > len - l)
3059 max = len - l;
3060
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003061 /* The buffer avalaible size may be not contiguous. This test
3062 * detects a non contiguous buffer and realign it.
3063 */
Willy Tarreau3f679992018-06-15 15:06:42 +02003064 if (ci_space_for_replace(chn) < max)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003065 channel_slow_realign(chn, trash.area);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003066
3067 /* Copy input data in the buffer. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003068 max = b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn), str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003069
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003070 /* buffer replace considers that the input part is filled.
3071 * so, I must forward these new data in the output part.
3072 */
Willy Tarreaubcbd3932018-06-06 07:13:22 +02003073 c_adv(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003074
3075 l += max;
3076 lua_pop(L, 1);
3077 lua_pushinteger(L, l);
3078
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003079 /* If there are no space avalaible, and the output buffer is empty.
3080 * in this case, we cannot add more data, so we cannot yield,
3081 * we return the amount of copyied data.
3082 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003083 max = b_room(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003084 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003085 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003086
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003087 if (l < len) {
3088 /* If we are waiting for space in the response buffer, we
3089 * must set the flag WAKERESWR. This flag required the task
3090 * wake up if any activity is detected on the response buffer.
3091 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003092 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003093 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003094 else
3095 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003096 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003097 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003098
3099 return 1;
3100}
3101
3102/* Just a wraper of "_hlua_channel_send". This wrapper permits
3103 * yield the LUA process, and resume it without checking the
3104 * input arguments.
3105 */
3106__LJMP static int hlua_channel_send(lua_State *L)
3107{
3108 MAY_LJMP(check_args(L, 2, "send"));
3109 lua_pushinteger(L, 0);
3110
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003111 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003112}
3113
3114/* This function forward and amount of butes. The data pass from
3115 * the input side of the buffer to the output side, and can be
3116 * forwarded. This function never fails.
3117 *
3118 * The Lua function takes an amount of bytes to be forwarded in
3119 * imput. It returns the number of bytes forwarded.
3120 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003121__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003122{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003123 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003124 int len;
3125 int l;
3126 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003127 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003128
3129 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3130 len = MAY_LJMP(luaL_checkinteger(L, 2));
3131 l = MAY_LJMP(luaL_checkinteger(L, -1));
3132
3133 max = len - l;
Willy Tarreaua79021a2018-06-15 18:07:57 +02003134 if (max > ci_data(chn))
3135 max = ci_data(chn);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003136 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003137 l += max;
3138
3139 lua_pop(L, 1);
3140 lua_pushinteger(L, l);
3141
3142 /* Check if it miss bytes to forward. */
3143 if (l < len) {
3144 /* The the input channel or the output channel are closed, we
3145 * must return the amount of data forwarded.
3146 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003147 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003148 return 1;
3149
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003150 /* If we are waiting for space data in the response buffer, we
3151 * must set the flag WAKERESWR. This flag required the task
3152 * wake up if any activity is detected on the response buffer.
3153 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003154 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003155 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003156 else
3157 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003158
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003159 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003160 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003161 }
3162
3163 return 1;
3164}
3165
3166/* Just check the input and prepare the stack for the previous
3167 * function "hlua_channel_forward_yield"
3168 */
3169__LJMP static int hlua_channel_forward(lua_State *L)
3170{
3171 MAY_LJMP(check_args(L, 2, "forward"));
3172 MAY_LJMP(hlua_checkchannel(L, 1));
3173 MAY_LJMP(luaL_checkinteger(L, 2));
3174
3175 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003176 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003177}
3178
3179/* Just returns the number of bytes available in the input
3180 * side of the buffer. This function never fails.
3181 */
3182__LJMP static int hlua_channel_get_in_len(lua_State *L)
3183{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003184 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003185
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003186 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003187 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003188 lua_pushinteger(L, ci_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003189 return 1;
3190}
3191
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003192/* Returns true if the channel is full. */
3193__LJMP static int hlua_channel_is_full(lua_State *L)
3194{
3195 struct channel *chn;
3196 int rem;
3197
3198 MAY_LJMP(check_args(L, 1, "is_full"));
3199 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3200
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003201 rem = b_room(&chn->buf);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003202 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
3203
3204 lua_pushboolean(L, rem <= 0);
3205 return 1;
3206}
3207
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003208/* Just returns the number of bytes available in the output
3209 * side of the buffer. This function never fails.
3210 */
3211__LJMP static int hlua_channel_get_out_len(lua_State *L)
3212{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003213 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003214
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003215 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003216 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003217 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003218 return 1;
3219}
3220
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003221/*
3222 *
3223 *
3224 * Class Fetches
3225 *
3226 *
3227 */
3228
3229/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003230 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003231 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003232__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003233{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003234 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003235}
3236
3237/* This function creates and push in the stack a fetch object according
3238 * with a current TXN.
3239 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003240static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003241{
Willy Tarreau7073c472015-04-06 11:15:40 +02003242 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003243
3244 /* Check stack size. */
3245 if (!lua_checkstack(L, 3))
3246 return 0;
3247
3248 /* Create the object: obj[0] = userdata.
3249 * Note that the base of the Fetches object is the
3250 * transaction object.
3251 */
3252 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003253 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003254 lua_rawseti(L, -2, 0);
3255
Willy Tarreau7073c472015-04-06 11:15:40 +02003256 hsmp->s = txn->s;
3257 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003258 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003259 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003260
3261 /* Pop a class sesison metatable and affect it to the userdata. */
3262 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3263 lua_setmetatable(L, -2);
3264
3265 return 1;
3266}
3267
3268/* This function is an LUA binding. It is called with each sample-fetch.
3269 * It uses closure argument to store the associated sample-fetch. It
3270 * returns only one argument or throws an error. An error is thrown
3271 * only if an error is encountered during the argument parsing. If
3272 * the "sample-fetch" function fails, nil is returned.
3273 */
3274__LJMP static int hlua_run_sample_fetch(lua_State *L)
3275{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003276 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003277 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003278 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003279 int i;
3280 struct sample smp;
3281
3282 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003283 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003284
3285 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003286 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003287
Thierry FOURNIERca988662015-12-20 18:43:03 +01003288 /* Check execution authorization. */
3289 if (f->use & SMP_USE_HTTP_ANY &&
3290 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3291 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3292 "is not available in Lua services", f->kw);
3293 WILL_LJMP(lua_error(L));
3294 }
3295
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003296 /* Get extra arguments. */
3297 for (i = 0; i < lua_gettop(L) - 1; i++) {
3298 if (i >= ARGM_NBARGS)
3299 break;
3300 hlua_lua2arg(L, i + 2, &args[i]);
3301 }
3302 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003303 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003304
3305 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003306 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003307
3308 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003309 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003310 lua_pushfstring(L, "error in arguments");
3311 WILL_LJMP(lua_error(L));
3312 }
3313
3314 /* Initialise the sample. */
3315 memset(&smp, 0, sizeof(smp));
3316
3317 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003318 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003319 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003320 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003321 lua_pushstring(L, "");
3322 else
3323 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003324 return 1;
3325 }
3326
3327 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003328 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003329 hlua_smp2lua_str(L, &smp);
3330 else
3331 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003332 return 1;
3333}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003334
3335/*
3336 *
3337 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003338 * Class Converters
3339 *
3340 *
3341 */
3342
3343/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003344 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003345 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003346__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003347{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003348 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003349}
3350
3351/* This function creates and push in the stack a Converters object
3352 * according with a current TXN.
3353 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003354static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003355{
Willy Tarreau7073c472015-04-06 11:15:40 +02003356 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003357
3358 /* Check stack size. */
3359 if (!lua_checkstack(L, 3))
3360 return 0;
3361
3362 /* Create the object: obj[0] = userdata.
3363 * Note that the base of the Converters object is the
3364 * same than the TXN object.
3365 */
3366 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003367 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003368 lua_rawseti(L, -2, 0);
3369
Willy Tarreau7073c472015-04-06 11:15:40 +02003370 hsmp->s = txn->s;
3371 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003372 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003373 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003374
Willy Tarreau87b09662015-04-03 00:22:06 +02003375 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003376 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3377 lua_setmetatable(L, -2);
3378
3379 return 1;
3380}
3381
3382/* This function is an LUA binding. It is called with each converter.
3383 * It uses closure argument to store the associated converter. It
3384 * returns only one argument or throws an error. An error is thrown
3385 * only if an error is encountered during the argument parsing. If
3386 * the converter function function fails, nil is returned.
3387 */
3388__LJMP static int hlua_run_sample_conv(lua_State *L)
3389{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003390 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003391 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003392 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003393 int i;
3394 struct sample smp;
3395
3396 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003397 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003398
3399 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003400 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003401
3402 /* Get extra arguments. */
3403 for (i = 0; i < lua_gettop(L) - 2; i++) {
3404 if (i >= ARGM_NBARGS)
3405 break;
3406 hlua_lua2arg(L, i + 3, &args[i]);
3407 }
3408 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003409 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003410
3411 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003412 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003413
3414 /* Run the special args checker. */
3415 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3416 hlua_pusherror(L, "error in arguments");
3417 WILL_LJMP(lua_error(L));
3418 }
3419
3420 /* Initialise the sample. */
3421 if (!hlua_lua2smp(L, 2, &smp)) {
3422 hlua_pusherror(L, "error in the input argument");
3423 WILL_LJMP(lua_error(L));
3424 }
3425
Willy Tarreau1777ea62016-03-10 16:15:46 +01003426 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3427
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003428 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003429 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003430 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003431 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003432 WILL_LJMP(lua_error(L));
3433 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003434 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3435 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003436 hlua_pusherror(L, "error during the input argument casting");
3437 WILL_LJMP(lua_error(L));
3438 }
3439
3440 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003441 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003442 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003443 lua_pushstring(L, "");
3444 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003445 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003446 return 1;
3447 }
3448
3449 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003450 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003451 hlua_smp2lua_str(L, &smp);
3452 else
3453 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003454 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003455}
3456
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003457/*
3458 *
3459 *
3460 * Class AppletTCP
3461 *
3462 *
3463 */
3464
3465/* Returns a struct hlua_txn if the stack entry "ud" is
3466 * a class stream, otherwise it throws an error.
3467 */
3468__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3469{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003470 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003471}
3472
3473/* This function creates and push in the stack an Applet object
3474 * according with a current TXN.
3475 */
3476static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3477{
3478 struct hlua_appctx *appctx;
3479 struct stream_interface *si = ctx->owner;
3480 struct stream *s = si_strm(si);
3481 struct proxy *p = s->be;
3482
3483 /* Check stack size. */
3484 if (!lua_checkstack(L, 3))
3485 return 0;
3486
3487 /* Create the object: obj[0] = userdata.
3488 * Note that the base of the Converters object is the
3489 * same than the TXN object.
3490 */
3491 lua_newtable(L);
3492 appctx = lua_newuserdata(L, sizeof(*appctx));
3493 lua_rawseti(L, -2, 0);
3494 appctx->appctx = ctx;
3495 appctx->htxn.s = s;
3496 appctx->htxn.p = p;
3497
3498 /* Create the "f" field that contains a list of fetches. */
3499 lua_pushstring(L, "f");
3500 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3501 return 0;
3502 lua_settable(L, -3);
3503
3504 /* Create the "sf" field that contains a list of stringsafe fetches. */
3505 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003506 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003507 return 0;
3508 lua_settable(L, -3);
3509
3510 /* Create the "c" field that contains a list of converters. */
3511 lua_pushstring(L, "c");
3512 if (!hlua_converters_new(L, &appctx->htxn, 0))
3513 return 0;
3514 lua_settable(L, -3);
3515
3516 /* Create the "sc" field that contains a list of stringsafe converters. */
3517 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003518 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003519 return 0;
3520 lua_settable(L, -3);
3521
3522 /* Pop a class stream metatable and affect it to the table. */
3523 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3524 lua_setmetatable(L, -2);
3525
3526 return 1;
3527}
3528
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003529__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3530{
3531 struct hlua_appctx *appctx;
3532 struct stream *s;
3533 const char *name;
3534 size_t len;
3535 struct sample smp;
3536
3537 MAY_LJMP(check_args(L, 3, "set_var"));
3538
3539 /* It is useles to retrieve the stream, but this function
3540 * runs only in a stream context.
3541 */
3542 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3543 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3544 s = appctx->htxn.s;
3545
3546 /* Converts the third argument in a sample. */
3547 hlua_lua2smp(L, 3, &smp);
3548
3549 /* Store the sample in a variable. */
3550 smp_set_owner(&smp, s->be, s->sess, s, 0);
3551 vars_set_by_name(name, len, &smp);
3552 return 0;
3553}
3554
3555__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3556{
3557 struct hlua_appctx *appctx;
3558 struct stream *s;
3559 const char *name;
3560 size_t len;
3561 struct sample smp;
3562
3563 MAY_LJMP(check_args(L, 2, "unset_var"));
3564
3565 /* It is useles to retrieve the stream, but this function
3566 * runs only in a stream context.
3567 */
3568 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3569 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3570 s = appctx->htxn.s;
3571
3572 /* Unset the variable. */
3573 smp_set_owner(&smp, s->be, s->sess, s, 0);
3574 vars_unset_by_name(name, len, &smp);
3575 return 0;
3576}
3577
3578__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3579{
3580 struct hlua_appctx *appctx;
3581 struct stream *s;
3582 const char *name;
3583 size_t len;
3584 struct sample smp;
3585
3586 MAY_LJMP(check_args(L, 2, "get_var"));
3587
3588 /* It is useles to retrieve the stream, but this function
3589 * runs only in a stream context.
3590 */
3591 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3592 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3593 s = appctx->htxn.s;
3594
3595 smp_set_owner(&smp, s->be, s->sess, s, 0);
3596 if (!vars_get_by_name(name, len, &smp)) {
3597 lua_pushnil(L);
3598 return 1;
3599 }
3600
3601 return hlua_smp2lua(L, &smp);
3602}
3603
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003604__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3605{
3606 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3607 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003608 struct hlua *hlua;
3609
3610 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003611 if (!s->hlua)
3612 return 0;
3613 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003614
3615 MAY_LJMP(check_args(L, 2, "set_priv"));
3616
3617 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003618 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003619
3620 /* Get and store new value. */
3621 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3622 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3623
3624 return 0;
3625}
3626
3627__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3628{
3629 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3630 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003631 struct hlua *hlua;
3632
3633 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003634 if (!s->hlua) {
3635 lua_pushnil(L);
3636 return 1;
3637 }
3638 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003639
3640 /* Push configuration index in the stack. */
3641 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3642
3643 return 1;
3644}
3645
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003646/* If expected data not yet available, it returns a yield. This function
3647 * consumes the data in the buffer. It returns a string containing the
3648 * data. This string can be empty.
3649 */
3650__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3651{
3652 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3653 struct stream_interface *si = appctx->appctx->owner;
3654 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003655 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003656 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003657 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003658 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003659
3660 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003661 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003662
3663 /* Data not yet avalaible. return yield. */
3664 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003665 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003666 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003667 }
3668
3669 /* End of data: commit the total strings and return. */
3670 if (ret < 0) {
3671 luaL_pushresult(&appctx->b);
3672 return 1;
3673 }
3674
3675 /* Ensure that the block 2 length is usable. */
3676 if (ret == 1)
3677 len2 = 0;
3678
3679 /* dont check the max length read and dont check. */
3680 luaL_addlstring(&appctx->b, blk1, len1);
3681 luaL_addlstring(&appctx->b, blk2, len2);
3682
3683 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003684 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003685 luaL_pushresult(&appctx->b);
3686 return 1;
3687}
3688
3689/* Check arguments for the fucntion "hlua_channel_get_yield". */
3690__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3691{
3692 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3693
3694 /* Initialise the string catenation. */
3695 luaL_buffinit(L, &appctx->b);
3696
3697 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3698}
3699
3700/* If expected data not yet available, it returns a yield. This function
3701 * consumes the data in the buffer. It returns a string containing the
3702 * data. This string can be empty.
3703 */
3704__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3705{
3706 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3707 struct stream_interface *si = appctx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003708 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003709 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003710 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003711 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003712 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003713 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003714
3715 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003716 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003717
3718 /* Data not yet avalaible. return yield. */
3719 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003720 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003721 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003722 }
3723
3724 /* End of data: commit the total strings and return. */
3725 if (ret < 0) {
3726 luaL_pushresult(&appctx->b);
3727 return 1;
3728 }
3729
3730 /* Ensure that the block 2 length is usable. */
3731 if (ret == 1)
3732 len2 = 0;
3733
3734 if (len == -1) {
3735
3736 /* If len == -1, catenate all the data avalaile and
3737 * yield because we want to get all the data until
3738 * the end of data stream.
3739 */
3740 luaL_addlstring(&appctx->b, blk1, len1);
3741 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003742 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003743 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003744 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003745
3746 } else {
3747
3748 /* Copy the fisrt block caping to the length required. */
3749 if (len1 > len)
3750 len1 = len;
3751 luaL_addlstring(&appctx->b, blk1, len1);
3752 len -= len1;
3753
3754 /* Copy the second block. */
3755 if (len2 > len)
3756 len2 = len;
3757 luaL_addlstring(&appctx->b, blk2, len2);
3758 len -= len2;
3759
3760 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003761 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003762
3763 /* If we are no other data avalaible, yield waiting for new data. */
3764 if (len > 0) {
3765 lua_pushinteger(L, len);
3766 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003767 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003768 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003769 }
3770
3771 /* return the result. */
3772 luaL_pushresult(&appctx->b);
3773 return 1;
3774 }
3775
3776 /* we never executes this */
3777 hlua_pusherror(L, "Lua: internal error");
3778 WILL_LJMP(lua_error(L));
3779 return 0;
3780}
3781
3782/* Check arguments for the fucntion "hlua_channel_get_yield". */
3783__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3784{
3785 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3786 int len = -1;
3787
3788 if (lua_gettop(L) > 2)
3789 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3790 if (lua_gettop(L) >= 2) {
3791 len = MAY_LJMP(luaL_checkinteger(L, 2));
3792 lua_pop(L, 1);
3793 }
3794
3795 /* Confirm or set the required length */
3796 lua_pushinteger(L, len);
3797
3798 /* Initialise the string catenation. */
3799 luaL_buffinit(L, &appctx->b);
3800
3801 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3802}
3803
3804/* Append data in the output side of the buffer. This data is immediatly
3805 * sent. The fcuntion returns the ammount of data writed. If the buffer
3806 * cannot contains the data, the function yield. The function returns -1
3807 * if the channel is closed.
3808 */
3809__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3810{
3811 size_t len;
3812 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3813 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3814 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3815 struct stream_interface *si = appctx->appctx->owner;
3816 struct channel *chn = si_ic(si);
3817 int max;
3818
3819 /* Get the max amount of data which can write as input in the channel. */
3820 max = channel_recv_max(chn);
3821 if (max > (len - l))
3822 max = len - l;
3823
3824 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003825 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003826
3827 /* update counters. */
3828 l += max;
3829 lua_pop(L, 1);
3830 lua_pushinteger(L, l);
3831
3832 /* If some data is not send, declares the situation to the
3833 * applet, and returns a yield.
3834 */
3835 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01003836 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003837 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003838 }
3839
3840 return 1;
3841}
3842
3843/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3844 * yield the LUA process, and resume it without checking the
3845 * input arguments.
3846 */
3847__LJMP static int hlua_applet_tcp_send(lua_State *L)
3848{
3849 MAY_LJMP(check_args(L, 2, "send"));
3850 lua_pushinteger(L, 0);
3851
3852 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3853}
3854
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003855/*
3856 *
3857 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003858 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003859 *
3860 *
3861 */
3862
3863/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003864 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003865 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003866__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003867{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003868 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003869}
3870
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003871/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003872 * according with a current TXN.
3873 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003874static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003875{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003876 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003877 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003878 struct stream_interface *si = ctx->owner;
3879 struct stream *s = si_strm(si);
3880 struct proxy *px = s->be;
3881 struct http_txn *txn = s->txn;
3882 const char *path;
3883 const char *end;
3884 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003885
3886 /* Check stack size. */
3887 if (!lua_checkstack(L, 3))
3888 return 0;
3889
3890 /* Create the object: obj[0] = userdata.
3891 * Note that the base of the Converters object is the
3892 * same than the TXN object.
3893 */
3894 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003895 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003896 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003897 appctx->appctx = ctx;
3898 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003899 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003900 appctx->htxn.s = s;
3901 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003902
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003903 /* Create the "f" field that contains a list of fetches. */
3904 lua_pushstring(L, "f");
3905 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3906 return 0;
3907 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003908
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003909 /* Create the "sf" field that contains a list of stringsafe fetches. */
3910 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003911 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003912 return 0;
3913 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003914
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003915 /* Create the "c" field that contains a list of converters. */
3916 lua_pushstring(L, "c");
3917 if (!hlua_converters_new(L, &appctx->htxn, 0))
3918 return 0;
3919 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003920
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003921 /* Create the "sc" field that contains a list of stringsafe converters. */
3922 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003923 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003924 return 0;
3925 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003926
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003927 /* Stores the request method. */
3928 lua_pushstring(L, "method");
Willy Tarreaua79021a2018-06-15 18:07:57 +02003929 lua_pushlstring(L, ci_head(txn->req.chn), txn->req.sl.rq.m_l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003930 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003931
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003932 /* Stores the http version. */
3933 lua_pushstring(L, "version");
Willy Tarreaua79021a2018-06-15 18:07:57 +02003934 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 +02003935 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003936
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003937 /* creates an array of headers. hlua_http_get_headers() crates and push
3938 * the array on the top of the stack.
3939 */
3940 lua_pushstring(L, "headers");
3941 htxn.s = s;
3942 htxn.p = px;
3943 htxn.dir = SMP_OPT_DIR_REQ;
3944 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3945 return 0;
3946 lua_settable(L, -3);
3947
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003948 /* Get path and qs */
Willy Tarreau6b952c82018-09-10 17:45:34 +02003949 path = http_txn_get_path(txn);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003950 if (path) {
Willy Tarreaua79021a2018-06-15 18:07:57 +02003951 end = ci_head(txn->req.chn) + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003952 p = path;
3953 while (p < end && *p != '?')
3954 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003955
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003956 /* Stores the request path. */
3957 lua_pushstring(L, "path");
3958 lua_pushlstring(L, path, p - path);
3959 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003960
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003961 /* Stores the query string. */
3962 lua_pushstring(L, "qs");
3963 if (*p == '?')
3964 p++;
3965 lua_pushlstring(L, p, end - p);
3966 lua_settable(L, -3);
3967 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003968
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003969 /* Stores the request path. */
3970 lua_pushstring(L, "length");
3971 lua_pushinteger(L, txn->req.body_len);
3972 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003973
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003974 /* Create an array of HTTP request headers. */
3975 lua_pushstring(L, "headers");
3976 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3977 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003978
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003979 /* Create an empty array of HTTP request headers. */
3980 lua_pushstring(L, "response");
3981 lua_newtable(L);
3982 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003983
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003984 /* Pop a class stream metatable and affect it to the table. */
3985 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3986 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003987
3988 return 1;
3989}
3990
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003991__LJMP static int hlua_applet_http_set_var(lua_State *L)
3992{
3993 struct hlua_appctx *appctx;
3994 struct stream *s;
3995 const char *name;
3996 size_t len;
3997 struct sample smp;
3998
3999 MAY_LJMP(check_args(L, 3, "set_var"));
4000
4001 /* It is useles to retrieve the stream, but this function
4002 * runs only in a stream context.
4003 */
4004 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4005 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4006 s = appctx->htxn.s;
4007
4008 /* Converts the third argument in a sample. */
4009 hlua_lua2smp(L, 3, &smp);
4010
4011 /* Store the sample in a variable. */
4012 smp_set_owner(&smp, s->be, s->sess, s, 0);
4013 vars_set_by_name(name, len, &smp);
4014 return 0;
4015}
4016
4017__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4018{
4019 struct hlua_appctx *appctx;
4020 struct stream *s;
4021 const char *name;
4022 size_t len;
4023 struct sample smp;
4024
4025 MAY_LJMP(check_args(L, 2, "unset_var"));
4026
4027 /* It is useles to retrieve the stream, but this function
4028 * runs only in a stream context.
4029 */
4030 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4031 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4032 s = appctx->htxn.s;
4033
4034 /* Unset the variable. */
4035 smp_set_owner(&smp, s->be, s->sess, s, 0);
4036 vars_unset_by_name(name, len, &smp);
4037 return 0;
4038}
4039
4040__LJMP static int hlua_applet_http_get_var(lua_State *L)
4041{
4042 struct hlua_appctx *appctx;
4043 struct stream *s;
4044 const char *name;
4045 size_t len;
4046 struct sample smp;
4047
4048 MAY_LJMP(check_args(L, 2, "get_var"));
4049
4050 /* It is useles to retrieve the stream, but this function
4051 * runs only in a stream context.
4052 */
4053 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4054 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4055 s = appctx->htxn.s;
4056
4057 smp_set_owner(&smp, s->be, s->sess, s, 0);
4058 if (!vars_get_by_name(name, len, &smp)) {
4059 lua_pushnil(L);
4060 return 1;
4061 }
4062
4063 return hlua_smp2lua(L, &smp);
4064}
4065
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004066__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4067{
4068 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4069 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004070 struct hlua *hlua;
4071
4072 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004073 if (!s->hlua)
4074 return 0;
4075 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004076
4077 MAY_LJMP(check_args(L, 2, "set_priv"));
4078
4079 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004080 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004081
4082 /* Get and store new value. */
4083 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4084 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4085
4086 return 0;
4087}
4088
4089__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4090{
4091 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4092 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004093 struct hlua *hlua;
4094
4095 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004096 if (!s->hlua) {
4097 lua_pushnil(L);
4098 return 1;
4099 }
4100 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004101
4102 /* Push configuration index in the stack. */
4103 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4104
4105 return 1;
4106}
4107
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004108/* If expected data not yet available, it returns a yield. This function
4109 * consumes the data in the buffer. It returns a string containing the
4110 * data. This string can be empty.
4111 */
4112__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004113{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004114 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4115 struct stream_interface *si = appctx->appctx->owner;
4116 struct channel *chn = si_ic(si);
4117 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004118 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004119 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004120 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004121 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004122
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004123 /* Maybe we cant send a 100-continue ? */
4124 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02004125 ret = ci_putblk(chn, HTTP_100.ptr, HTTP_100.len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004126 /* if ret == -2 or -3 the channel closed or the message si too
4127 * big for the buffers. We cant send anything. So, we ignoring
4128 * the error, considers that the 100-continue is sent, and try
4129 * to receive.
4130 * If ret is -1, we dont have room in the buffer, so we yield.
4131 */
4132 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004133 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004134 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004135 }
4136 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4137 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004138
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004139 /* Check for the end of the data. */
4140 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4141 luaL_pushresult(&appctx->b);
4142 return 1;
4143 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004144
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004145 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004146 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004147
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004148 /* Data not yet avalaible. return yield. */
4149 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004150 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004151 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004152 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004153
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004154 /* End of data: commit the total strings and return. */
4155 if (ret < 0) {
4156 luaL_pushresult(&appctx->b);
4157 return 1;
4158 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004159
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004160 /* Ensure that the block 2 length is usable. */
4161 if (ret == 1)
4162 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004163
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004164 /* Copy the fisrt block caping to the length required. */
4165 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4166 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4167 luaL_addlstring(&appctx->b, blk1, len1);
4168 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004169
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004170 /* Copy the second block. */
4171 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4172 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4173 luaL_addlstring(&appctx->b, blk2, len2);
4174 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004175
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004176 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004177 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004178 luaL_pushresult(&appctx->b);
4179 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004180}
4181
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004182/* Check arguments for the fucntion "hlua_channel_get_yield". */
4183__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004184{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004185 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004186
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004187 /* Initialise the string catenation. */
4188 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004189
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004190 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004191}
4192
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004193/* If expected data not yet available, it returns a yield. This function
4194 * consumes the data in the buffer. It returns a string containing the
4195 * data. This string can be empty.
4196 */
4197__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004198{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004199 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4200 struct stream_interface *si = appctx->appctx->owner;
4201 int len = MAY_LJMP(luaL_checkinteger(L, 2));
4202 struct channel *chn = si_ic(si);
4203 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004204 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004205 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004206 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004207 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004208
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004209 /* Maybe we cant send a 100-continue ? */
4210 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02004211 ret = ci_putblk(chn, HTTP_100.ptr, HTTP_100.len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004212 /* if ret == -2 or -3 the channel closed or the message si too
4213 * big for the buffers. We cant send anything. So, we ignoring
4214 * the error, considers that the 100-continue is sent, and try
4215 * to receive.
4216 * If ret is -1, we dont have room in the buffer, so we yield.
4217 */
4218 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004219 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004220 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004221 }
4222 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4223 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004224
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004225 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004226 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004227
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004228 /* Data not yet avalaible. return yield. */
4229 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004230 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004231 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004232 }
4233
4234 /* End of data: commit the total strings and return. */
4235 if (ret < 0) {
4236 luaL_pushresult(&appctx->b);
4237 return 1;
4238 }
4239
4240 /* Ensure that the block 2 length is usable. */
4241 if (ret == 1)
4242 len2 = 0;
4243
4244 /* Copy the fisrt block caping to the length required. */
4245 if (len1 > len)
4246 len1 = len;
4247 luaL_addlstring(&appctx->b, blk1, len1);
4248 len -= len1;
4249
4250 /* Copy the second block. */
4251 if (len2 > len)
4252 len2 = len;
4253 luaL_addlstring(&appctx->b, blk2, len2);
4254 len -= len2;
4255
4256 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004257 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004258 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4259 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4260
4261 /* If we are no other data avalaible, yield waiting for new data. */
4262 if (len > 0) {
4263 lua_pushinteger(L, len);
4264 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004265 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004266 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004267 }
4268
4269 /* return the result. */
4270 luaL_pushresult(&appctx->b);
4271 return 1;
4272}
4273
4274/* Check arguments for the fucntion "hlua_channel_get_yield". */
4275__LJMP static int hlua_applet_http_recv(lua_State *L)
4276{
4277 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4278 int len = -1;
4279
4280 /* Check arguments. */
4281 if (lua_gettop(L) > 2)
4282 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4283 if (lua_gettop(L) >= 2) {
4284 len = MAY_LJMP(luaL_checkinteger(L, 2));
4285 lua_pop(L, 1);
4286 }
4287
4288 /* Check the required length */
4289 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4290 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4291 lua_pushinteger(L, len);
4292
4293 /* Initialise the string catenation. */
4294 luaL_buffinit(L, &appctx->b);
4295
4296 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4297}
4298
4299/* Append data in the output side of the buffer. This data is immediatly
4300 * sent. The fcuntion returns the ammount of data writed. If the buffer
4301 * cannot contains the data, the function yield. The function returns -1
4302 * if the channel is closed.
4303 */
4304__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4305{
4306 size_t len;
4307 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4308 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4309 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4310 struct stream_interface *si = appctx->appctx->owner;
4311 struct channel *chn = si_ic(si);
4312 int max;
4313
4314 /* Get the max amount of data which can write as input in the channel. */
4315 max = channel_recv_max(chn);
4316 if (max > (len - l))
4317 max = len - l;
4318
4319 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004320 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004321
4322 /* update counters. */
4323 l += max;
4324 lua_pop(L, 1);
4325 lua_pushinteger(L, l);
4326
4327 /* If some data is not send, declares the situation to the
4328 * applet, and returns a yield.
4329 */
4330 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004331 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004332 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004333 }
4334
4335 return 1;
4336}
4337
4338/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4339 * yield the LUA process, and resume it without checking the
4340 * input arguments.
4341 */
4342__LJMP static int hlua_applet_http_send(lua_State *L)
4343{
4344 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4345 size_t len;
4346 char hex[10];
4347
4348 MAY_LJMP(luaL_checklstring(L, 2, &len));
4349
4350 /* If transfer encoding chunked is selected, we surround the data
4351 * by chunk data.
4352 */
4353 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4354 snprintf(hex, 9, "%x", (unsigned int)len);
4355 lua_pushfstring(L, "%s\r\n", hex);
4356 lua_insert(L, 2); /* swap the last 2 entries. */
4357 lua_pushstring(L, "\r\n");
4358 lua_concat(L, 3);
4359 }
4360
4361 /* This interger is used for followinf the amount of data sent. */
4362 lua_pushinteger(L, 0);
4363
4364 /* We want to send some data. Headers must be sent. */
4365 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4366 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4367 WILL_LJMP(lua_error(L));
4368 }
4369
4370 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4371}
4372
4373__LJMP static int hlua_applet_http_addheader(lua_State *L)
4374{
4375 const char *name;
4376 int ret;
4377
4378 MAY_LJMP(hlua_checkapplet_http(L, 1));
4379 name = MAY_LJMP(luaL_checkstring(L, 2));
4380 MAY_LJMP(luaL_checkstring(L, 3));
4381
4382 /* Push in the stack the "response" entry. */
4383 ret = lua_getfield(L, 1, "response");
4384 if (ret != LUA_TTABLE) {
4385 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4386 "is expected as an array. %s found", lua_typename(L, ret));
4387 WILL_LJMP(lua_error(L));
4388 }
4389
4390 /* check if the header is already registered if it is not
4391 * the case, register it.
4392 */
4393 ret = lua_getfield(L, -1, name);
4394 if (ret == LUA_TNIL) {
4395
4396 /* Entry not found. */
4397 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4398
4399 /* Insert the new header name in the array in the top of the stack.
4400 * It left the new array in the top of the stack.
4401 */
4402 lua_newtable(L);
4403 lua_pushvalue(L, 2);
4404 lua_pushvalue(L, -2);
4405 lua_settable(L, -4);
4406
4407 } else if (ret != LUA_TTABLE) {
4408
4409 /* corruption error. */
4410 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4411 "is expected as an array. %s found", name, lua_typename(L, ret));
4412 WILL_LJMP(lua_error(L));
4413 }
4414
4415 /* Now the top od thestack is an array of values. We push
4416 * the header value as new entry.
4417 */
4418 lua_pushvalue(L, 3);
4419 ret = lua_rawlen(L, -2);
4420 lua_rawseti(L, -2, ret + 1);
4421 lua_pushboolean(L, 1);
4422 return 1;
4423}
4424
4425__LJMP static int hlua_applet_http_status(lua_State *L)
4426{
4427 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4428 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004429 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004430
4431 if (status < 100 || status > 599) {
4432 lua_pushboolean(L, 0);
4433 return 1;
4434 }
4435
4436 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004437 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004438 lua_pushboolean(L, 1);
4439 return 1;
4440}
4441
4442/* We will build the status line and the headers of the HTTP response.
4443 * We will try send at once if its not possible, we give back the hand
4444 * waiting for more room.
4445 */
4446__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4447{
4448 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4449 struct stream_interface *si = appctx->appctx->owner;
4450 struct channel *chn = si_ic(si);
4451 int ret;
4452 size_t len;
4453 const char *msg;
4454
4455 /* Get the message as the first argument on the stack. */
4456 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4457
4458 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004459 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004460
4461 /* if ret == -2 or -3 the channel closed or the message si too
4462 * big for the buffers.
4463 */
4464 if (ret == -2 || ret == -3) {
4465 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4466 WILL_LJMP(lua_error(L));
4467 }
4468
4469 /* If ret is -1, we dont have room in the buffer, so we yield. */
4470 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004471 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004472 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004473 }
4474
4475 /* Headers sent, set the flag. */
4476 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4477 return 0;
4478}
4479
4480__LJMP static int hlua_applet_http_start_response(lua_State *L)
4481{
Willy Tarreau83061a82018-07-13 11:56:34 +02004482 struct buffer *tmp = get_trash_chunk();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004483 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004484 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02004485 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004486 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02004487 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004488 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004489 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004490 int hdr_chunked = 0;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004491 const char *reason = appctx->appctx->ctx.hlua_apphttp.reason;
4492
4493 if (reason == NULL)
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02004494 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004495
4496 /* Use the same http version than the request. */
4497 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004498 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004499 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004500 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004501
4502 /* Get the array associated to the field "response" in the object AppletHTTP. */
4503 lua_pushvalue(L, 0);
4504 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4505 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4506 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4507 WILL_LJMP(lua_error(L));
4508 }
4509
4510 /* Browse the list of headers. */
4511 lua_pushnil(L);
4512 while(lua_next(L, -2) != 0) {
4513
4514 /* We expect a string as -2. */
4515 if (lua_type(L, -2) != LUA_TSTRING) {
4516 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4517 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4518 lua_typename(L, lua_type(L, -2)));
4519 WILL_LJMP(lua_error(L));
4520 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004521 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004522
4523 /* We expect an array as -1. */
4524 if (lua_type(L, -1) != LUA_TTABLE) {
4525 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4526 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4527 name,
4528 lua_typename(L, lua_type(L, -1)));
4529 WILL_LJMP(lua_error(L));
4530 }
4531
4532 /* Browse the table who is on the top of the stack. */
4533 lua_pushnil(L);
4534 while(lua_next(L, -2) != 0) {
4535
4536 /* We expect a number as -2. */
4537 if (lua_type(L, -2) != LUA_TNUMBER) {
4538 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4539 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4540 name,
4541 lua_typename(L, lua_type(L, -2)));
4542 WILL_LJMP(lua_error(L));
4543 }
4544 id = lua_tointeger(L, -2);
4545
4546 /* We expect a string as -2. */
4547 if (lua_type(L, -1) != LUA_TSTRING) {
4548 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4549 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4550 name, id,
4551 lua_typename(L, lua_type(L, -1)));
4552 WILL_LJMP(lua_error(L));
4553 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004554 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004555
4556 /* Catenate a new header. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004557 if (tmp->data + name_len + 2 + value_len + 2 < tmp->size) {
4558 memcpy(tmp->area + tmp->data, name, name_len);
4559 tmp->data += name_len;
4560 tmp->area[tmp->data++] = ':';
4561 tmp->area[tmp->data++] = ' ';
Willy Tarreaua3294632017-08-23 11:24:47 +02004562
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004563 memcpy(tmp->area + tmp->data, value,
4564 value_len);
4565 tmp->data += value_len;
4566 tmp->area[tmp->data++] = '\r';
4567 tmp->area[tmp->data++] = '\n';
Willy Tarreaua3294632017-08-23 11:24:47 +02004568 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004569
4570 /* Protocol checks. */
4571
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004572 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004573 * is done without control. If it contains a bad value,
4574 * the content-length remains negative so that we can
4575 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004576 */
Willy Tarreaua3294632017-08-23 11:24:47 +02004577 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004578 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004579
4580 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004581 if (name_len == 17 && value_len == 7 &&
4582 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004583 strcasecmp("chunked", value) == 0)
4584 hdr_chunked = 1;
4585
4586 /* Remove the array from the stack, and get next element with a remaining string. */
4587 lua_pop(L, 1);
4588 }
4589
4590 /* Remove the array from the stack, and get next element with a remaining string. */
4591 lua_pop(L, 1);
4592 }
4593
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004594 /* If we dont have a content-length set, and the HTTP version is 1.1
4595 * and the status code implies the presence of a message body, we must
4596 * announce a transfer encoding chunked. This is required by haproxy
4597 * for the keepalive compliance. If the applet annouces a transfer-encoding
4598 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004599 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004600 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004601 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
4602 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4603 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4604 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004605 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4606 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4607 }
4608
4609 /* Finalize headers. */
4610 chunk_appendf(tmp, "\r\n");
4611
4612 /* Remove the last entry and the array of headers */
4613 lua_pop(L, 2);
4614
4615 /* Push the headers block. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004616 lua_pushlstring(L, tmp->area, tmp->data);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004617
4618 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4619}
4620
4621/*
4622 *
4623 *
4624 * Class HTTP
4625 *
4626 *
4627 */
4628
4629/* Returns a struct hlua_txn if the stack entry "ud" is
4630 * a class stream, otherwise it throws an error.
4631 */
4632__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4633{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004634 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004635}
4636
4637/* This function creates and push in the stack a HTTP object
4638 * according with a current TXN.
4639 */
4640static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4641{
4642 struct hlua_txn *htxn;
4643
4644 /* Check stack size. */
4645 if (!lua_checkstack(L, 3))
4646 return 0;
4647
4648 /* Create the object: obj[0] = userdata.
4649 * Note that the base of the Converters object is the
4650 * same than the TXN object.
4651 */
4652 lua_newtable(L);
4653 htxn = lua_newuserdata(L, sizeof(*htxn));
4654 lua_rawseti(L, -2, 0);
4655
4656 htxn->s = txn->s;
4657 htxn->p = txn->p;
4658
4659 /* Pop a class stream metatable and affect it to the table. */
4660 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4661 lua_setmetatable(L, -2);
4662
4663 return 1;
4664}
4665
4666/* This function creates ans returns an array of HTTP headers.
4667 * This function does not fails. It is used as wrapper with the
4668 * 2 following functions.
4669 */
4670__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4671{
4672 const char *cur_ptr, *cur_next, *p;
4673 int old_idx, cur_idx;
4674 struct hdr_idx_elem *cur_hdr;
4675 const char *hn, *hv;
4676 int hnl, hvl;
4677 int type;
4678 const char *in;
4679 char *out;
4680 int len;
4681
4682 /* Create the table. */
4683 lua_newtable(L);
4684
4685 if (!htxn->s->txn)
4686 return 1;
4687
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004688 /* Check if a valid response is parsed */
4689 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4690 return 1;
4691
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004692 /* Build array of headers. */
4693 old_idx = 0;
Willy Tarreaua79021a2018-06-15 18:07:57 +02004694 cur_next = ci_head(msg->chn) + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004695
4696 while (1) {
4697 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4698 if (!cur_idx)
4699 break;
4700 old_idx = cur_idx;
4701
4702 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4703 cur_ptr = cur_next;
4704 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4705
4706 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4707 * and the next header starts at cur_next. We'll check
4708 * this header in the list as well as against the default
4709 * rule.
4710 */
4711
4712 /* look for ': *'. */
4713 hn = cur_ptr;
4714 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4715 if (p >= cur_ptr+cur_hdr->len)
4716 continue;
4717 hnl = p - hn;
4718 p++;
4719 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4720 p++;
4721 if (p >= cur_ptr+cur_hdr->len)
4722 continue;
4723 hv = p;
4724 hvl = cur_ptr+cur_hdr->len-p;
4725
4726 /* Lowercase the key. Don't check the size of trash, it have
4727 * the size of one buffer and the input data contains in one
4728 * buffer.
4729 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004730 out = trash.area;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004731 for (in=hn; in<hn+hnl; in++, out++)
4732 *out = tolower(*in);
4733 *out = '\0';
4734
4735 /* Check for existing entry:
4736 * assume that the table is on the top of the stack, and
4737 * push the key in the stack, the function lua_gettable()
4738 * perform the lookup.
4739 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004740 lua_pushlstring(L, trash.area, hnl);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004741 lua_gettable(L, -2);
4742 type = lua_type(L, -1);
4743
4744 switch (type) {
4745 case LUA_TNIL:
4746 /* Table not found, create it. */
4747 lua_pop(L, 1); /* remove the nil value. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004748 lua_pushlstring(L, trash.area, hnl); /* push the header name as key. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004749 lua_newtable(L); /* create and push empty table. */
4750 lua_pushlstring(L, hv, hvl); /* push header value. */
4751 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4752 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4753 break;
4754
4755 case LUA_TTABLE:
4756 /* Entry found: push the value in the table. */
4757 len = lua_rawlen(L, -1);
4758 lua_pushlstring(L, hv, hvl); /* push header value. */
4759 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4760 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4761 break;
4762
4763 default:
4764 /* Other cases are errors. */
4765 hlua_pusherror(L, "internal error during the parsing of headers.");
4766 WILL_LJMP(lua_error(L));
4767 }
4768 }
4769
4770 return 1;
4771}
4772
4773__LJMP static int hlua_http_req_get_headers(lua_State *L)
4774{
4775 struct hlua_txn *htxn;
4776
4777 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4778 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4779
4780 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4781}
4782
4783__LJMP static int hlua_http_res_get_headers(lua_State *L)
4784{
4785 struct hlua_txn *htxn;
4786
4787 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4788 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4789
4790 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4791}
4792
4793/* This function replace full header, or just a value in
4794 * the request or in the response. It is a wrapper fir the
4795 * 4 following functions.
4796 */
4797__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4798 struct http_msg *msg, int action)
4799{
4800 size_t name_len;
4801 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4802 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4803 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4804 struct my_regex re;
4805
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004806 /* Check if a valid response is parsed */
4807 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4808 return 0;
4809
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004810 if (!regex_comp(reg, &re, 1, 1, NULL))
4811 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4812
4813 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4814 regex_free(&re);
4815 return 0;
4816}
4817
4818__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4819{
4820 struct hlua_txn *htxn;
4821
4822 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4823 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4824
4825 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4826}
4827
4828__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4829{
4830 struct hlua_txn *htxn;
4831
4832 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4833 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4834
4835 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4836}
4837
4838__LJMP static int hlua_http_req_rep_val(lua_State *L)
4839{
4840 struct hlua_txn *htxn;
4841
4842 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4843 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4844
4845 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4846}
4847
4848__LJMP static int hlua_http_res_rep_val(lua_State *L)
4849{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004850 struct hlua_txn *htxn;
4851
4852 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4853 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4854
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004855 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004856}
4857
4858/* This function deletes all the occurences of an header.
4859 * It is a wrapper for the 2 following functions.
4860 */
4861__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4862{
4863 size_t len;
4864 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4865 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004866 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004867
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004868 /* Check if a valid response is parsed */
4869 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4870 return 0;
4871
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004872 ctx.idx = 0;
Willy Tarreaua79021a2018-06-15 18:07:57 +02004873 while (http_find_header2(name, len, ci_head(msg->chn), &txn->hdr_idx, &ctx))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004874 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4875 return 0;
4876}
4877
4878__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4879{
4880 struct hlua_txn *htxn;
4881
4882 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4883 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4884
Willy Tarreaueee5b512015-04-03 23:46:31 +02004885 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004886}
4887
4888__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4889{
4890 struct hlua_txn *htxn;
4891
4892 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4893 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4894
Willy Tarreaueee5b512015-04-03 23:46:31 +02004895 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004896}
4897
4898/* This function adds an header. It is a wrapper used by
4899 * the 2 following functions.
4900 */
4901__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4902{
4903 size_t name_len;
4904 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4905 size_t value_len;
4906 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4907 char *p;
4908
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004909 /* Check if a valid message is parsed */
4910 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4911 return 0;
4912
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004913 /* Check length. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004914 trash.data = value_len + name_len + 2;
4915 if (trash.data > trash.size)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004916 return 0;
4917
4918 /* Creates the header string. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004919 p = trash.area;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004920 memcpy(p, name, name_len);
4921 p += name_len;
4922 *p = ':';
4923 p++;
4924 *p = ' ';
4925 p++;
4926 memcpy(p, value, value_len);
4927
Willy Tarreaueee5b512015-04-03 23:46:31 +02004928 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004929 trash.area, trash.data) != 0);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004930
4931 return 0;
4932}
4933
4934__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4935{
4936 struct hlua_txn *htxn;
4937
4938 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4939 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4940
Willy Tarreaueee5b512015-04-03 23:46:31 +02004941 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004942}
4943
4944__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4945{
4946 struct hlua_txn *htxn;
4947
4948 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4949 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4950
Willy Tarreaueee5b512015-04-03 23:46:31 +02004951 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004952}
4953
4954static int hlua_http_req_set_hdr(lua_State *L)
4955{
4956 struct hlua_txn *htxn;
4957
4958 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4959 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4960
Willy Tarreaueee5b512015-04-03 23:46:31 +02004961 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4962 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004963}
4964
4965static int hlua_http_res_set_hdr(lua_State *L)
4966{
4967 struct hlua_txn *htxn;
4968
4969 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4970 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4971
Willy Tarreaueee5b512015-04-03 23:46:31 +02004972 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4973 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004974}
4975
4976/* This function set the method. */
4977static int hlua_http_req_set_meth(lua_State *L)
4978{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004979 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004980 size_t name_len;
4981 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004982
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004983 /* Check if a valid request is parsed */
4984 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4985 lua_pushboolean(L, 0);
4986 return 1;
4987 }
4988
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004989 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004990 return 1;
4991}
4992
4993/* This function set the method. */
4994static int hlua_http_req_set_path(lua_State *L)
4995{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004996 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004997 size_t name_len;
4998 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004999
5000 /* Check if a valid request is parsed */
5001 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
5002 lua_pushboolean(L, 0);
5003 return 1;
5004 }
5005
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005006 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005007 return 1;
5008}
5009
5010/* This function set the query-string. */
5011static int hlua_http_req_set_query(lua_State *L)
5012{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005013 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005014 size_t name_len;
5015 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005016
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005017 /* Check if a valid request is parsed */
5018 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
5019 lua_pushboolean(L, 0);
5020 return 1;
5021 }
5022
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005023 /* Check length. */
5024 if (name_len > trash.size - 1) {
5025 lua_pushboolean(L, 0);
5026 return 1;
5027 }
5028
5029 /* Add the mark question as prefix. */
5030 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005031 trash.area[trash.data++] = '?';
5032 memcpy(trash.area + trash.data, name, name_len);
5033 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005034
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005035 lua_pushboolean(L,
5036 http_replace_req_line(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005037 return 1;
5038}
5039
5040/* This function set the uri. */
5041static int hlua_http_req_set_uri(lua_State *L)
5042{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005043 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005044 size_t name_len;
5045 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005046
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005047 /* Check if a valid request is parsed */
5048 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
5049 lua_pushboolean(L, 0);
5050 return 1;
5051 }
5052
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005053 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005054 return 1;
5055}
5056
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005057/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005058static int hlua_http_res_set_status(lua_State *L)
5059{
5060 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5061 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005062 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005063
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005064 /* Check if a valid response is parsed */
5065 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
5066 return 0;
5067
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005068 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005069 return 0;
5070}
5071
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005072/*
5073 *
5074 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005075 * Class TXN
5076 *
5077 *
5078 */
5079
5080/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005081 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005082 */
5083__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5084{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005085 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005086}
5087
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005088__LJMP static int hlua_set_var(lua_State *L)
5089{
5090 struct hlua_txn *htxn;
5091 const char *name;
5092 size_t len;
5093 struct sample smp;
5094
5095 MAY_LJMP(check_args(L, 3, "set_var"));
5096
5097 /* It is useles to retrieve the stream, but this function
5098 * runs only in a stream context.
5099 */
5100 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5101 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5102
5103 /* Converts the third argument in a sample. */
5104 hlua_lua2smp(L, 3, &smp);
5105
5106 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005107 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005108 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005109 return 0;
5110}
5111
Christopher Faulet85d79c92016-11-09 16:54:56 +01005112__LJMP static int hlua_unset_var(lua_State *L)
5113{
5114 struct hlua_txn *htxn;
5115 const char *name;
5116 size_t len;
5117 struct sample smp;
5118
5119 MAY_LJMP(check_args(L, 2, "unset_var"));
5120
5121 /* It is useles to retrieve the stream, but this function
5122 * runs only in a stream context.
5123 */
5124 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5125 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5126
5127 /* Unset the variable. */
5128 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5129 vars_unset_by_name(name, len, &smp);
5130 return 0;
5131}
5132
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005133__LJMP static int hlua_get_var(lua_State *L)
5134{
5135 struct hlua_txn *htxn;
5136 const char *name;
5137 size_t len;
5138 struct sample smp;
5139
5140 MAY_LJMP(check_args(L, 2, "get_var"));
5141
5142 /* It is useles to retrieve the stream, but this function
5143 * runs only in a stream context.
5144 */
5145 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5146 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5147
Willy Tarreau7560dd42016-03-10 16:28:58 +01005148 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005149 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005150 lua_pushnil(L);
5151 return 1;
5152 }
5153
5154 return hlua_smp2lua(L, &smp);
5155}
5156
Willy Tarreau59551662015-03-10 14:23:13 +01005157__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005158{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005159 struct hlua *hlua;
5160
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005161 MAY_LJMP(check_args(L, 2, "set_priv"));
5162
Willy Tarreau87b09662015-04-03 00:22:06 +02005163 /* It is useles to retrieve the stream, but this function
5164 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005165 */
5166 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005167 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005168
5169 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005170 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005171
5172 /* Get and store new value. */
5173 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5174 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5175
5176 return 0;
5177}
5178
Willy Tarreau59551662015-03-10 14:23:13 +01005179__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005180{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005181 struct hlua *hlua;
5182
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005183 MAY_LJMP(check_args(L, 1, "get_priv"));
5184
Willy Tarreau87b09662015-04-03 00:22:06 +02005185 /* It is useles to retrieve the stream, but this function
5186 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005187 */
5188 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005189 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005190
5191 /* Push configuration index in the stack. */
5192 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5193
5194 return 1;
5195}
5196
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005197/* Create stack entry containing a class TXN. This function
5198 * return 0 if the stack does not contains free slots,
5199 * otherwise it returns 1.
5200 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005201static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005202{
Willy Tarreaude491382015-04-06 11:04:28 +02005203 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005204
5205 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005206 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005207 return 0;
5208
5209 /* NOTE: The allocation never fails. The failure
5210 * throw an error, and the function never returns.
5211 * if the throw is not avalaible, the process is aborted.
5212 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005213 /* Create the object: obj[0] = userdata. */
5214 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005215 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005216 lua_rawseti(L, -2, 0);
5217
Willy Tarreaude491382015-04-06 11:04:28 +02005218 htxn->s = s;
5219 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005220 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005221 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005222
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005223 /* Create the "f" field that contains a list of fetches. */
5224 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005225 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005226 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005227 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005228
5229 /* Create the "sf" field that contains a list of stringsafe fetches. */
5230 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005231 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005232 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005233 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005234
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005235 /* Create the "c" field that contains a list of converters. */
5236 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005237 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005238 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005239 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005240
5241 /* Create the "sc" field that contains a list of stringsafe converters. */
5242 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005243 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005244 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005245 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005246
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005247 /* Create the "req" field that contains the request channel object. */
5248 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005249 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005250 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005251 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005252
5253 /* Create the "res" field that contains the response channel object. */
5254 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005255 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005256 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005257 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005258
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005259 /* Creates the HTTP object is the current proxy allows http. */
5260 lua_pushstring(L, "http");
5261 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005262 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005263 return 0;
5264 }
5265 else
5266 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005267 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005268
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005269 /* Pop a class sesison metatable and affect it to the userdata. */
5270 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5271 lua_setmetatable(L, -2);
5272
5273 return 1;
5274}
5275
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005276__LJMP static int hlua_txn_deflog(lua_State *L)
5277{
5278 const char *msg;
5279 struct hlua_txn *htxn;
5280
5281 MAY_LJMP(check_args(L, 2, "deflog"));
5282 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5283 msg = MAY_LJMP(luaL_checkstring(L, 2));
5284
5285 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5286 return 0;
5287}
5288
5289__LJMP static int hlua_txn_log(lua_State *L)
5290{
5291 int level;
5292 const char *msg;
5293 struct hlua_txn *htxn;
5294
5295 MAY_LJMP(check_args(L, 3, "log"));
5296 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5297 level = MAY_LJMP(luaL_checkinteger(L, 2));
5298 msg = MAY_LJMP(luaL_checkstring(L, 3));
5299
5300 if (level < 0 || level >= NB_LOG_LEVELS)
5301 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5302
5303 hlua_sendlog(htxn->s->be, level, msg);
5304 return 0;
5305}
5306
5307__LJMP static int hlua_txn_log_debug(lua_State *L)
5308{
5309 const char *msg;
5310 struct hlua_txn *htxn;
5311
5312 MAY_LJMP(check_args(L, 2, "Debug"));
5313 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5314 msg = MAY_LJMP(luaL_checkstring(L, 2));
5315 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5316 return 0;
5317}
5318
5319__LJMP static int hlua_txn_log_info(lua_State *L)
5320{
5321 const char *msg;
5322 struct hlua_txn *htxn;
5323
5324 MAY_LJMP(check_args(L, 2, "Info"));
5325 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5326 msg = MAY_LJMP(luaL_checkstring(L, 2));
5327 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5328 return 0;
5329}
5330
5331__LJMP static int hlua_txn_log_warning(lua_State *L)
5332{
5333 const char *msg;
5334 struct hlua_txn *htxn;
5335
5336 MAY_LJMP(check_args(L, 2, "Warning"));
5337 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5338 msg = MAY_LJMP(luaL_checkstring(L, 2));
5339 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5340 return 0;
5341}
5342
5343__LJMP static int hlua_txn_log_alert(lua_State *L)
5344{
5345 const char *msg;
5346 struct hlua_txn *htxn;
5347
5348 MAY_LJMP(check_args(L, 2, "Alert"));
5349 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5350 msg = MAY_LJMP(luaL_checkstring(L, 2));
5351 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5352 return 0;
5353}
5354
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005355__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5356{
5357 struct hlua_txn *htxn;
5358 int ll;
5359
5360 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5361 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5362 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5363
5364 if (ll < 0 || ll > 7)
5365 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5366
5367 htxn->s->logs.level = ll;
5368 return 0;
5369}
5370
5371__LJMP static int hlua_txn_set_tos(lua_State *L)
5372{
5373 struct hlua_txn *htxn;
5374 struct connection *cli_conn;
5375 int tos;
5376
5377 MAY_LJMP(check_args(L, 2, "set_tos"));
5378 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5379 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5380
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005381 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005382 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005383
5384 return 0;
5385}
5386
5387__LJMP static int hlua_txn_set_mark(lua_State *L)
5388{
5389#ifdef SO_MARK
5390 struct hlua_txn *htxn;
5391 struct connection *cli_conn;
5392 int mark;
5393
5394 MAY_LJMP(check_args(L, 2, "set_mark"));
5395 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5396 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5397
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005398 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005399 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005400#endif
5401 return 0;
5402}
5403
Patrick Hemmer268a7072018-05-11 12:52:31 -04005404__LJMP static int hlua_txn_set_priority_class(lua_State *L)
5405{
5406 struct hlua_txn *htxn;
5407
5408 MAY_LJMP(check_args(L, 2, "set_priority_class"));
5409 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5410 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
5411 return 0;
5412}
5413
5414__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
5415{
5416 struct hlua_txn *htxn;
5417
5418 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
5419 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5420 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
5421 return 0;
5422}
5423
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005424/* This function is an Lua binding that send pending data
5425 * to the client, and close the stream interface.
5426 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005427__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005428{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005429 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005430 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005431 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005432
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005433 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005434 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005435 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005436
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005437 /* If the flags NOTERM is set, we cannot terminate the http
5438 * session, so we just end the execution of the current
5439 * lua code.
5440 */
5441 if (htxn->flags & HLUA_TXN_NOTERM) {
5442 WILL_LJMP(hlua_done(L));
5443 return 0;
5444 }
5445
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005446 ic = &htxn->s->req;
5447 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005448
Willy Tarreau630ef452015-08-28 10:06:15 +02005449 if (htxn->s->txn) {
5450 /* HTTP mode, let's stay in sync with the stream */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02005451 b_del(&ic->buf, htxn->s->txn->req.sov);
Willy Tarreau630ef452015-08-28 10:06:15 +02005452 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5453 htxn->s->txn->req.sov = 0;
5454 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5455 oc->analysers = AN_RES_HTTP_XFER_BODY;
5456 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5457 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5458
Willy Tarreau630ef452015-08-28 10:06:15 +02005459 /* Note that if we want to support keep-alive, we need
5460 * to bypass the close/shutr_now calls below, but that
5461 * may only be done if the HTTP request was already
5462 * processed and the connection header is known (ie
5463 * not during TCP rules).
5464 */
5465 }
5466
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005467 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005468 channel_abort(ic);
5469 channel_auto_close(ic);
5470 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005471
5472 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005473 channel_auto_read(oc);
5474 channel_auto_close(oc);
5475 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005476
Willy Tarreau0458b082015-08-28 09:40:04 +02005477 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005478
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005479 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005480 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005481 return 0;
5482}
5483
5484__LJMP static int hlua_log(lua_State *L)
5485{
5486 int level;
5487 const char *msg;
5488
5489 MAY_LJMP(check_args(L, 2, "log"));
5490 level = MAY_LJMP(luaL_checkinteger(L, 1));
5491 msg = MAY_LJMP(luaL_checkstring(L, 2));
5492
5493 if (level < 0 || level >= NB_LOG_LEVELS)
5494 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5495
5496 hlua_sendlog(NULL, level, msg);
5497 return 0;
5498}
5499
5500__LJMP static int hlua_log_debug(lua_State *L)
5501{
5502 const char *msg;
5503
5504 MAY_LJMP(check_args(L, 1, "debug"));
5505 msg = MAY_LJMP(luaL_checkstring(L, 1));
5506 hlua_sendlog(NULL, LOG_DEBUG, msg);
5507 return 0;
5508}
5509
5510__LJMP static int hlua_log_info(lua_State *L)
5511{
5512 const char *msg;
5513
5514 MAY_LJMP(check_args(L, 1, "info"));
5515 msg = MAY_LJMP(luaL_checkstring(L, 1));
5516 hlua_sendlog(NULL, LOG_INFO, msg);
5517 return 0;
5518}
5519
5520__LJMP static int hlua_log_warning(lua_State *L)
5521{
5522 const char *msg;
5523
5524 MAY_LJMP(check_args(L, 1, "warning"));
5525 msg = MAY_LJMP(luaL_checkstring(L, 1));
5526 hlua_sendlog(NULL, LOG_WARNING, msg);
5527 return 0;
5528}
5529
5530__LJMP static int hlua_log_alert(lua_State *L)
5531{
5532 const char *msg;
5533
5534 MAY_LJMP(check_args(L, 1, "alert"));
5535 msg = MAY_LJMP(luaL_checkstring(L, 1));
5536 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005537 return 0;
5538}
5539
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005540__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005541{
5542 int wakeup_ms = lua_tointeger(L, -1);
5543 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02005544 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005545 return 0;
5546}
5547
5548__LJMP static int hlua_sleep(lua_State *L)
5549{
5550 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005551 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005552
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005553 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005554
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005555 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005556 wakeup_ms = tick_add(now_ms, delay);
5557 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005558
Willy Tarreau9635e032018-10-16 17:52:55 +02005559 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005560 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005561}
5562
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005563__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005564{
5565 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005566 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005567
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005568 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005569
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005570 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005571 wakeup_ms = tick_add(now_ms, delay);
5572 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005573
Willy Tarreau9635e032018-10-16 17:52:55 +02005574 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005575 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005576}
5577
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005578/* This functionis an LUA binding. it permits to give back
5579 * the hand at the HAProxy scheduler. It is used when the
5580 * LUA processing consumes a lot of time.
5581 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005582__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005583{
5584 return 0;
5585}
5586
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005587__LJMP static int hlua_yield(lua_State *L)
5588{
Willy Tarreau9635e032018-10-16 17:52:55 +02005589 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005590 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005591}
5592
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005593/* This function change the nice of the currently executed
5594 * task. It is used set low or high priority at the current
5595 * task.
5596 */
Willy Tarreau59551662015-03-10 14:23:13 +01005597__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005598{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005599 struct hlua *hlua;
5600 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005601
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005602 MAY_LJMP(check_args(L, 1, "set_nice"));
5603 hlua = hlua_gethlua(L);
5604 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005605
5606 /* If he task is not set, I'm in a start mode. */
5607 if (!hlua || !hlua->task)
5608 return 0;
5609
5610 if (nice < -1024)
5611 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005612 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005613 nice = 1024;
5614
5615 hlua->task->nice = nice;
5616 return 0;
5617}
5618
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005619/* This function is used as a calback of a task. It is called by the
5620 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5621 * return an E_AGAIN signal, the emmiter of this signal must set a
5622 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005623 *
5624 * Task wrapper are longjmp safe because the only one Lua code
5625 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005626 */
Olivier Houchard9f6af332018-05-25 14:04:04 +02005627static struct task *hlua_process_task(struct task *task, void *context, unsigned short state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005628{
Olivier Houchard9f6af332018-05-25 14:04:04 +02005629 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005630 enum hlua_exec status;
5631
Christopher Faulet5bc99722018-04-25 10:34:45 +02005632 if (task->thread_mask == MAX_THREADS_MASK)
5633 task_set_affinity(task, tid_bit);
5634
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005635 /* If it is the first call to the task, we must initialize the
5636 * execution timeouts.
5637 */
5638 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005639 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005640
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005641 /* Execute the Lua code. */
5642 status = hlua_ctx_resume(hlua, 1);
5643
5644 switch (status) {
5645 /* finished or yield */
5646 case HLUA_E_OK:
5647 hlua_ctx_destroy(hlua);
5648 task_delete(task);
5649 task_free(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02005650 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005651 break;
5652
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005653 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01005654 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02005655 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005656 break;
5657
5658 /* finished with error. */
5659 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005660 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005661 hlua_ctx_destroy(hlua);
5662 task_delete(task);
5663 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005664 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005665 break;
5666
5667 case HLUA_E_ERR:
5668 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005669 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005670 hlua_ctx_destroy(hlua);
5671 task_delete(task);
5672 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005673 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005674 break;
5675 }
Emeric Brun253e53e2017-10-17 18:58:40 +02005676 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005677}
5678
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005679/* This function is an LUA binding that register LUA function to be
5680 * executed after the HAProxy configuration parsing and before the
5681 * HAProxy scheduler starts. This function expect only one LUA
5682 * argument that is a function. This function returns nothing, but
5683 * throws if an error is encountered.
5684 */
5685__LJMP static int hlua_register_init(lua_State *L)
5686{
5687 struct hlua_init_function *init;
5688 int ref;
5689
5690 MAY_LJMP(check_args(L, 1, "register_init"));
5691
5692 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5693
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005694 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005695 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005696 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005697
5698 init->function_ref = ref;
5699 LIST_ADDQ(&hlua_init_functions, &init->l);
5700 return 0;
5701}
5702
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005703/* This functio is an LUA binding. It permits to register a task
5704 * executed in parallel of the main HAroxy activity. The task is
5705 * created and it is set in the HAProxy scheduler. It can be called
5706 * from the "init" section, "post init" or during the runtime.
5707 *
5708 * Lua prototype:
5709 *
5710 * <none> core.register_task(<function>)
5711 */
5712static int hlua_register_task(lua_State *L)
5713{
5714 struct hlua *hlua;
5715 struct task *task;
5716 int ref;
5717
5718 MAY_LJMP(check_args(L, 1, "register_task"));
5719
5720 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5721
Willy Tarreaubafbe012017-11-24 17:34:44 +01005722 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005723 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005724 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005725
Emeric Brunc60def82017-09-27 14:59:38 +02005726 task = task_new(MAX_THREADS_MASK);
Willy Tarreaue09101e2018-10-16 17:37:12 +02005727 if (!task)
5728 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
5729
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005730 task->context = hlua;
5731 task->process = hlua_process_task;
5732
5733 if (!hlua_ctx_init(hlua, task))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005734 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005735
5736 /* Restore the function in the stack. */
5737 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5738 hlua->nargs = 0;
5739
5740 /* Schedule task. */
5741 task_schedule(task, now_ms);
5742
5743 return 0;
5744}
5745
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005746/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5747 * doesn't allow "yield" functions because the HAProxy engine cannot
5748 * resume converters.
5749 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005750static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005751{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005752 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005753 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005754 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005755
Willy Tarreaube508f12016-03-10 11:47:01 +01005756 if (!stream)
5757 return 0;
5758
Willy Tarreau87b09662015-04-03 00:22:06 +02005759 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005760 * Lua context can be not initialized. This behavior
5761 * permits to save performances because a systematic
5762 * Lua initialization cause 5% performances loss.
5763 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005764 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005765 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005766 if (!stream->hlua) {
5767 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5768 return 0;
5769 }
5770 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5771 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5772 return 0;
5773 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005774 }
5775
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005776 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005777 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005778
5779 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005780 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5781 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5782 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005783 else
5784 error = "critical error";
5785 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005786 return 0;
5787 }
5788
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005789 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005790 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005791 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005792 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005793 return 0;
5794 }
5795
5796 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005797 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005798
5799 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005800 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005801 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005802 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005803 return 0;
5804 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005805 hlua_smp2lua(stream->hlua->T, smp);
5806 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005807
5808 /* push keywords in the stack. */
5809 if (arg_p) {
5810 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005811 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005812 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005813 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005814 return 0;
5815 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005816 hlua_arg2lua(stream->hlua->T, arg_p);
5817 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005818 }
5819 }
5820
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005821 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005822 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005823
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005824 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005825 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005826 }
5827
5828 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005829 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005830 /* finished. */
5831 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005832 /* If the stack is empty, the function fails. */
5833 if (lua_gettop(stream->hlua->T) <= 0)
5834 return 0;
5835
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005836 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005837 hlua_lua2smp(stream->hlua->T, -1, smp);
5838 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005839 return 1;
5840
5841 /* yield. */
5842 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005843 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005844 return 0;
5845
5846 /* finished with error. */
5847 case HLUA_E_ERRMSG:
5848 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005849 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005850 fcn->name, lua_tostring(stream->hlua->T, -1));
5851 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005852 return 0;
5853
Thierry Fournierd5b073c2018-05-21 19:42:47 +02005854 case HLUA_E_ETMOUT:
5855 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
5856 return 0;
5857
5858 case HLUA_E_NOMEM:
5859 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
5860 return 0;
5861
5862 case HLUA_E_YIELD:
5863 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
5864 return 0;
5865
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005866 case HLUA_E_ERR:
5867 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005868 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005869
5870 default:
5871 return 0;
5872 }
5873}
5874
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005875/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5876 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005877 * resume sample-fetches. This function will be called by the sample
5878 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005879 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005880static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5881 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005882{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005883 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005884 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005885 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02005886 const struct buffer msg = { };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005887
Willy Tarreaube508f12016-03-10 11:47:01 +01005888 if (!stream)
5889 return 0;
5890
Willy Tarreau87b09662015-04-03 00:22:06 +02005891 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005892 * Lua context can be not initialized. This behavior
5893 * permits to save performances because a systematic
5894 * Lua initialization cause 5% performances loss.
5895 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005896 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005897 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005898 if (!stream->hlua) {
5899 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5900 return 0;
5901 }
5902 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5903 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5904 return 0;
5905 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005906 }
5907
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005908 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005909
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005910 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005911 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005912
5913 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005914 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5915 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5916 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005917 else
5918 error = "critical error";
5919 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005920 return 0;
5921 }
5922
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005923 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005924 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005925 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005926 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005927 return 0;
5928 }
5929
5930 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005931 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005932
5933 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005934 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005935 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005936 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005937 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005938 return 0;
5939 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005940 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005941
5942 /* push keywords in the stack. */
5943 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5944 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005945 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005946 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005947 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005948 return 0;
5949 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005950 hlua_arg2lua(stream->hlua->T, arg_p);
5951 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005952 }
5953
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005954 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005955 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005956
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005957 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005958 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005959 }
5960
5961 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005962 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005963 /* finished. */
5964 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005965 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005966 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005967 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005968 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005969 /* If the stack is empty, the function fails. */
5970 if (lua_gettop(stream->hlua->T) <= 0)
5971 return 0;
5972
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005973 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005974 hlua_lua2smp(stream->hlua->T, -1, smp);
5975 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005976
5977 /* Set the end of execution flag. */
5978 smp->flags &= ~SMP_F_MAY_CHANGE;
5979 return 1;
5980
5981 /* yield. */
5982 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005983 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005984 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005985 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005986 return 0;
5987
5988 /* finished with error. */
5989 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005990 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005991 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005992 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005993 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005994 fcn->name, lua_tostring(stream->hlua->T, -1));
5995 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005996 return 0;
5997
Thierry Fournierd5b073c2018-05-21 19:42:47 +02005998 case HLUA_E_ETMOUT:
5999 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
6000 stream_int_retnclose(&stream->si[0], &msg);
6001 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
6002 return 0;
6003
6004 case HLUA_E_NOMEM:
6005 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
6006 stream_int_retnclose(&stream->si[0], &msg);
6007 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
6008 return 0;
6009
6010 case HLUA_E_YIELD:
6011 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
6012 stream_int_retnclose(&stream->si[0], &msg);
6013 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
6014 return 0;
6015
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006016 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006017 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006018 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006019 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006020 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006021
6022 default:
6023 return 0;
6024 }
6025}
6026
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006027/* This function is an LUA binding used for registering
6028 * "sample-conv" functions. It expects a converter name used
6029 * in the haproxy configuration file, and an LUA function.
6030 */
6031__LJMP static int hlua_register_converters(lua_State *L)
6032{
6033 struct sample_conv_kw_list *sck;
6034 const char *name;
6035 int ref;
6036 int len;
6037 struct hlua_function *fcn;
6038
6039 MAY_LJMP(check_args(L, 2, "register_converters"));
6040
6041 /* First argument : converter name. */
6042 name = MAY_LJMP(luaL_checkstring(L, 1));
6043
6044 /* Second argument : lua function. */
6045 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6046
6047 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006048 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006049 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006050 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006051 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006052 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006053 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006054
6055 /* Fill fcn. */
6056 fcn->name = strdup(name);
6057 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006058 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006059 fcn->function_ref = ref;
6060
6061 /* List head */
6062 sck->list.n = sck->list.p = NULL;
6063
6064 /* converter keyword. */
6065 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006066 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006067 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006068 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006069
6070 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6071 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006072 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 +01006073 sck->kw[0].val_args = NULL;
6074 sck->kw[0].in_type = SMP_T_STR;
6075 sck->kw[0].out_type = SMP_T_STR;
6076 sck->kw[0].private = fcn;
6077
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006078 /* Register this new converter */
6079 sample_register_convs(sck);
6080
6081 return 0;
6082}
6083
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006084/* This fucntion is an LUA binding used for registering
6085 * "sample-fetch" functions. It expects a converter name used
6086 * in the haproxy configuration file, and an LUA function.
6087 */
6088__LJMP static int hlua_register_fetches(lua_State *L)
6089{
6090 const char *name;
6091 int ref;
6092 int len;
6093 struct sample_fetch_kw_list *sfk;
6094 struct hlua_function *fcn;
6095
6096 MAY_LJMP(check_args(L, 2, "register_fetches"));
6097
6098 /* First argument : sample-fetch name. */
6099 name = MAY_LJMP(luaL_checkstring(L, 1));
6100
6101 /* Second argument : lua function. */
6102 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6103
6104 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006105 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006106 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006107 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006108 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006109 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006110 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006111
6112 /* Fill fcn. */
6113 fcn->name = strdup(name);
6114 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006115 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006116 fcn->function_ref = ref;
6117
6118 /* List head */
6119 sfk->list.n = sfk->list.p = NULL;
6120
6121 /* sample-fetch keyword. */
6122 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006123 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006124 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006125 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006126
6127 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6128 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006129 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 +01006130 sfk->kw[0].val_args = NULL;
6131 sfk->kw[0].out_type = SMP_T_STR;
6132 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6133 sfk->kw[0].val = 0;
6134 sfk->kw[0].private = fcn;
6135
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006136 /* Register this new fetch. */
6137 sample_register_fetches(sfk);
6138
6139 return 0;
6140}
6141
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006142/* This function is a wrapper to execute each LUA function declared
6143 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006144 * return ACT_RET_CONT if the processing is finished (with or without
6145 * error) and return ACT_RET_YIELD if the function must be called again
6146 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006147 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006148static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006149 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006150{
6151 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006152 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006153 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006154 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006155 const struct buffer msg = { };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006156
6157 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01006158 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
6159 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
6160 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
6161 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006162 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006163 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006164 return ACT_RET_CONT;
6165 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006166
Willy Tarreau87b09662015-04-03 00:22:06 +02006167 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006168 * Lua context can be not initialized. This behavior
6169 * permits to save performances because a systematic
6170 * Lua initialization cause 5% performances loss.
6171 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006172 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006173 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006174 if (!s->hlua) {
6175 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6176 rule->arg.hlua_rule->fcn.name);
6177 return ACT_RET_CONT;
6178 }
6179 if (!hlua_ctx_init(s->hlua, s->task)) {
6180 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6181 rule->arg.hlua_rule->fcn.name);
6182 return ACT_RET_CONT;
6183 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006184 }
6185
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006186 consistency_set(s, dir, &s->hlua->cons);
6187
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006188 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006189 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006190
6191 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006192 if (!SET_SAFE_LJMP(s->hlua->T)) {
6193 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6194 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006195 else
6196 error = "critical error";
6197 SEND_ERR(px, "Lua function '%s': %s.\n",
6198 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006199 return ACT_RET_CONT;
6200 }
6201
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006202 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006203 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006204 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006205 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006206 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006207 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006208 }
6209
6210 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006211 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006212
Willy Tarreau87b09662015-04-03 00:22:06 +02006213 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006214 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006215 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006216 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006217 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006218 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006219 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006220 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006221
6222 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006223 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006224 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006225 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006226 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006227 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006228 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006229 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006230 lua_pushstring(s->hlua->T, *arg);
6231 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006232 }
6233
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006234 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006235 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006236
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006237 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006238 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006239 }
6240
6241 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006242 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006243 /* finished. */
6244 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006245 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006246 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006247 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006248 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006249 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006250 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006251 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006252
6253 /* yield. */
6254 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006255 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006256 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006257 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006258 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006259 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006260 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006261 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006262 /* Some actions can be wake up when a "write" event
6263 * is detected on a response channel. This is useful
6264 * only for actions targetted on the requests.
6265 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006266 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006267 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01006268 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006269 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006270 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006271 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006272 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006273 /* We can quit the fcuntion without consistency check
6274 * because HAProxy is not able to manipulate data, it
6275 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006276 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006277
6278 /* finished with error. */
6279 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006280 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006281 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006282 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006283 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006284 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006285 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006286 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6287 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006288 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006289
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006290 case HLUA_E_ETMOUT:
6291 if (!consistency_check(s, dir, &s->hlua->cons)) {
6292 stream_int_retnclose(&s->si[0], &msg);
6293 return ACT_RET_ERR;
6294 }
6295 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
6296 return 0;
6297
6298 case HLUA_E_NOMEM:
6299 if (!consistency_check(s, dir, &s->hlua->cons)) {
6300 stream_int_retnclose(&s->si[0], &msg);
6301 return ACT_RET_ERR;
6302 }
6303 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
6304 return 0;
6305
6306 case HLUA_E_YIELD:
6307 if (!consistency_check(s, dir, &s->hlua->cons)) {
6308 stream_int_retnclose(&s->si[0], &msg);
6309 return ACT_RET_ERR;
6310 }
6311 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6312 rule->arg.hlua_rule->fcn.name);
6313 return 0;
6314
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006315 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006316 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006317 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006318 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006319 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006320 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006321 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006322 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006323
6324 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006325 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006326 }
6327}
6328
Olivier Houchard9f6af332018-05-25 14:04:04 +02006329struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006330{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006331 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006332
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006333 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006334 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006335 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006336}
6337
6338static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6339{
6340 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006341 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006342 struct task *task;
6343 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006344 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006345
Willy Tarreaubafbe012017-11-24 17:34:44 +01006346 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006347 if (!hlua) {
6348 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6349 ctx->rule->arg.hlua_rule->fcn.name);
6350 return 0;
6351 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006352 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006353 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006354 ctx->ctx.hlua_apptcp.flags = 0;
6355
6356 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006357 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006358 if (!task) {
6359 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6360 ctx->rule->arg.hlua_rule->fcn.name);
6361 return 0;
6362 }
6363 task->nice = 0;
6364 task->context = ctx;
6365 task->process = hlua_applet_wakeup;
6366 ctx->ctx.hlua_apptcp.task = task;
6367
6368 /* In the execution wrappers linked with a stream, the
6369 * Lua context can be not initialized. This behavior
6370 * permits to save performances because a systematic
6371 * Lua initialization cause 5% performances loss.
6372 */
6373 if (!hlua_ctx_init(hlua, task)) {
6374 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6375 ctx->rule->arg.hlua_rule->fcn.name);
6376 return 0;
6377 }
6378
6379 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006380 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006381
6382 /* The following Lua calls can fail. */
6383 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006384 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6385 error = lua_tostring(hlua->T, -1);
6386 else
6387 error = "critical error";
6388 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6389 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006390 return 0;
6391 }
6392
6393 /* Check stack available size. */
6394 if (!lua_checkstack(hlua->T, 1)) {
6395 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6396 ctx->rule->arg.hlua_rule->fcn.name);
6397 RESET_SAFE_LJMP(hlua->T);
6398 return 0;
6399 }
6400
6401 /* Restore the function in the stack. */
6402 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6403
6404 /* Create and and push object stream in the stack. */
6405 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6406 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6407 ctx->rule->arg.hlua_rule->fcn.name);
6408 RESET_SAFE_LJMP(hlua->T);
6409 return 0;
6410 }
6411 hlua->nargs = 1;
6412
6413 /* push keywords in the stack. */
6414 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6415 if (!lua_checkstack(hlua->T, 1)) {
6416 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6417 ctx->rule->arg.hlua_rule->fcn.name);
6418 RESET_SAFE_LJMP(hlua->T);
6419 return 0;
6420 }
6421 lua_pushstring(hlua->T, *arg);
6422 hlua->nargs++;
6423 }
6424
6425 RESET_SAFE_LJMP(hlua->T);
6426
6427 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01006428 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01006429 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006430
6431 return 1;
6432}
6433
6434static void hlua_applet_tcp_fct(struct appctx *ctx)
6435{
6436 struct stream_interface *si = ctx->owner;
6437 struct stream *strm = si_strm(si);
6438 struct channel *res = si_ic(si);
6439 struct act_rule *rule = ctx->rule;
6440 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006441 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006442
6443 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02006444 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
6445 /* eat the whole request */
6446 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006447 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02006448 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006449
6450 /* If the stream is disconnect or closed, ldo nothing. */
6451 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6452 return;
6453
6454 /* Execute the function. */
6455 switch (hlua_ctx_resume(hlua, 1)) {
6456 /* finished. */
6457 case HLUA_E_OK:
6458 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6459
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006460 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02006461 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006462 res->flags |= CF_READ_NULL;
6463 si_shutr(si);
6464 return;
6465
6466 /* yield. */
6467 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006468 if (hlua->wake_time != TICK_ETERNITY)
6469 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006470 return;
6471
6472 /* finished with error. */
6473 case HLUA_E_ERRMSG:
6474 /* Display log. */
6475 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6476 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6477 lua_pop(hlua->T, 1);
6478 goto error;
6479
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006480 case HLUA_E_ETMOUT:
6481 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
6482 rule->arg.hlua_rule->fcn.name);
6483 goto error;
6484
6485 case HLUA_E_NOMEM:
6486 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
6487 rule->arg.hlua_rule->fcn.name);
6488 goto error;
6489
6490 case HLUA_E_YIELD: /* unexpected */
6491 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
6492 rule->arg.hlua_rule->fcn.name);
6493 goto error;
6494
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006495 case HLUA_E_ERR:
6496 /* Display log. */
6497 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6498 rule->arg.hlua_rule->fcn.name);
6499 goto error;
6500
6501 default:
6502 goto error;
6503 }
6504
6505error:
6506
6507 /* For all other cases, just close the stream. */
6508 si_shutw(si);
6509 si_shutr(si);
6510 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6511}
6512
6513static void hlua_applet_tcp_release(struct appctx *ctx)
6514{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006515 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006516 task_free(ctx->ctx.hlua_apptcp.task);
6517 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006518 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006519 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006520}
6521
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006522/* The function returns 1 if the initialisation is complete, 0 if
6523 * an errors occurs and -1 if more data are required for initializing
6524 * the applet.
6525 */
6526static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6527{
6528 struct stream_interface *si = ctx->owner;
6529 struct channel *req = si_oc(si);
6530 struct http_msg *msg;
6531 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006532 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006533 char **arg;
6534 struct hdr_ctx hdr;
6535 struct task *task;
6536 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006537 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006538
6539 /* Wait for a full HTTP request. */
6540 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6541 if (smp.flags & SMP_F_MAY_CHANGE)
6542 return -1;
6543 return 0;
6544 }
6545 txn = strm->txn;
6546 msg = &txn->req;
6547
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006548 /* We want two things in HTTP mode :
6549 * - enforce server-close mode if we were in keep-alive, so that the
6550 * applet is released after each response ;
6551 * - enable request body transfer to the applet in order to resync
6552 * with the response body.
6553 */
6554 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6555 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006556
Willy Tarreaubafbe012017-11-24 17:34:44 +01006557 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006558 if (!hlua) {
6559 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6560 ctx->rule->arg.hlua_rule->fcn.name);
6561 return 0;
6562 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006563 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006564 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006565 ctx->ctx.hlua_apphttp.left_bytes = -1;
6566 ctx->ctx.hlua_apphttp.flags = 0;
6567
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006568 if (txn->req.flags & HTTP_MSGF_VER_11)
6569 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6570
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006571 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006572 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006573 if (!task) {
6574 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6575 ctx->rule->arg.hlua_rule->fcn.name);
6576 return 0;
6577 }
6578 task->nice = 0;
6579 task->context = ctx;
6580 task->process = hlua_applet_wakeup;
6581 ctx->ctx.hlua_apphttp.task = task;
6582
6583 /* In the execution wrappers linked with a stream, the
6584 * Lua context can be not initialized. This behavior
6585 * permits to save performances because a systematic
6586 * Lua initialization cause 5% performances loss.
6587 */
6588 if (!hlua_ctx_init(hlua, task)) {
6589 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6590 ctx->rule->arg.hlua_rule->fcn.name);
6591 return 0;
6592 }
6593
6594 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006595 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006596
6597 /* The following Lua calls can fail. */
6598 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006599 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6600 error = lua_tostring(hlua->T, -1);
6601 else
6602 error = "critical error";
6603 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6604 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006605 return 0;
6606 }
6607
6608 /* Check stack available size. */
6609 if (!lua_checkstack(hlua->T, 1)) {
6610 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6611 ctx->rule->arg.hlua_rule->fcn.name);
6612 RESET_SAFE_LJMP(hlua->T);
6613 return 0;
6614 }
6615
6616 /* Restore the function in the stack. */
6617 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6618
6619 /* Create and and push object stream in the stack. */
6620 if (!hlua_applet_http_new(hlua->T, ctx)) {
6621 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6622 ctx->rule->arg.hlua_rule->fcn.name);
6623 RESET_SAFE_LJMP(hlua->T);
6624 return 0;
6625 }
6626 hlua->nargs = 1;
6627
6628 /* Look for a 100-continue expected. */
6629 if (msg->flags & HTTP_MSGF_VER_11) {
6630 hdr.idx = 0;
Willy Tarreaua79021a2018-06-15 18:07:57 +02006631 if (http_find_header2("Expect", 6, ci_head(req), &txn->hdr_idx, &hdr) &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006632 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6633 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6634 }
6635
6636 /* push keywords in the stack. */
6637 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6638 if (!lua_checkstack(hlua->T, 1)) {
6639 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6640 ctx->rule->arg.hlua_rule->fcn.name);
6641 RESET_SAFE_LJMP(hlua->T);
6642 return 0;
6643 }
6644 lua_pushstring(hlua->T, *arg);
6645 hlua->nargs++;
6646 }
6647
6648 RESET_SAFE_LJMP(hlua->T);
6649
6650 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01006651 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006652
6653 return 1;
6654}
6655
6656static void hlua_applet_http_fct(struct appctx *ctx)
6657{
6658 struct stream_interface *si = ctx->owner;
6659 struct stream *strm = si_strm(si);
6660 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006661 struct act_rule *rule = ctx->rule;
6662 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006663 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Willy Tarreau206ba832018-06-14 15:27:31 +02006664 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02006665 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02006666 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02006667 size_t len2;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006668 int ret;
6669
6670 /* If the stream is disconnect or closed, ldo nothing. */
6671 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6672 return;
6673
6674 /* Set the currently running flag. */
6675 if (!HLUA_IS_RUNNING(hlua) &&
6676 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6677
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006678 /* Wait for full HTTP analysys. */
6679 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01006680 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006681 return;
6682 }
6683
6684 /* Store the max amount of bytes that we can read. */
6685 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6686
6687 /* We need to flush the request header. This left the body
6688 * for the Lua.
6689 */
6690
6691 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006692 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006693 if (ret == -1)
6694 return;
6695
6696 /* No data available, ask for more data. */
6697 if (ret == 1)
6698 len2 = 0;
6699 if (ret == 0)
6700 len1 = 0;
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02006701 if (len1 + len2 < strm->txn->req.eoh + strm->txn->req.eol) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01006702 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006703 return;
6704 }
6705
6706 /* skip the requests bytes. */
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02006707 co_skip(si_oc(si), strm->txn->req.eoh + strm->txn->req.eol);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006708 }
6709
6710 /* Executes The applet if it is not done. */
6711 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6712
6713 /* Execute the function. */
6714 switch (hlua_ctx_resume(hlua, 1)) {
6715 /* finished. */
6716 case HLUA_E_OK:
6717 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6718 break;
6719
6720 /* yield. */
6721 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006722 if (hlua->wake_time != TICK_ETERNITY)
6723 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006724 return;
6725
6726 /* finished with error. */
6727 case HLUA_E_ERRMSG:
6728 /* Display log. */
6729 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6730 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6731 lua_pop(hlua->T, 1);
6732 goto error;
6733
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006734 case HLUA_E_ETMOUT:
6735 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
6736 rule->arg.hlua_rule->fcn.name);
6737 goto error;
6738
6739 case HLUA_E_NOMEM:
6740 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
6741 rule->arg.hlua_rule->fcn.name);
6742 goto error;
6743
6744 case HLUA_E_YIELD: /* unexpected */
6745 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
6746 rule->arg.hlua_rule->fcn.name);
6747 goto error;
6748
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006749 case HLUA_E_ERR:
6750 /* Display log. */
6751 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6752 rule->arg.hlua_rule->fcn.name);
6753 goto error;
6754
6755 default:
6756 goto error;
6757 }
6758 }
6759
6760 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6761
6762 /* We must send the final chunk. */
6763 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6764 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6765
6766 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006767 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006768
6769 /* critical error. */
6770 if (ret == -2 || ret == -3) {
6771 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6772 rule->arg.hlua_rule->fcn.name);
6773 goto error;
6774 }
6775
6776 /* no enough space error. */
6777 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01006778 si_rx_room_blk(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006779 return;
6780 }
6781
6782 /* set the last chunk sent. */
6783 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6784 }
6785
6786 /* close the connection. */
6787
Frédéric Lécaille83ed5d52018-07-18 14:25:26 +02006788 /* status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006789 strm->txn->status = ctx->ctx.hlua_apphttp.status;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006790
6791 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02006792 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006793 res->flags |= CF_READ_NULL;
6794 si_shutr(si);
6795
6796 return;
6797 }
6798
6799error:
6800
6801 /* If we are in HTTP mode, and we are not send any
6802 * data, return a 500 server error in best effort:
6803 * if there are no room avalaible in the buffer,
6804 * just close the connection.
6805 */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006806 ci_putblk(res, error_500, strlen(error_500));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006807 if (!(strm->flags & SF_ERR_MASK))
6808 strm->flags |= SF_ERR_RESOURCE;
6809 si_shutw(si);
6810 si_shutr(si);
6811 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6812}
6813
6814static void hlua_applet_http_release(struct appctx *ctx)
6815{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006816 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006817 task_free(ctx->ctx.hlua_apphttp.task);
6818 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006819 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006820 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006821}
6822
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006823/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6824 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006825 *
6826 * This function can fail with an abort() due to an Lua critical error.
6827 * We are in the configuration parsing process of HAProxy, this abort() is
6828 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006829 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006830static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6831 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006832{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006833 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006834 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006835
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006836 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006837 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006838 if (!rule->arg.hlua_rule) {
6839 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006840 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006841 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006842
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006843 /* Memory for arguments. */
6844 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6845 if (!rule->arg.hlua_rule->args) {
6846 memprintf(err, "out of memory error");
6847 return ACT_RET_PRS_ERR;
6848 }
6849
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006850 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006851 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006852
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006853 /* Expect some arguments */
6854 for (i = 0; i < fcn->nargs; i++) {
6855 if (*args[i+1] == '\0') {
6856 memprintf(err, "expect %d arguments", fcn->nargs);
6857 return ACT_RET_PRS_ERR;
6858 }
6859 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6860 if (!rule->arg.hlua_rule->args[i]) {
6861 memprintf(err, "out of memory error");
6862 return ACT_RET_PRS_ERR;
6863 }
6864 (*cur_arg)++;
6865 }
6866 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006867
Thierry FOURNIER42148732015-09-02 17:17:33 +02006868 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006869 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006870 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006871}
6872
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006873static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6874 struct act_rule *rule, char **err)
6875{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006876 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006877
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006878 /* HTTP applets are forbidden in tcp-request rules.
6879 * HTTP applet request requires everything initilized by
6880 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6881 * The applet will be immediately initilized, but its before
6882 * the call of this analyzer.
6883 */
6884 if (rule->from != ACT_F_HTTP_REQ) {
6885 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6886 return ACT_RET_PRS_ERR;
6887 }
6888
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006889 /* Memory for the rule. */
6890 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6891 if (!rule->arg.hlua_rule) {
6892 memprintf(err, "out of memory error");
6893 return ACT_RET_PRS_ERR;
6894 }
6895
6896 /* Reference the Lua function and store the reference. */
6897 rule->arg.hlua_rule->fcn = *fcn;
6898
6899 /* TODO: later accept arguments. */
6900 rule->arg.hlua_rule->args = NULL;
6901
6902 /* Add applet pointer in the rule. */
6903 rule->applet.obj_type = OBJ_TYPE_APPLET;
6904 rule->applet.name = fcn->name;
6905 rule->applet.init = hlua_applet_http_init;
6906 rule->applet.fct = hlua_applet_http_fct;
6907 rule->applet.release = hlua_applet_http_release;
6908 rule->applet.timeout = hlua_timeout_applet;
6909
6910 return ACT_RET_PRS_OK;
6911}
6912
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006913/* This function is an LUA binding used for registering
6914 * "sample-conv" functions. It expects a converter name used
6915 * in the haproxy configuration file, and an LUA function.
6916 */
6917__LJMP static int hlua_register_action(lua_State *L)
6918{
6919 struct action_kw_list *akl;
6920 const char *name;
6921 int ref;
6922 int len;
6923 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006924 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006925
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006926 /* Initialise the number of expected arguments at 0. */
6927 nargs = 0;
6928
6929 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6930 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006931
6932 /* First argument : converter name. */
6933 name = MAY_LJMP(luaL_checkstring(L, 1));
6934
6935 /* Second argument : environment. */
6936 if (lua_type(L, 2) != LUA_TTABLE)
6937 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6938
6939 /* Third argument : lua function. */
6940 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6941
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006942 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6943 if (lua_gettop(L) >= 4)
6944 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6945
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006946 /* browse the second argulent as an array. */
6947 lua_pushnil(L);
6948 while (lua_next(L, 2) != 0) {
6949 if (lua_type(L, -1) != LUA_TSTRING)
6950 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6951
6952 /* Check required environment. Only accepted "http" or "tcp". */
6953 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006954 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006955 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006956 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006957 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006958 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006959 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006960
6961 /* Fill fcn. */
6962 fcn->name = strdup(name);
6963 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006964 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006965 fcn->function_ref = ref;
6966
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006967 /* Set the expected number od arguments. */
6968 fcn->nargs = nargs;
6969
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006970 /* List head */
6971 akl->list.n = akl->list.p = NULL;
6972
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006973 /* action keyword. */
6974 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006975 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006976 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006977 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006978
6979 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6980
6981 akl->kw[0].match_pfx = 0;
6982 akl->kw[0].private = fcn;
6983 akl->kw[0].parse = action_register_lua;
6984
6985 /* select the action registering point. */
6986 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6987 tcp_req_cont_keywords_register(akl);
6988 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6989 tcp_res_cont_keywords_register(akl);
6990 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6991 http_req_keywords_register(akl);
6992 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6993 http_res_keywords_register(akl);
6994 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006995 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006996 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6997 "are expected.", lua_tostring(L, -1)));
6998
6999 /* pop the environment string. */
7000 lua_pop(L, 1);
7001 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007002 return ACT_RET_PRS_OK;
7003}
7004
7005static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7006 struct act_rule *rule, char **err)
7007{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007008 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007009
7010 /* Memory for the rule. */
7011 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7012 if (!rule->arg.hlua_rule) {
7013 memprintf(err, "out of memory error");
7014 return ACT_RET_PRS_ERR;
7015 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007016
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007017 /* Reference the Lua function and store the reference. */
7018 rule->arg.hlua_rule->fcn = *fcn;
7019
7020 /* TODO: later accept arguments. */
7021 rule->arg.hlua_rule->args = NULL;
7022
7023 /* Add applet pointer in the rule. */
7024 rule->applet.obj_type = OBJ_TYPE_APPLET;
7025 rule->applet.name = fcn->name;
7026 rule->applet.init = hlua_applet_tcp_init;
7027 rule->applet.fct = hlua_applet_tcp_fct;
7028 rule->applet.release = hlua_applet_tcp_release;
7029 rule->applet.timeout = hlua_timeout_applet;
7030
7031 return 0;
7032}
7033
7034/* This function is an LUA binding used for registering
7035 * "sample-conv" functions. It expects a converter name used
7036 * in the haproxy configuration file, and an LUA function.
7037 */
7038__LJMP static int hlua_register_service(lua_State *L)
7039{
7040 struct action_kw_list *akl;
7041 const char *name;
7042 const char *env;
7043 int ref;
7044 int len;
7045 struct hlua_function *fcn;
7046
7047 MAY_LJMP(check_args(L, 3, "register_service"));
7048
7049 /* First argument : converter name. */
7050 name = MAY_LJMP(luaL_checkstring(L, 1));
7051
7052 /* Second argument : environment. */
7053 env = MAY_LJMP(luaL_checkstring(L, 2));
7054
7055 /* Third argument : lua function. */
7056 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7057
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007058 /* Allocate and fill the sample fetch keyword struct. */
7059 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7060 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007061 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007062 fcn = calloc(1, sizeof(*fcn));
7063 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007064 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007065
7066 /* Fill fcn. */
7067 len = strlen("<lua.>") + strlen(name) + 1;
7068 fcn->name = calloc(1, len);
7069 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007070 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007071 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7072 fcn->function_ref = ref;
7073
7074 /* List head */
7075 akl->list.n = akl->list.p = NULL;
7076
7077 /* converter keyword. */
7078 len = strlen("lua.") + strlen(name) + 1;
7079 akl->kw[0].kw = calloc(1, len);
7080 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007081 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007082
7083 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7084
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007085 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007086 if (strcmp(env, "tcp") == 0)
7087 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007088 else if (strcmp(env, "http") == 0)
7089 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007090 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007091 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007092 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007093
7094 akl->kw[0].match_pfx = 0;
7095 akl->kw[0].private = fcn;
7096
7097 /* End of array. */
7098 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7099
7100 /* Register this new converter */
7101 service_keywords_register(akl);
7102
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007103 return 0;
7104}
7105
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007106/* This function initialises Lua cli handler. It copies the
7107 * arguments in the Lua stack and create channel IO objects.
7108 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007109static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007110{
7111 struct hlua *hlua;
7112 struct hlua_function *fcn;
7113 int i;
7114 const char *error;
7115
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007116 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007117 appctx->ctx.hlua_cli.fcn = private;
7118
Willy Tarreaubafbe012017-11-24 17:34:44 +01007119 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007120 if (!hlua) {
7121 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007122 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007123 }
7124 HLUA_INIT(hlua);
7125 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007126
7127 /* Create task used by signal to wakeup applets.
7128 * We use the same wakeup fonction than the Lua applet_tcp and
7129 * applet_http. It is absolutely compatible.
7130 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007131 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007132 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007133 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007134 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007135 }
7136 appctx->ctx.hlua_cli.task->nice = 0;
7137 appctx->ctx.hlua_cli.task->context = appctx;
7138 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7139
7140 /* Initialises the Lua context */
7141 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
7142 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007143 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007144 }
7145
7146 /* The following Lua calls can fail. */
7147 if (!SET_SAFE_LJMP(hlua->T)) {
7148 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7149 error = lua_tostring(hlua->T, -1);
7150 else
7151 error = "critical error";
7152 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7153 goto error;
7154 }
7155
7156 /* Check stack available size. */
7157 if (!lua_checkstack(hlua->T, 2)) {
7158 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7159 goto error;
7160 }
7161
7162 /* Restore the function in the stack. */
7163 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7164
7165 /* Once the arguments parsed, the CLI is like an AppletTCP,
7166 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007167 */
7168 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7169 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7170 goto error;
7171 }
7172 hlua->nargs = 1;
7173
7174 /* push keywords in the stack. */
7175 for (i = 0; *args[i]; i++) {
7176 /* Check stack available size. */
7177 if (!lua_checkstack(hlua->T, 1)) {
7178 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7179 goto error;
7180 }
7181 lua_pushstring(hlua->T, args[i]);
7182 hlua->nargs++;
7183 }
7184
7185 /* We must initialize the execution timeouts. */
7186 hlua->max_time = hlua_timeout_session;
7187
7188 /* At this point the execution is safe. */
7189 RESET_SAFE_LJMP(hlua->T);
7190
7191 /* It's ok */
7192 return 0;
7193
7194 /* It's not ok. */
7195error:
7196 RESET_SAFE_LJMP(hlua->T);
7197 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007198 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007199 return 1;
7200}
7201
7202static int hlua_cli_io_handler_fct(struct appctx *appctx)
7203{
7204 struct hlua *hlua;
7205 struct stream_interface *si;
7206 struct hlua_function *fcn;
7207
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007208 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007209 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007210 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007211
7212 /* If the stream is disconnect or closed, ldo nothing. */
7213 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7214 return 1;
7215
7216 /* Execute the function. */
7217 switch (hlua_ctx_resume(hlua, 1)) {
7218
7219 /* finished. */
7220 case HLUA_E_OK:
7221 return 1;
7222
7223 /* yield. */
7224 case HLUA_E_AGAIN:
7225 /* We want write. */
7226 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01007227 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007228 /* Set the timeout. */
7229 if (hlua->wake_time != TICK_ETERNITY)
7230 task_schedule(hlua->task, hlua->wake_time);
7231 return 0;
7232
7233 /* finished with error. */
7234 case HLUA_E_ERRMSG:
7235 /* Display log. */
7236 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
7237 fcn->name, lua_tostring(hlua->T, -1));
7238 lua_pop(hlua->T, 1);
7239 return 1;
7240
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007241 case HLUA_E_ETMOUT:
7242 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
7243 fcn->name);
7244 return 1;
7245
7246 case HLUA_E_NOMEM:
7247 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
7248 fcn->name);
7249 return 1;
7250
7251 case HLUA_E_YIELD: /* unexpected */
7252 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
7253 fcn->name);
7254 return 1;
7255
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007256 case HLUA_E_ERR:
7257 /* Display log. */
7258 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
7259 fcn->name);
7260 return 1;
7261
7262 default:
7263 return 1;
7264 }
7265
7266 return 1;
7267}
7268
7269static void hlua_cli_io_release_fct(struct appctx *appctx)
7270{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007271 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007272 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007273}
7274
7275/* This function is an LUA binding used for registering
7276 * new keywords in the cli. It expects a list of keywords
7277 * which are the "path". It is limited to 5 keywords. A
7278 * description of the command, a function to be executed
7279 * for the parsing and a function for io handlers.
7280 */
7281__LJMP static int hlua_register_cli(lua_State *L)
7282{
7283 struct cli_kw_list *cli_kws;
7284 const char *message;
7285 int ref_io;
7286 int len;
7287 struct hlua_function *fcn;
7288 int index;
7289 int i;
7290
7291 MAY_LJMP(check_args(L, 3, "register_cli"));
7292
7293 /* First argument : an array of maximum 5 keywords. */
7294 if (!lua_istable(L, 1))
7295 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
7296
7297 /* Second argument : string with contextual message. */
7298 message = MAY_LJMP(luaL_checkstring(L, 2));
7299
7300 /* Third and fourth argument : lua function. */
7301 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
7302
7303 /* Allocate and fill the sample fetch keyword struct. */
7304 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
7305 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007306 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007307 fcn = calloc(1, sizeof(*fcn));
7308 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007309 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007310
7311 /* Fill path. */
7312 index = 0;
7313 lua_pushnil(L);
7314 while(lua_next(L, 1) != 0) {
7315 if (index >= 5)
7316 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
7317 if (lua_type(L, -1) != LUA_TSTRING)
7318 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
7319 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
7320 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007321 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007322 index++;
7323 lua_pop(L, 1);
7324 }
7325
7326 /* Copy help message. */
7327 cli_kws->kw[0].usage = strdup(message);
7328 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007329 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007330
7331 /* Fill fcn io handler. */
7332 len = strlen("<lua.cli>") + 1;
7333 for (i = 0; i < index; i++)
7334 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
7335 fcn->name = calloc(1, len);
7336 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007337 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007338 strncat((char *)fcn->name, "<lua.cli", len);
7339 for (i = 0; i < index; i++) {
7340 strncat((char *)fcn->name, ".", len);
7341 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
7342 }
7343 strncat((char *)fcn->name, ">", len);
7344 fcn->function_ref = ref_io;
7345
7346 /* Fill last entries. */
7347 cli_kws->kw[0].private = fcn;
7348 cli_kws->kw[0].parse = hlua_cli_parse_fct;
7349 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
7350 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
7351
7352 /* Register this new converter */
7353 cli_register_kw(cli_kws);
7354
7355 return 0;
7356}
7357
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007358static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7359 struct proxy *defpx, const char *file, int line,
7360 char **err, unsigned int *timeout)
7361{
7362 const char *error;
7363
7364 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
7365 if (error && *error != '\0') {
7366 memprintf(err, "%s: invalid timeout", args[0]);
7367 return -1;
7368 }
7369 return 0;
7370}
7371
7372static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7373 struct proxy *defpx, const char *file, int line,
7374 char **err)
7375{
7376 return hlua_read_timeout(args, section_type, curpx, defpx,
7377 file, line, err, &hlua_timeout_session);
7378}
7379
7380static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7381 struct proxy *defpx, const char *file, int line,
7382 char **err)
7383{
7384 return hlua_read_timeout(args, section_type, curpx, defpx,
7385 file, line, err, &hlua_timeout_task);
7386}
7387
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007388static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7389 struct proxy *defpx, const char *file, int line,
7390 char **err)
7391{
7392 return hlua_read_timeout(args, section_type, curpx, defpx,
7393 file, line, err, &hlua_timeout_applet);
7394}
7395
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007396static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7397 struct proxy *defpx, const char *file, int line,
7398 char **err)
7399{
7400 char *error;
7401
7402 hlua_nb_instruction = strtoll(args[1], &error, 10);
7403 if (*error != '\0') {
7404 memprintf(err, "%s: invalid number", args[0]);
7405 return -1;
7406 }
7407 return 0;
7408}
7409
Willy Tarreau32f61e22015-03-18 17:54:59 +01007410static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7411 struct proxy *defpx, const char *file, int line,
7412 char **err)
7413{
7414 char *error;
7415
7416 if (*(args[1]) == 0) {
7417 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7418 return -1;
7419 }
7420 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7421 if (*error != '\0') {
7422 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7423 return -1;
7424 }
7425 return 0;
7426}
7427
7428
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007429/* This function is called by the main configuration key "lua-load". It loads and
7430 * execute an lua file during the parsing of the HAProxy configuration file. It is
7431 * the main lua entry point.
7432 *
7433 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7434 * occured, otherwise it returns 0.
7435 *
7436 * In some error case, LUA set an error message in top of the stack. This function
7437 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007438 *
7439 * This function can fail with an abort() due to an Lua critical error.
7440 * We are in the configuration parsing process of HAProxy, this abort() is
7441 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007442 */
7443static int hlua_load(char **args, int section_type, struct proxy *curpx,
7444 struct proxy *defpx, const char *file, int line,
7445 char **err)
7446{
7447 int error;
7448
7449 /* Just load and compile the file. */
7450 error = luaL_loadfile(gL.T, args[1]);
7451 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007452 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007453 lua_pop(gL.T, 1);
7454 return -1;
7455 }
7456
7457 /* If no syntax error where detected, execute the code. */
7458 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7459 switch (error) {
7460 case LUA_OK:
7461 break;
7462 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007463 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007464 lua_pop(gL.T, 1);
7465 return -1;
7466 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007467 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007468 return -1;
7469 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007470 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007471 lua_pop(gL.T, 1);
7472 return -1;
7473 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007474 memprintf(err, "Lua garbage collector 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 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007478 memprintf(err, "Lua unknonwn 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 }
7482
7483 return 0;
7484}
7485
7486/* configuration keywords declaration */
7487static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007488 { CFG_GLOBAL, "lua-load", hlua_load },
7489 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7490 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007491 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007492 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007493 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007494 { 0, NULL, NULL },
7495}};
7496
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007497/* This function can fail with an abort() due to an Lua critical error.
7498 * We are in the initialisation process of HAProxy, this abort() is
7499 * tolerated.
7500 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007501int hlua_post_init()
7502{
7503 struct hlua_init_function *init;
7504 const char *msg;
7505 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007506 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007507
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007508 /* Call post initialisation function in safe environement. */
7509 if (!SET_SAFE_LJMP(gL.T)) {
7510 if (lua_type(gL.T, -1) == LUA_TSTRING)
7511 error = lua_tostring(gL.T, -1);
7512 else
7513 error = "critical error";
7514 fprintf(stderr, "Lua post-init: %s.\n", error);
7515 exit(1);
7516 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02007517
7518#if USE_OPENSSL
7519 /* Initialize SSL server. */
7520 if (socket_ssl.xprt->prepare_srv) {
7521 int saved_used_backed = global.ssl_used_backend;
7522 // don't affect maxconn automatic computation
7523 socket_ssl.xprt->prepare_srv(&socket_ssl);
7524 global.ssl_used_backend = saved_used_backed;
7525 }
7526#endif
7527
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007528 hlua_fcn_post_init(gL.T);
7529 RESET_SAFE_LJMP(gL.T);
7530
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007531 list_for_each_entry(init, &hlua_init_functions, l) {
7532 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7533 ret = hlua_ctx_resume(&gL, 0);
7534 switch (ret) {
7535 case HLUA_E_OK:
7536 lua_pop(gL.T, -1);
7537 return 1;
7538 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007539 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007540 return 0;
7541 case HLUA_E_ERRMSG:
7542 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01007543 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007544 return 0;
7545 case HLUA_E_ERR:
7546 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007547 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007548 return 0;
7549 }
7550 }
7551 return 1;
7552}
7553
Willy Tarreau32f61e22015-03-18 17:54:59 +01007554/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7555 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7556 * is the previously allocated size or the kind of object in case of a new
7557 * allocation. <nsize> is the requested new size.
7558 */
7559static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7560{
7561 struct hlua_mem_allocator *zone = ud;
7562
7563 if (nsize == 0) {
7564 /* it's a free */
7565 if (ptr)
7566 zone->allocated -= osize;
7567 free(ptr);
7568 return NULL;
7569 }
7570
7571 if (!ptr) {
7572 /* it's a new allocation */
7573 if (zone->limit && zone->allocated + nsize > zone->limit)
7574 return NULL;
7575
7576 ptr = malloc(nsize);
7577 if (ptr)
7578 zone->allocated += nsize;
7579 return ptr;
7580 }
7581
7582 /* it's a realloc */
7583 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7584 return NULL;
7585
7586 ptr = realloc(ptr, nsize);
7587 if (ptr)
7588 zone->allocated += nsize - osize;
7589 return ptr;
7590}
7591
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007592/* Ithis function can fail with an abort() due to an Lua critical error.
7593 * We are in the initialisation process of HAProxy, this abort() is
7594 * tolerated.
7595 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007596void hlua_init(void)
7597{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007598 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007599 int idx;
7600 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007601 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007602 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007603 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007604#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007605 struct srv_kw *kw;
7606 int tmp_error;
7607 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007608 char *args[] = { /* SSL client configuration. */
7609 "ssl",
7610 "verify",
7611 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007612 NULL
7613 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007614#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007615
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007616 HA_SPIN_INIT(&hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02007617
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007618 /* Initialise struct hlua and com signals pool */
Willy Tarreaubafbe012017-11-24 17:34:44 +01007619 pool_head_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007620
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007621 /* Register configuration keywords. */
7622 cfg_register_keywords(&cfg_kws);
7623
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007624 /* Init main lua stack. */
7625 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007626 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007627 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007628 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007629 hlua_sethlua(&gL);
7630 gL.Tref = LUA_REFNIL;
7631 gL.task = NULL;
7632
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007633 /* From this point, until the end of the initialisation fucntion,
7634 * the Lua function can fail with an abort. We are in the initialisation
7635 * process of HAProxy, this abort() is tolerated.
7636 */
7637
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007638 /* Initialise lua. */
7639 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007640
Thierry Fournier75933d42016-01-21 09:30:18 +01007641 /* Set safe environment for the initialisation. */
7642 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007643 if (lua_type(gL.T, -1) == LUA_TSTRING)
7644 error_msg = lua_tostring(gL.T, -1);
7645 else
7646 error_msg = "critical error";
7647 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007648 exit(1);
7649 }
7650
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007651 /*
7652 *
7653 * Create "core" object.
7654 *
7655 */
7656
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007657 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007658 lua_newtable(gL.T);
7659
7660 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007661 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007662 hlua_class_const_int(gL.T, log_levels[i], i);
7663
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007664 /* Register special functions. */
7665 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007666 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007667 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007668 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007669 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007670 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007671 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007672 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007673 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007674 hlua_class_function(gL.T, "sleep", hlua_sleep);
7675 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007676 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7677 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7678 hlua_class_function(gL.T, "set_map", hlua_set_map);
7679 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007680 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007681 hlua_class_function(gL.T, "log", hlua_log);
7682 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7683 hlua_class_function(gL.T, "Info", hlua_log_info);
7684 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7685 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007686 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007687 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007688
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007689 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007690
7691 /*
7692 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007693 * Register class Map
7694 *
7695 */
7696
7697 /* This table entry is the object "Map" base. */
7698 lua_newtable(gL.T);
7699
7700 /* register pattern types. */
7701 for (i=0; i<PAT_MATCH_NUM; i++)
7702 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007703 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007704 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
7705 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007706 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007707
7708 /* register constructor. */
7709 hlua_class_function(gL.T, "new", hlua_map_new);
7710
7711 /* Create and fill the metatable. */
7712 lua_newtable(gL.T);
7713
7714 /* Create and fille the __index entry. */
7715 lua_pushstring(gL.T, "__index");
7716 lua_newtable(gL.T);
7717
7718 /* Register . */
7719 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7720 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7721
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007722 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007723
Thierry Fournier45e78d72016-02-19 18:34:46 +01007724 /* Register previous table in the registry with reference and named entry.
7725 * The function hlua_register_metatable() pops the stack, so we
7726 * previously create a copy of the table.
7727 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007728 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007729 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007730
7731 /* Assign the metatable to the mai Map object. */
7732 lua_setmetatable(gL.T, -2);
7733
7734 /* Set a name to the table. */
7735 lua_setglobal(gL.T, "Map");
7736
7737 /*
7738 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007739 * Register class Channel
7740 *
7741 */
7742
7743 /* Create and fill the metatable. */
7744 lua_newtable(gL.T);
7745
7746 /* Create and fille the __index entry. */
7747 lua_pushstring(gL.T, "__index");
7748 lua_newtable(gL.T);
7749
7750 /* Register . */
7751 hlua_class_function(gL.T, "get", hlua_channel_get);
7752 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7753 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7754 hlua_class_function(gL.T, "set", hlua_channel_set);
7755 hlua_class_function(gL.T, "append", hlua_channel_append);
7756 hlua_class_function(gL.T, "send", hlua_channel_send);
7757 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7758 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7759 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007760 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007761
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007762 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007763
7764 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007765 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007766
7767 /*
7768 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007769 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007770 *
7771 */
7772
7773 /* Create and fill the metatable. */
7774 lua_newtable(gL.T);
7775
7776 /* Create and fille the __index entry. */
7777 lua_pushstring(gL.T, "__index");
7778 lua_newtable(gL.T);
7779
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007780 /* Browse existing fetches and create the associated
7781 * object method.
7782 */
7783 sf = NULL;
7784 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7785
7786 /* Dont register the keywork if the arguments check function are
7787 * not safe during the runtime.
7788 */
7789 if ((sf->val_args != NULL) &&
7790 (sf->val_args != val_payload_lv) &&
7791 (sf->val_args != val_hdr))
7792 continue;
7793
7794 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7795 * by an underscore.
7796 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007797 strncpy(trash.area, sf->kw, trash.size);
7798 trash.area[trash.size - 1] = '\0';
7799 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007800 if (*p == '.' || *p == '-' || *p == '+')
7801 *p = '_';
7802
7803 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007804 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007805 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007806 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007807 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007808 }
7809
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007810 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007811
7812 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007813 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007814
7815 /*
7816 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007817 * Register class Converters
7818 *
7819 */
7820
7821 /* Create and fill the metatable. */
7822 lua_newtable(gL.T);
7823
7824 /* Create and fill the __index entry. */
7825 lua_pushstring(gL.T, "__index");
7826 lua_newtable(gL.T);
7827
7828 /* Browse existing converters and create the associated
7829 * object method.
7830 */
7831 sc = NULL;
7832 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7833 /* Dont register the keywork if the arguments check function are
7834 * not safe during the runtime.
7835 */
7836 if (sc->val_args != NULL)
7837 continue;
7838
7839 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7840 * by an underscore.
7841 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007842 strncpy(trash.area, sc->kw, trash.size);
7843 trash.area[trash.size - 1] = '\0';
7844 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007845 if (*p == '.' || *p == '-' || *p == '+')
7846 *p = '_';
7847
7848 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007849 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007850 lua_pushlightuserdata(gL.T, sc);
7851 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007852 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007853 }
7854
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007855 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007856
7857 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007858 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007859
7860 /*
7861 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007862 * Register class HTTP
7863 *
7864 */
7865
7866 /* Create and fill the metatable. */
7867 lua_newtable(gL.T);
7868
7869 /* Create and fille the __index entry. */
7870 lua_pushstring(gL.T, "__index");
7871 lua_newtable(gL.T);
7872
7873 /* Register Lua functions. */
7874 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7875 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7876 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7877 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7878 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7879 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7880 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7881 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7882 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7883 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7884
7885 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7886 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7887 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7888 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7889 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7890 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007891 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007892
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007893 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007894
7895 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007896 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007897
7898 /*
7899 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007900 * Register class AppletTCP
7901 *
7902 */
7903
7904 /* Create and fill the metatable. */
7905 lua_newtable(gL.T);
7906
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007907 /* Create and fille the __index entry. */
7908 lua_pushstring(gL.T, "__index");
7909 lua_newtable(gL.T);
7910
7911 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007912 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7913 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7914 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7915 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7916 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007917 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7918 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7919 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007920
7921 lua_settable(gL.T, -3);
7922
7923 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007924 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007925
7926 /*
7927 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007928 * Register class AppletHTTP
7929 *
7930 */
7931
7932 /* Create and fill the metatable. */
7933 lua_newtable(gL.T);
7934
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007935 /* Create and fille the __index entry. */
7936 lua_pushstring(gL.T, "__index");
7937 lua_newtable(gL.T);
7938
7939 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007940 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7941 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007942 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7943 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7944 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007945 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7946 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7947 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7948 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7949 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7950 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7951
7952 lua_settable(gL.T, -3);
7953
7954 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007955 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007956
7957 /*
7958 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007959 * Register class TXN
7960 *
7961 */
7962
7963 /* Create and fill the metatable. */
7964 lua_newtable(gL.T);
7965
7966 /* Create and fille the __index entry. */
7967 lua_pushstring(gL.T, "__index");
7968 lua_newtable(gL.T);
7969
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007970 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04007971 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7972 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
7973 hlua_class_function(gL.T, "set_var", hlua_set_var);
7974 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
7975 hlua_class_function(gL.T, "get_var", hlua_get_var);
7976 hlua_class_function(gL.T, "done", hlua_txn_done);
7977 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
7978 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7979 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
7980 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
7981 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
7982 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7983 hlua_class_function(gL.T, "log", hlua_txn_log);
7984 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7985 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7986 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7987 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007988
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007989 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007990
7991 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007992 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007993
7994 /*
7995 *
7996 * Register class Socket
7997 *
7998 */
7999
8000 /* Create and fill the metatable. */
8001 lua_newtable(gL.T);
8002
8003 /* Create and fille the __index entry. */
8004 lua_pushstring(gL.T, "__index");
8005 lua_newtable(gL.T);
8006
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008007#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008008 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008009#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008010 hlua_class_function(gL.T, "connect", hlua_socket_connect);
8011 hlua_class_function(gL.T, "send", hlua_socket_send);
8012 hlua_class_function(gL.T, "receive", hlua_socket_receive);
8013 hlua_class_function(gL.T, "close", hlua_socket_close);
8014 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
8015 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8016 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8017 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8018
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008019 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008020
8021 /* Register the garbage collector entry. */
8022 lua_pushstring(gL.T, "__gc");
8023 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008024 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008025
8026 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008027 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008028
8029 /* Proxy and server configuration initialisation. */
8030 memset(&socket_proxy, 0, sizeof(socket_proxy));
8031 init_new_proxy(&socket_proxy);
8032 socket_proxy.parent = NULL;
8033 socket_proxy.last_change = now.tv_sec;
8034 socket_proxy.id = "LUA-SOCKET";
8035 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8036 socket_proxy.maxconn = 0;
8037 socket_proxy.accept = NULL;
8038 socket_proxy.options2 |= PR_O2_INDEPSTR;
8039 socket_proxy.srv = NULL;
8040 socket_proxy.conn_retries = 0;
8041 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8042
8043 /* Init TCP server: unchanged parameters */
8044 memset(&socket_tcp, 0, sizeof(socket_tcp));
8045 socket_tcp.next = NULL;
8046 socket_tcp.proxy = &socket_proxy;
8047 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8048 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008049 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008050 socket_tcp.priv_conns = NULL;
8051 socket_tcp.idle_conns = NULL;
8052 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008053 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008054 socket_tcp.last_change = 0;
8055 socket_tcp.id = "LUA-TCP-CONN";
8056 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8057 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8058 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
8059
8060 /* XXX: Copy default parameter from default server,
8061 * but the default server is not initialized.
8062 */
8063 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
8064 socket_tcp.minconn = socket_proxy.defsrv.minconn;
8065 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
8066 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
8067 socket_tcp.onerror = socket_proxy.defsrv.onerror;
8068 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8069 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
8070 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8071 socket_tcp.uweight = socket_proxy.defsrv.iweight;
8072 socket_tcp.iweight = socket_proxy.defsrv.iweight;
8073
8074 socket_tcp.check.status = HCHK_STATUS_INI;
8075 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
8076 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
8077 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
8078 socket_tcp.check.server = &socket_tcp;
8079
8080 socket_tcp.agent.status = HCHK_STATUS_INI;
8081 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
8082 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
8083 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
8084 socket_tcp.agent.server = &socket_tcp;
8085
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008086 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008087
8088#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008089 /* Init TCP server: unchanged parameters */
8090 memset(&socket_ssl, 0, sizeof(socket_ssl));
8091 socket_ssl.next = NULL;
8092 socket_ssl.proxy = &socket_proxy;
8093 socket_ssl.obj_type = OBJ_TYPE_SERVER;
8094 LIST_INIT(&socket_ssl.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008095 socket_ssl.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008096 socket_tcp.priv_conns = NULL;
8097 socket_tcp.idle_conns = NULL;
8098 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008099 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008100 socket_ssl.last_change = 0;
8101 socket_ssl.id = "LUA-SSL-CONN";
8102 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8103 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8104 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8105
8106 /* XXX: Copy default parameter from default server,
8107 * but the default server is not initialized.
8108 */
8109 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8110 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8111 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8112 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8113 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8114 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8115 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8116 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8117 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8118 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8119
8120 socket_ssl.check.status = HCHK_STATUS_INI;
8121 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8122 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8123 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8124 socket_ssl.check.server = &socket_ssl;
8125
8126 socket_ssl.agent.status = HCHK_STATUS_INI;
8127 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8128 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8129 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8130 socket_ssl.agent.server = &socket_ssl;
8131
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008132 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008133 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008134
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008135 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008136 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8137 /*
8138 *
8139 * If the keyword is not known, we can search in the registered
8140 * server keywords. This is usefull to configure special SSL
8141 * features like client certificates and ssl_verify.
8142 *
8143 */
8144 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8145 if (tmp_error != 0) {
8146 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8147 abort(); /* This must be never arrives because the command line
8148 not editable by the user. */
8149 }
8150 idx += kw->skip;
8151 }
8152 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008153#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008154
8155 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008156}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008157
8158__attribute__((constructor))
8159static void __hlua_init(void)
8160{
8161 char *ptr = NULL;
8162 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8163 hap_register_build_opts(ptr, 1);
8164}