blob: 6ad3c822d1f693338d3d11443d8b06eb574052b9 [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)) {
1617 si_applet_cant_get(si);
1618 si_applet_cant_put(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
1640 * to write, so we set the flag cant put
1641 */
1642 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
1643 si_applet_cant_put(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 */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002482 si_applet_cant_get(&s->si[0]);
2483 si_applet_cant_put(&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) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002945 si_applet_cant_put(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) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01003039 si_applet_cant_put(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) {
3665 si_applet_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) {
3720 si_applet_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);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003743 si_applet_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);
3767 si_applet_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) {
3836 si_applet_cant_put(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) {
4133 si_applet_cant_put(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) {
4150 si_applet_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) {
4219 si_applet_cant_put(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) {
4230 si_applet_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);
4265 si_applet_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) {
4331 si_applet_cant_put(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) {
4471 si_applet_cant_put(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 struct stream_interface *si = ctx->owner;
6333
6334 /* If the applet is wake up without any expected work, the sheduler
6335 * remove it from the run queue. This flag indicate that the applet
6336 * is waiting for write. If the buffer is full, the main processing
6337 * will send some data and after call the applet, otherwise it call
6338 * the applet ASAP.
6339 */
6340 si_applet_cant_put(si);
6341 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006342 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006343 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006344}
6345
6346static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6347{
6348 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006349 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006350 struct task *task;
6351 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006352 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006353
Willy Tarreaubafbe012017-11-24 17:34:44 +01006354 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006355 if (!hlua) {
6356 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6357 ctx->rule->arg.hlua_rule->fcn.name);
6358 return 0;
6359 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006360 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006361 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006362 ctx->ctx.hlua_apptcp.flags = 0;
6363
6364 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006365 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006366 if (!task) {
6367 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6368 ctx->rule->arg.hlua_rule->fcn.name);
6369 return 0;
6370 }
6371 task->nice = 0;
6372 task->context = ctx;
6373 task->process = hlua_applet_wakeup;
6374 ctx->ctx.hlua_apptcp.task = task;
6375
6376 /* In the execution wrappers linked with a stream, the
6377 * Lua context can be not initialized. This behavior
6378 * permits to save performances because a systematic
6379 * Lua initialization cause 5% performances loss.
6380 */
6381 if (!hlua_ctx_init(hlua, task)) {
6382 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6383 ctx->rule->arg.hlua_rule->fcn.name);
6384 return 0;
6385 }
6386
6387 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006388 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006389
6390 /* The following Lua calls can fail. */
6391 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006392 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6393 error = lua_tostring(hlua->T, -1);
6394 else
6395 error = "critical error";
6396 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6397 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006398 return 0;
6399 }
6400
6401 /* Check stack available size. */
6402 if (!lua_checkstack(hlua->T, 1)) {
6403 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6404 ctx->rule->arg.hlua_rule->fcn.name);
6405 RESET_SAFE_LJMP(hlua->T);
6406 return 0;
6407 }
6408
6409 /* Restore the function in the stack. */
6410 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6411
6412 /* Create and and push object stream in the stack. */
6413 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6414 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6415 ctx->rule->arg.hlua_rule->fcn.name);
6416 RESET_SAFE_LJMP(hlua->T);
6417 return 0;
6418 }
6419 hlua->nargs = 1;
6420
6421 /* push keywords in the stack. */
6422 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6423 if (!lua_checkstack(hlua->T, 1)) {
6424 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6425 ctx->rule->arg.hlua_rule->fcn.name);
6426 RESET_SAFE_LJMP(hlua->T);
6427 return 0;
6428 }
6429 lua_pushstring(hlua->T, *arg);
6430 hlua->nargs++;
6431 }
6432
6433 RESET_SAFE_LJMP(hlua->T);
6434
6435 /* Wakeup the applet ASAP. */
6436 si_applet_cant_get(si);
6437 si_applet_cant_put(si);
6438
6439 return 1;
6440}
6441
6442static void hlua_applet_tcp_fct(struct appctx *ctx)
6443{
6444 struct stream_interface *si = ctx->owner;
6445 struct stream *strm = si_strm(si);
6446 struct channel *res = si_ic(si);
6447 struct act_rule *rule = ctx->rule;
6448 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006449 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006450
6451 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02006452 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
6453 /* eat the whole request */
6454 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006455 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02006456 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006457
6458 /* If the stream is disconnect or closed, ldo nothing. */
6459 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6460 return;
6461
6462 /* Execute the function. */
6463 switch (hlua_ctx_resume(hlua, 1)) {
6464 /* finished. */
6465 case HLUA_E_OK:
6466 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6467
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006468 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02006469 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006470 res->flags |= CF_READ_NULL;
6471 si_shutr(si);
6472 return;
6473
6474 /* yield. */
6475 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006476 if (hlua->wake_time != TICK_ETERNITY)
6477 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006478 return;
6479
6480 /* finished with error. */
6481 case HLUA_E_ERRMSG:
6482 /* Display log. */
6483 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6484 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6485 lua_pop(hlua->T, 1);
6486 goto error;
6487
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006488 case HLUA_E_ETMOUT:
6489 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
6490 rule->arg.hlua_rule->fcn.name);
6491 goto error;
6492
6493 case HLUA_E_NOMEM:
6494 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
6495 rule->arg.hlua_rule->fcn.name);
6496 goto error;
6497
6498 case HLUA_E_YIELD: /* unexpected */
6499 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
6500 rule->arg.hlua_rule->fcn.name);
6501 goto error;
6502
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006503 case HLUA_E_ERR:
6504 /* Display log. */
6505 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6506 rule->arg.hlua_rule->fcn.name);
6507 goto error;
6508
6509 default:
6510 goto error;
6511 }
6512
6513error:
6514
6515 /* For all other cases, just close the stream. */
6516 si_shutw(si);
6517 si_shutr(si);
6518 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6519}
6520
6521static void hlua_applet_tcp_release(struct appctx *ctx)
6522{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006523 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006524 task_free(ctx->ctx.hlua_apptcp.task);
6525 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006526 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006527 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006528}
6529
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006530/* The function returns 1 if the initialisation is complete, 0 if
6531 * an errors occurs and -1 if more data are required for initializing
6532 * the applet.
6533 */
6534static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6535{
6536 struct stream_interface *si = ctx->owner;
6537 struct channel *req = si_oc(si);
6538 struct http_msg *msg;
6539 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006540 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006541 char **arg;
6542 struct hdr_ctx hdr;
6543 struct task *task;
6544 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006545 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006546
6547 /* Wait for a full HTTP request. */
6548 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6549 if (smp.flags & SMP_F_MAY_CHANGE)
6550 return -1;
6551 return 0;
6552 }
6553 txn = strm->txn;
6554 msg = &txn->req;
6555
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006556 /* We want two things in HTTP mode :
6557 * - enforce server-close mode if we were in keep-alive, so that the
6558 * applet is released after each response ;
6559 * - enable request body transfer to the applet in order to resync
6560 * with the response body.
6561 */
6562 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6563 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006564
Willy Tarreaubafbe012017-11-24 17:34:44 +01006565 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006566 if (!hlua) {
6567 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6568 ctx->rule->arg.hlua_rule->fcn.name);
6569 return 0;
6570 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006571 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006572 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006573 ctx->ctx.hlua_apphttp.left_bytes = -1;
6574 ctx->ctx.hlua_apphttp.flags = 0;
6575
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006576 if (txn->req.flags & HTTP_MSGF_VER_11)
6577 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6578
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006579 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006580 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006581 if (!task) {
6582 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6583 ctx->rule->arg.hlua_rule->fcn.name);
6584 return 0;
6585 }
6586 task->nice = 0;
6587 task->context = ctx;
6588 task->process = hlua_applet_wakeup;
6589 ctx->ctx.hlua_apphttp.task = task;
6590
6591 /* In the execution wrappers linked with a stream, the
6592 * Lua context can be not initialized. This behavior
6593 * permits to save performances because a systematic
6594 * Lua initialization cause 5% performances loss.
6595 */
6596 if (!hlua_ctx_init(hlua, task)) {
6597 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6598 ctx->rule->arg.hlua_rule->fcn.name);
6599 return 0;
6600 }
6601
6602 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006603 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006604
6605 /* The following Lua calls can fail. */
6606 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006607 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6608 error = lua_tostring(hlua->T, -1);
6609 else
6610 error = "critical error";
6611 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6612 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006613 return 0;
6614 }
6615
6616 /* Check stack available size. */
6617 if (!lua_checkstack(hlua->T, 1)) {
6618 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6619 ctx->rule->arg.hlua_rule->fcn.name);
6620 RESET_SAFE_LJMP(hlua->T);
6621 return 0;
6622 }
6623
6624 /* Restore the function in the stack. */
6625 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6626
6627 /* Create and and push object stream in the stack. */
6628 if (!hlua_applet_http_new(hlua->T, ctx)) {
6629 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6630 ctx->rule->arg.hlua_rule->fcn.name);
6631 RESET_SAFE_LJMP(hlua->T);
6632 return 0;
6633 }
6634 hlua->nargs = 1;
6635
6636 /* Look for a 100-continue expected. */
6637 if (msg->flags & HTTP_MSGF_VER_11) {
6638 hdr.idx = 0;
Willy Tarreaua79021a2018-06-15 18:07:57 +02006639 if (http_find_header2("Expect", 6, ci_head(req), &txn->hdr_idx, &hdr) &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006640 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6641 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6642 }
6643
6644 /* push keywords in the stack. */
6645 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6646 if (!lua_checkstack(hlua->T, 1)) {
6647 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6648 ctx->rule->arg.hlua_rule->fcn.name);
6649 RESET_SAFE_LJMP(hlua->T);
6650 return 0;
6651 }
6652 lua_pushstring(hlua->T, *arg);
6653 hlua->nargs++;
6654 }
6655
6656 RESET_SAFE_LJMP(hlua->T);
6657
6658 /* Wakeup the applet when data is ready for read. */
6659 si_applet_cant_get(si);
6660
6661 return 1;
6662}
6663
6664static void hlua_applet_http_fct(struct appctx *ctx)
6665{
6666 struct stream_interface *si = ctx->owner;
6667 struct stream *strm = si_strm(si);
6668 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006669 struct act_rule *rule = ctx->rule;
6670 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006671 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Willy Tarreau206ba832018-06-14 15:27:31 +02006672 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02006673 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02006674 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02006675 size_t len2;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006676 int ret;
6677
6678 /* If the stream is disconnect or closed, ldo nothing. */
6679 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6680 return;
6681
6682 /* Set the currently running flag. */
6683 if (!HLUA_IS_RUNNING(hlua) &&
6684 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6685
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006686 /* Wait for full HTTP analysys. */
6687 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6688 si_applet_cant_get(si);
6689 return;
6690 }
6691
6692 /* Store the max amount of bytes that we can read. */
6693 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6694
6695 /* We need to flush the request header. This left the body
6696 * for the Lua.
6697 */
6698
6699 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006700 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006701 if (ret == -1)
6702 return;
6703
6704 /* No data available, ask for more data. */
6705 if (ret == 1)
6706 len2 = 0;
6707 if (ret == 0)
6708 len1 = 0;
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02006709 if (len1 + len2 < strm->txn->req.eoh + strm->txn->req.eol) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006710 si_applet_cant_get(si);
6711 return;
6712 }
6713
6714 /* skip the requests bytes. */
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02006715 co_skip(si_oc(si), strm->txn->req.eoh + strm->txn->req.eol);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006716 }
6717
6718 /* Executes The applet if it is not done. */
6719 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6720
6721 /* Execute the function. */
6722 switch (hlua_ctx_resume(hlua, 1)) {
6723 /* finished. */
6724 case HLUA_E_OK:
6725 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6726 break;
6727
6728 /* yield. */
6729 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006730 if (hlua->wake_time != TICK_ETERNITY)
6731 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006732 return;
6733
6734 /* finished with error. */
6735 case HLUA_E_ERRMSG:
6736 /* Display log. */
6737 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6738 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6739 lua_pop(hlua->T, 1);
6740 goto error;
6741
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006742 case HLUA_E_ETMOUT:
6743 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
6744 rule->arg.hlua_rule->fcn.name);
6745 goto error;
6746
6747 case HLUA_E_NOMEM:
6748 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
6749 rule->arg.hlua_rule->fcn.name);
6750 goto error;
6751
6752 case HLUA_E_YIELD: /* unexpected */
6753 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
6754 rule->arg.hlua_rule->fcn.name);
6755 goto error;
6756
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006757 case HLUA_E_ERR:
6758 /* Display log. */
6759 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6760 rule->arg.hlua_rule->fcn.name);
6761 goto error;
6762
6763 default:
6764 goto error;
6765 }
6766 }
6767
6768 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6769
6770 /* We must send the final chunk. */
6771 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6772 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6773
6774 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006775 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006776
6777 /* critical error. */
6778 if (ret == -2 || ret == -3) {
6779 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6780 rule->arg.hlua_rule->fcn.name);
6781 goto error;
6782 }
6783
6784 /* no enough space error. */
6785 if (ret == -1) {
6786 si_applet_cant_put(si);
6787 return;
6788 }
6789
6790 /* set the last chunk sent. */
6791 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6792 }
6793
6794 /* close the connection. */
6795
Frédéric Lécaille83ed5d52018-07-18 14:25:26 +02006796 /* status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006797 strm->txn->status = ctx->ctx.hlua_apphttp.status;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006798
6799 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02006800 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006801 res->flags |= CF_READ_NULL;
6802 si_shutr(si);
6803
6804 return;
6805 }
6806
6807error:
6808
6809 /* If we are in HTTP mode, and we are not send any
6810 * data, return a 500 server error in best effort:
6811 * if there are no room avalaible in the buffer,
6812 * just close the connection.
6813 */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006814 ci_putblk(res, error_500, strlen(error_500));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006815 if (!(strm->flags & SF_ERR_MASK))
6816 strm->flags |= SF_ERR_RESOURCE;
6817 si_shutw(si);
6818 si_shutr(si);
6819 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6820}
6821
6822static void hlua_applet_http_release(struct appctx *ctx)
6823{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006824 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006825 task_free(ctx->ctx.hlua_apphttp.task);
6826 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006827 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006828 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006829}
6830
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006831/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6832 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006833 *
6834 * This function can fail with an abort() due to an Lua critical error.
6835 * We are in the configuration parsing process of HAProxy, this abort() is
6836 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006837 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006838static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6839 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006840{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006841 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006842 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006843
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006844 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006845 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006846 if (!rule->arg.hlua_rule) {
6847 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006848 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006849 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006850
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006851 /* Memory for arguments. */
6852 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6853 if (!rule->arg.hlua_rule->args) {
6854 memprintf(err, "out of memory error");
6855 return ACT_RET_PRS_ERR;
6856 }
6857
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006858 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006859 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006860
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006861 /* Expect some arguments */
6862 for (i = 0; i < fcn->nargs; i++) {
6863 if (*args[i+1] == '\0') {
6864 memprintf(err, "expect %d arguments", fcn->nargs);
6865 return ACT_RET_PRS_ERR;
6866 }
6867 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6868 if (!rule->arg.hlua_rule->args[i]) {
6869 memprintf(err, "out of memory error");
6870 return ACT_RET_PRS_ERR;
6871 }
6872 (*cur_arg)++;
6873 }
6874 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006875
Thierry FOURNIER42148732015-09-02 17:17:33 +02006876 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006877 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006878 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006879}
6880
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006881static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6882 struct act_rule *rule, char **err)
6883{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006884 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006885
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006886 /* HTTP applets are forbidden in tcp-request rules.
6887 * HTTP applet request requires everything initilized by
6888 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6889 * The applet will be immediately initilized, but its before
6890 * the call of this analyzer.
6891 */
6892 if (rule->from != ACT_F_HTTP_REQ) {
6893 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6894 return ACT_RET_PRS_ERR;
6895 }
6896
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006897 /* Memory for the rule. */
6898 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6899 if (!rule->arg.hlua_rule) {
6900 memprintf(err, "out of memory error");
6901 return ACT_RET_PRS_ERR;
6902 }
6903
6904 /* Reference the Lua function and store the reference. */
6905 rule->arg.hlua_rule->fcn = *fcn;
6906
6907 /* TODO: later accept arguments. */
6908 rule->arg.hlua_rule->args = NULL;
6909
6910 /* Add applet pointer in the rule. */
6911 rule->applet.obj_type = OBJ_TYPE_APPLET;
6912 rule->applet.name = fcn->name;
6913 rule->applet.init = hlua_applet_http_init;
6914 rule->applet.fct = hlua_applet_http_fct;
6915 rule->applet.release = hlua_applet_http_release;
6916 rule->applet.timeout = hlua_timeout_applet;
6917
6918 return ACT_RET_PRS_OK;
6919}
6920
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006921/* This function is an LUA binding used for registering
6922 * "sample-conv" functions. It expects a converter name used
6923 * in the haproxy configuration file, and an LUA function.
6924 */
6925__LJMP static int hlua_register_action(lua_State *L)
6926{
6927 struct action_kw_list *akl;
6928 const char *name;
6929 int ref;
6930 int len;
6931 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006932 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006933
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006934 /* Initialise the number of expected arguments at 0. */
6935 nargs = 0;
6936
6937 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6938 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006939
6940 /* First argument : converter name. */
6941 name = MAY_LJMP(luaL_checkstring(L, 1));
6942
6943 /* Second argument : environment. */
6944 if (lua_type(L, 2) != LUA_TTABLE)
6945 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6946
6947 /* Third argument : lua function. */
6948 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6949
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006950 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6951 if (lua_gettop(L) >= 4)
6952 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6953
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006954 /* browse the second argulent as an array. */
6955 lua_pushnil(L);
6956 while (lua_next(L, 2) != 0) {
6957 if (lua_type(L, -1) != LUA_TSTRING)
6958 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6959
6960 /* Check required environment. Only accepted "http" or "tcp". */
6961 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006962 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006963 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006964 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006965 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006966 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006967 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006968
6969 /* Fill fcn. */
6970 fcn->name = strdup(name);
6971 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006972 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006973 fcn->function_ref = ref;
6974
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006975 /* Set the expected number od arguments. */
6976 fcn->nargs = nargs;
6977
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006978 /* List head */
6979 akl->list.n = akl->list.p = NULL;
6980
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006981 /* action keyword. */
6982 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006983 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006984 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006985 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006986
6987 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6988
6989 akl->kw[0].match_pfx = 0;
6990 akl->kw[0].private = fcn;
6991 akl->kw[0].parse = action_register_lua;
6992
6993 /* select the action registering point. */
6994 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6995 tcp_req_cont_keywords_register(akl);
6996 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6997 tcp_res_cont_keywords_register(akl);
6998 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6999 http_req_keywords_register(akl);
7000 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
7001 http_res_keywords_register(akl);
7002 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007003 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007004 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
7005 "are expected.", lua_tostring(L, -1)));
7006
7007 /* pop the environment string. */
7008 lua_pop(L, 1);
7009 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007010 return ACT_RET_PRS_OK;
7011}
7012
7013static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7014 struct act_rule *rule, char **err)
7015{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007016 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007017
7018 /* Memory for the rule. */
7019 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7020 if (!rule->arg.hlua_rule) {
7021 memprintf(err, "out of memory error");
7022 return ACT_RET_PRS_ERR;
7023 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007024
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007025 /* Reference the Lua function and store the reference. */
7026 rule->arg.hlua_rule->fcn = *fcn;
7027
7028 /* TODO: later accept arguments. */
7029 rule->arg.hlua_rule->args = NULL;
7030
7031 /* Add applet pointer in the rule. */
7032 rule->applet.obj_type = OBJ_TYPE_APPLET;
7033 rule->applet.name = fcn->name;
7034 rule->applet.init = hlua_applet_tcp_init;
7035 rule->applet.fct = hlua_applet_tcp_fct;
7036 rule->applet.release = hlua_applet_tcp_release;
7037 rule->applet.timeout = hlua_timeout_applet;
7038
7039 return 0;
7040}
7041
7042/* This function is an LUA binding used for registering
7043 * "sample-conv" functions. It expects a converter name used
7044 * in the haproxy configuration file, and an LUA function.
7045 */
7046__LJMP static int hlua_register_service(lua_State *L)
7047{
7048 struct action_kw_list *akl;
7049 const char *name;
7050 const char *env;
7051 int ref;
7052 int len;
7053 struct hlua_function *fcn;
7054
7055 MAY_LJMP(check_args(L, 3, "register_service"));
7056
7057 /* First argument : converter name. */
7058 name = MAY_LJMP(luaL_checkstring(L, 1));
7059
7060 /* Second argument : environment. */
7061 env = MAY_LJMP(luaL_checkstring(L, 2));
7062
7063 /* Third argument : lua function. */
7064 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7065
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007066 /* Allocate and fill the sample fetch keyword struct. */
7067 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7068 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007069 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007070 fcn = calloc(1, sizeof(*fcn));
7071 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007072 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007073
7074 /* Fill fcn. */
7075 len = strlen("<lua.>") + strlen(name) + 1;
7076 fcn->name = calloc(1, len);
7077 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007078 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007079 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7080 fcn->function_ref = ref;
7081
7082 /* List head */
7083 akl->list.n = akl->list.p = NULL;
7084
7085 /* converter keyword. */
7086 len = strlen("lua.") + strlen(name) + 1;
7087 akl->kw[0].kw = calloc(1, len);
7088 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007089 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007090
7091 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7092
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007093 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007094 if (strcmp(env, "tcp") == 0)
7095 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007096 else if (strcmp(env, "http") == 0)
7097 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007098 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007099 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007100 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007101
7102 akl->kw[0].match_pfx = 0;
7103 akl->kw[0].private = fcn;
7104
7105 /* End of array. */
7106 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7107
7108 /* Register this new converter */
7109 service_keywords_register(akl);
7110
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007111 return 0;
7112}
7113
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007114/* This function initialises Lua cli handler. It copies the
7115 * arguments in the Lua stack and create channel IO objects.
7116 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007117static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007118{
7119 struct hlua *hlua;
7120 struct hlua_function *fcn;
7121 int i;
7122 const char *error;
7123
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007124 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007125 appctx->ctx.hlua_cli.fcn = private;
7126
Willy Tarreaubafbe012017-11-24 17:34:44 +01007127 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007128 if (!hlua) {
7129 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007130 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007131 }
7132 HLUA_INIT(hlua);
7133 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007134
7135 /* Create task used by signal to wakeup applets.
7136 * We use the same wakeup fonction than the Lua applet_tcp and
7137 * applet_http. It is absolutely compatible.
7138 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007139 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007140 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007141 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007142 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007143 }
7144 appctx->ctx.hlua_cli.task->nice = 0;
7145 appctx->ctx.hlua_cli.task->context = appctx;
7146 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7147
7148 /* Initialises the Lua context */
7149 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
7150 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007151 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007152 }
7153
7154 /* The following Lua calls can fail. */
7155 if (!SET_SAFE_LJMP(hlua->T)) {
7156 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7157 error = lua_tostring(hlua->T, -1);
7158 else
7159 error = "critical error";
7160 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7161 goto error;
7162 }
7163
7164 /* Check stack available size. */
7165 if (!lua_checkstack(hlua->T, 2)) {
7166 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7167 goto error;
7168 }
7169
7170 /* Restore the function in the stack. */
7171 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7172
7173 /* Once the arguments parsed, the CLI is like an AppletTCP,
7174 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007175 */
7176 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7177 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7178 goto error;
7179 }
7180 hlua->nargs = 1;
7181
7182 /* push keywords in the stack. */
7183 for (i = 0; *args[i]; i++) {
7184 /* Check stack available size. */
7185 if (!lua_checkstack(hlua->T, 1)) {
7186 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7187 goto error;
7188 }
7189 lua_pushstring(hlua->T, args[i]);
7190 hlua->nargs++;
7191 }
7192
7193 /* We must initialize the execution timeouts. */
7194 hlua->max_time = hlua_timeout_session;
7195
7196 /* At this point the execution is safe. */
7197 RESET_SAFE_LJMP(hlua->T);
7198
7199 /* It's ok */
7200 return 0;
7201
7202 /* It's not ok. */
7203error:
7204 RESET_SAFE_LJMP(hlua->T);
7205 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007206 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007207 return 1;
7208}
7209
7210static int hlua_cli_io_handler_fct(struct appctx *appctx)
7211{
7212 struct hlua *hlua;
7213 struct stream_interface *si;
7214 struct hlua_function *fcn;
7215
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007216 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007217 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007218 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007219
7220 /* If the stream is disconnect or closed, ldo nothing. */
7221 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7222 return 1;
7223
7224 /* Execute the function. */
7225 switch (hlua_ctx_resume(hlua, 1)) {
7226
7227 /* finished. */
7228 case HLUA_E_OK:
7229 return 1;
7230
7231 /* yield. */
7232 case HLUA_E_AGAIN:
7233 /* We want write. */
7234 if (HLUA_IS_WAKERESWR(hlua))
7235 si_applet_cant_put(si);
7236 /* Set the timeout. */
7237 if (hlua->wake_time != TICK_ETERNITY)
7238 task_schedule(hlua->task, hlua->wake_time);
7239 return 0;
7240
7241 /* finished with error. */
7242 case HLUA_E_ERRMSG:
7243 /* Display log. */
7244 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
7245 fcn->name, lua_tostring(hlua->T, -1));
7246 lua_pop(hlua->T, 1);
7247 return 1;
7248
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007249 case HLUA_E_ETMOUT:
7250 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
7251 fcn->name);
7252 return 1;
7253
7254 case HLUA_E_NOMEM:
7255 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
7256 fcn->name);
7257 return 1;
7258
7259 case HLUA_E_YIELD: /* unexpected */
7260 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
7261 fcn->name);
7262 return 1;
7263
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007264 case HLUA_E_ERR:
7265 /* Display log. */
7266 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
7267 fcn->name);
7268 return 1;
7269
7270 default:
7271 return 1;
7272 }
7273
7274 return 1;
7275}
7276
7277static void hlua_cli_io_release_fct(struct appctx *appctx)
7278{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007279 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007280 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007281}
7282
7283/* This function is an LUA binding used for registering
7284 * new keywords in the cli. It expects a list of keywords
7285 * which are the "path". It is limited to 5 keywords. A
7286 * description of the command, a function to be executed
7287 * for the parsing and a function for io handlers.
7288 */
7289__LJMP static int hlua_register_cli(lua_State *L)
7290{
7291 struct cli_kw_list *cli_kws;
7292 const char *message;
7293 int ref_io;
7294 int len;
7295 struct hlua_function *fcn;
7296 int index;
7297 int i;
7298
7299 MAY_LJMP(check_args(L, 3, "register_cli"));
7300
7301 /* First argument : an array of maximum 5 keywords. */
7302 if (!lua_istable(L, 1))
7303 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
7304
7305 /* Second argument : string with contextual message. */
7306 message = MAY_LJMP(luaL_checkstring(L, 2));
7307
7308 /* Third and fourth argument : lua function. */
7309 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
7310
7311 /* Allocate and fill the sample fetch keyword struct. */
7312 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
7313 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007314 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007315 fcn = calloc(1, sizeof(*fcn));
7316 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007317 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007318
7319 /* Fill path. */
7320 index = 0;
7321 lua_pushnil(L);
7322 while(lua_next(L, 1) != 0) {
7323 if (index >= 5)
7324 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
7325 if (lua_type(L, -1) != LUA_TSTRING)
7326 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
7327 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
7328 if (!cli_kws->kw[0].str_kw[index])
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 index++;
7331 lua_pop(L, 1);
7332 }
7333
7334 /* Copy help message. */
7335 cli_kws->kw[0].usage = strdup(message);
7336 if (!cli_kws->kw[0].usage)
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
7339 /* Fill fcn io handler. */
7340 len = strlen("<lua.cli>") + 1;
7341 for (i = 0; i < index; i++)
7342 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
7343 fcn->name = calloc(1, len);
7344 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007345 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007346 strncat((char *)fcn->name, "<lua.cli", len);
7347 for (i = 0; i < index; i++) {
7348 strncat((char *)fcn->name, ".", len);
7349 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
7350 }
7351 strncat((char *)fcn->name, ">", len);
7352 fcn->function_ref = ref_io;
7353
7354 /* Fill last entries. */
7355 cli_kws->kw[0].private = fcn;
7356 cli_kws->kw[0].parse = hlua_cli_parse_fct;
7357 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
7358 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
7359
7360 /* Register this new converter */
7361 cli_register_kw(cli_kws);
7362
7363 return 0;
7364}
7365
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007366static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7367 struct proxy *defpx, const char *file, int line,
7368 char **err, unsigned int *timeout)
7369{
7370 const char *error;
7371
7372 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
7373 if (error && *error != '\0') {
7374 memprintf(err, "%s: invalid timeout", args[0]);
7375 return -1;
7376 }
7377 return 0;
7378}
7379
7380static int hlua_session_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_session);
7386}
7387
7388static int hlua_task_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_task);
7394}
7395
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007396static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7397 struct proxy *defpx, const char *file, int line,
7398 char **err)
7399{
7400 return hlua_read_timeout(args, section_type, curpx, defpx,
7401 file, line, err, &hlua_timeout_applet);
7402}
7403
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007404static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7405 struct proxy *defpx, const char *file, int line,
7406 char **err)
7407{
7408 char *error;
7409
7410 hlua_nb_instruction = strtoll(args[1], &error, 10);
7411 if (*error != '\0') {
7412 memprintf(err, "%s: invalid number", args[0]);
7413 return -1;
7414 }
7415 return 0;
7416}
7417
Willy Tarreau32f61e22015-03-18 17:54:59 +01007418static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7419 struct proxy *defpx, const char *file, int line,
7420 char **err)
7421{
7422 char *error;
7423
7424 if (*(args[1]) == 0) {
7425 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7426 return -1;
7427 }
7428 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7429 if (*error != '\0') {
7430 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7431 return -1;
7432 }
7433 return 0;
7434}
7435
7436
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007437/* This function is called by the main configuration key "lua-load". It loads and
7438 * execute an lua file during the parsing of the HAProxy configuration file. It is
7439 * the main lua entry point.
7440 *
7441 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7442 * occured, otherwise it returns 0.
7443 *
7444 * In some error case, LUA set an error message in top of the stack. This function
7445 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007446 *
7447 * This function can fail with an abort() due to an Lua critical error.
7448 * We are in the configuration parsing process of HAProxy, this abort() is
7449 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007450 */
7451static int hlua_load(char **args, int section_type, struct proxy *curpx,
7452 struct proxy *defpx, const char *file, int line,
7453 char **err)
7454{
7455 int error;
7456
7457 /* Just load and compile the file. */
7458 error = luaL_loadfile(gL.T, args[1]);
7459 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007460 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007461 lua_pop(gL.T, 1);
7462 return -1;
7463 }
7464
7465 /* If no syntax error where detected, execute the code. */
7466 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7467 switch (error) {
7468 case LUA_OK:
7469 break;
7470 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007471 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007472 lua_pop(gL.T, 1);
7473 return -1;
7474 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007475 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007476 return -1;
7477 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007478 memprintf(err, "Lua message handler 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 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007482 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007483 lua_pop(gL.T, 1);
7484 return -1;
7485 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007486 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007487 lua_pop(gL.T, 1);
7488 return -1;
7489 }
7490
7491 return 0;
7492}
7493
7494/* configuration keywords declaration */
7495static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007496 { CFG_GLOBAL, "lua-load", hlua_load },
7497 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7498 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007499 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007500 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007501 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007502 { 0, NULL, NULL },
7503}};
7504
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007505/* This function can fail with an abort() due to an Lua critical error.
7506 * We are in the initialisation process of HAProxy, this abort() is
7507 * tolerated.
7508 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007509int hlua_post_init()
7510{
7511 struct hlua_init_function *init;
7512 const char *msg;
7513 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007514 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007515
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007516 /* Call post initialisation function in safe environement. */
7517 if (!SET_SAFE_LJMP(gL.T)) {
7518 if (lua_type(gL.T, -1) == LUA_TSTRING)
7519 error = lua_tostring(gL.T, -1);
7520 else
7521 error = "critical error";
7522 fprintf(stderr, "Lua post-init: %s.\n", error);
7523 exit(1);
7524 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02007525
7526#if USE_OPENSSL
7527 /* Initialize SSL server. */
7528 if (socket_ssl.xprt->prepare_srv) {
7529 int saved_used_backed = global.ssl_used_backend;
7530 // don't affect maxconn automatic computation
7531 socket_ssl.xprt->prepare_srv(&socket_ssl);
7532 global.ssl_used_backend = saved_used_backed;
7533 }
7534#endif
7535
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007536 hlua_fcn_post_init(gL.T);
7537 RESET_SAFE_LJMP(gL.T);
7538
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007539 list_for_each_entry(init, &hlua_init_functions, l) {
7540 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7541 ret = hlua_ctx_resume(&gL, 0);
7542 switch (ret) {
7543 case HLUA_E_OK:
7544 lua_pop(gL.T, -1);
7545 return 1;
7546 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007547 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007548 return 0;
7549 case HLUA_E_ERRMSG:
7550 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01007551 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007552 return 0;
7553 case HLUA_E_ERR:
7554 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007555 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007556 return 0;
7557 }
7558 }
7559 return 1;
7560}
7561
Willy Tarreau32f61e22015-03-18 17:54:59 +01007562/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7563 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7564 * is the previously allocated size or the kind of object in case of a new
7565 * allocation. <nsize> is the requested new size.
7566 */
7567static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7568{
7569 struct hlua_mem_allocator *zone = ud;
7570
7571 if (nsize == 0) {
7572 /* it's a free */
7573 if (ptr)
7574 zone->allocated -= osize;
7575 free(ptr);
7576 return NULL;
7577 }
7578
7579 if (!ptr) {
7580 /* it's a new allocation */
7581 if (zone->limit && zone->allocated + nsize > zone->limit)
7582 return NULL;
7583
7584 ptr = malloc(nsize);
7585 if (ptr)
7586 zone->allocated += nsize;
7587 return ptr;
7588 }
7589
7590 /* it's a realloc */
7591 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7592 return NULL;
7593
7594 ptr = realloc(ptr, nsize);
7595 if (ptr)
7596 zone->allocated += nsize - osize;
7597 return ptr;
7598}
7599
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007600/* Ithis function can fail with an abort() due to an Lua critical error.
7601 * We are in the initialisation process of HAProxy, this abort() is
7602 * tolerated.
7603 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007604void hlua_init(void)
7605{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007606 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007607 int idx;
7608 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007609 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007610 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007611 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007612#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007613 struct srv_kw *kw;
7614 int tmp_error;
7615 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007616 char *args[] = { /* SSL client configuration. */
7617 "ssl",
7618 "verify",
7619 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007620 NULL
7621 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007622#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007623
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007624 HA_SPIN_INIT(&hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02007625
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007626 /* Initialise struct hlua and com signals pool */
Willy Tarreaubafbe012017-11-24 17:34:44 +01007627 pool_head_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007628
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007629 /* Register configuration keywords. */
7630 cfg_register_keywords(&cfg_kws);
7631
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007632 /* Init main lua stack. */
7633 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007634 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007635 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007636 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007637 hlua_sethlua(&gL);
7638 gL.Tref = LUA_REFNIL;
7639 gL.task = NULL;
7640
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007641 /* From this point, until the end of the initialisation fucntion,
7642 * the Lua function can fail with an abort. We are in the initialisation
7643 * process of HAProxy, this abort() is tolerated.
7644 */
7645
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007646 /* Initialise lua. */
7647 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007648
Thierry Fournier75933d42016-01-21 09:30:18 +01007649 /* Set safe environment for the initialisation. */
7650 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007651 if (lua_type(gL.T, -1) == LUA_TSTRING)
7652 error_msg = lua_tostring(gL.T, -1);
7653 else
7654 error_msg = "critical error";
7655 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007656 exit(1);
7657 }
7658
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007659 /*
7660 *
7661 * Create "core" object.
7662 *
7663 */
7664
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007665 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007666 lua_newtable(gL.T);
7667
7668 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007669 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007670 hlua_class_const_int(gL.T, log_levels[i], i);
7671
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007672 /* Register special functions. */
7673 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007674 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007675 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007676 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007677 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007678 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007679 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007680 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007681 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007682 hlua_class_function(gL.T, "sleep", hlua_sleep);
7683 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007684 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7685 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7686 hlua_class_function(gL.T, "set_map", hlua_set_map);
7687 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007688 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007689 hlua_class_function(gL.T, "log", hlua_log);
7690 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7691 hlua_class_function(gL.T, "Info", hlua_log_info);
7692 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7693 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007694 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007695 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007696
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007697 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007698
7699 /*
7700 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007701 * Register class Map
7702 *
7703 */
7704
7705 /* This table entry is the object "Map" base. */
7706 lua_newtable(gL.T);
7707
7708 /* register pattern types. */
7709 for (i=0; i<PAT_MATCH_NUM; i++)
7710 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007711 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007712 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
7713 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007714 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007715
7716 /* register constructor. */
7717 hlua_class_function(gL.T, "new", hlua_map_new);
7718
7719 /* Create and fill the metatable. */
7720 lua_newtable(gL.T);
7721
7722 /* Create and fille the __index entry. */
7723 lua_pushstring(gL.T, "__index");
7724 lua_newtable(gL.T);
7725
7726 /* Register . */
7727 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7728 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7729
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007730 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007731
Thierry Fournier45e78d72016-02-19 18:34:46 +01007732 /* Register previous table in the registry with reference and named entry.
7733 * The function hlua_register_metatable() pops the stack, so we
7734 * previously create a copy of the table.
7735 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007736 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007737 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007738
7739 /* Assign the metatable to the mai Map object. */
7740 lua_setmetatable(gL.T, -2);
7741
7742 /* Set a name to the table. */
7743 lua_setglobal(gL.T, "Map");
7744
7745 /*
7746 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007747 * Register class Channel
7748 *
7749 */
7750
7751 /* Create and fill the metatable. */
7752 lua_newtable(gL.T);
7753
7754 /* Create and fille the __index entry. */
7755 lua_pushstring(gL.T, "__index");
7756 lua_newtable(gL.T);
7757
7758 /* Register . */
7759 hlua_class_function(gL.T, "get", hlua_channel_get);
7760 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7761 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7762 hlua_class_function(gL.T, "set", hlua_channel_set);
7763 hlua_class_function(gL.T, "append", hlua_channel_append);
7764 hlua_class_function(gL.T, "send", hlua_channel_send);
7765 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7766 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7767 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007768 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007769
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007770 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007771
7772 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007773 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007774
7775 /*
7776 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007777 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007778 *
7779 */
7780
7781 /* Create and fill the metatable. */
7782 lua_newtable(gL.T);
7783
7784 /* Create and fille the __index entry. */
7785 lua_pushstring(gL.T, "__index");
7786 lua_newtable(gL.T);
7787
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007788 /* Browse existing fetches and create the associated
7789 * object method.
7790 */
7791 sf = NULL;
7792 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7793
7794 /* Dont register the keywork if the arguments check function are
7795 * not safe during the runtime.
7796 */
7797 if ((sf->val_args != NULL) &&
7798 (sf->val_args != val_payload_lv) &&
7799 (sf->val_args != val_hdr))
7800 continue;
7801
7802 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7803 * by an underscore.
7804 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007805 strncpy(trash.area, sf->kw, trash.size);
7806 trash.area[trash.size - 1] = '\0';
7807 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007808 if (*p == '.' || *p == '-' || *p == '+')
7809 *p = '_';
7810
7811 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007812 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007813 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007814 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007815 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007816 }
7817
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007818 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007819
7820 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007821 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007822
7823 /*
7824 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007825 * Register class Converters
7826 *
7827 */
7828
7829 /* Create and fill the metatable. */
7830 lua_newtable(gL.T);
7831
7832 /* Create and fill the __index entry. */
7833 lua_pushstring(gL.T, "__index");
7834 lua_newtable(gL.T);
7835
7836 /* Browse existing converters and create the associated
7837 * object method.
7838 */
7839 sc = NULL;
7840 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7841 /* Dont register the keywork if the arguments check function are
7842 * not safe during the runtime.
7843 */
7844 if (sc->val_args != NULL)
7845 continue;
7846
7847 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7848 * by an underscore.
7849 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007850 strncpy(trash.area, sc->kw, trash.size);
7851 trash.area[trash.size - 1] = '\0';
7852 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007853 if (*p == '.' || *p == '-' || *p == '+')
7854 *p = '_';
7855
7856 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007857 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007858 lua_pushlightuserdata(gL.T, sc);
7859 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007860 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007861 }
7862
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007863 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007864
7865 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007866 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007867
7868 /*
7869 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007870 * Register class HTTP
7871 *
7872 */
7873
7874 /* Create and fill the metatable. */
7875 lua_newtable(gL.T);
7876
7877 /* Create and fille the __index entry. */
7878 lua_pushstring(gL.T, "__index");
7879 lua_newtable(gL.T);
7880
7881 /* Register Lua functions. */
7882 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7883 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7884 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7885 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7886 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7887 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7888 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7889 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7890 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7891 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7892
7893 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7894 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7895 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7896 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7897 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7898 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007899 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007900
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007901 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007902
7903 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007904 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007905
7906 /*
7907 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007908 * Register class AppletTCP
7909 *
7910 */
7911
7912 /* Create and fill the metatable. */
7913 lua_newtable(gL.T);
7914
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007915 /* Create and fille the __index entry. */
7916 lua_pushstring(gL.T, "__index");
7917 lua_newtable(gL.T);
7918
7919 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007920 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7921 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7922 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7923 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7924 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007925 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7926 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7927 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007928
7929 lua_settable(gL.T, -3);
7930
7931 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007932 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007933
7934 /*
7935 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007936 * Register class AppletHTTP
7937 *
7938 */
7939
7940 /* Create and fill the metatable. */
7941 lua_newtable(gL.T);
7942
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007943 /* Create and fille the __index entry. */
7944 lua_pushstring(gL.T, "__index");
7945 lua_newtable(gL.T);
7946
7947 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007948 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7949 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007950 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7951 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7952 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007953 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7954 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7955 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7956 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7957 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7958 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7959
7960 lua_settable(gL.T, -3);
7961
7962 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007963 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007964
7965 /*
7966 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007967 * Register class TXN
7968 *
7969 */
7970
7971 /* Create and fill the metatable. */
7972 lua_newtable(gL.T);
7973
7974 /* Create and fille the __index entry. */
7975 lua_pushstring(gL.T, "__index");
7976 lua_newtable(gL.T);
7977
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007978 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04007979 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7980 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
7981 hlua_class_function(gL.T, "set_var", hlua_set_var);
7982 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
7983 hlua_class_function(gL.T, "get_var", hlua_get_var);
7984 hlua_class_function(gL.T, "done", hlua_txn_done);
7985 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
7986 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7987 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
7988 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
7989 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
7990 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7991 hlua_class_function(gL.T, "log", hlua_txn_log);
7992 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7993 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7994 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7995 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007996
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007997 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007998
7999 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008000 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008001
8002 /*
8003 *
8004 * Register class Socket
8005 *
8006 */
8007
8008 /* Create and fill the metatable. */
8009 lua_newtable(gL.T);
8010
8011 /* Create and fille the __index entry. */
8012 lua_pushstring(gL.T, "__index");
8013 lua_newtable(gL.T);
8014
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008015#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008016 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008017#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008018 hlua_class_function(gL.T, "connect", hlua_socket_connect);
8019 hlua_class_function(gL.T, "send", hlua_socket_send);
8020 hlua_class_function(gL.T, "receive", hlua_socket_receive);
8021 hlua_class_function(gL.T, "close", hlua_socket_close);
8022 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
8023 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8024 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8025 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8026
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008027 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008028
8029 /* Register the garbage collector entry. */
8030 lua_pushstring(gL.T, "__gc");
8031 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008032 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008033
8034 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008035 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008036
8037 /* Proxy and server configuration initialisation. */
8038 memset(&socket_proxy, 0, sizeof(socket_proxy));
8039 init_new_proxy(&socket_proxy);
8040 socket_proxy.parent = NULL;
8041 socket_proxy.last_change = now.tv_sec;
8042 socket_proxy.id = "LUA-SOCKET";
8043 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8044 socket_proxy.maxconn = 0;
8045 socket_proxy.accept = NULL;
8046 socket_proxy.options2 |= PR_O2_INDEPSTR;
8047 socket_proxy.srv = NULL;
8048 socket_proxy.conn_retries = 0;
8049 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8050
8051 /* Init TCP server: unchanged parameters */
8052 memset(&socket_tcp, 0, sizeof(socket_tcp));
8053 socket_tcp.next = NULL;
8054 socket_tcp.proxy = &socket_proxy;
8055 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8056 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008057 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008058 socket_tcp.priv_conns = NULL;
8059 socket_tcp.idle_conns = NULL;
8060 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008061 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008062 socket_tcp.last_change = 0;
8063 socket_tcp.id = "LUA-TCP-CONN";
8064 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8065 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8066 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
8067
8068 /* XXX: Copy default parameter from default server,
8069 * but the default server is not initialized.
8070 */
8071 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
8072 socket_tcp.minconn = socket_proxy.defsrv.minconn;
8073 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
8074 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
8075 socket_tcp.onerror = socket_proxy.defsrv.onerror;
8076 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8077 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
8078 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8079 socket_tcp.uweight = socket_proxy.defsrv.iweight;
8080 socket_tcp.iweight = socket_proxy.defsrv.iweight;
8081
8082 socket_tcp.check.status = HCHK_STATUS_INI;
8083 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
8084 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
8085 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
8086 socket_tcp.check.server = &socket_tcp;
8087
8088 socket_tcp.agent.status = HCHK_STATUS_INI;
8089 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
8090 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
8091 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
8092 socket_tcp.agent.server = &socket_tcp;
8093
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008094 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008095
8096#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008097 /* Init TCP server: unchanged parameters */
8098 memset(&socket_ssl, 0, sizeof(socket_ssl));
8099 socket_ssl.next = NULL;
8100 socket_ssl.proxy = &socket_proxy;
8101 socket_ssl.obj_type = OBJ_TYPE_SERVER;
8102 LIST_INIT(&socket_ssl.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008103 socket_ssl.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008104 socket_tcp.priv_conns = NULL;
8105 socket_tcp.idle_conns = NULL;
8106 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008107 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008108 socket_ssl.last_change = 0;
8109 socket_ssl.id = "LUA-SSL-CONN";
8110 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8111 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8112 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8113
8114 /* XXX: Copy default parameter from default server,
8115 * but the default server is not initialized.
8116 */
8117 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8118 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8119 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8120 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8121 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8122 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8123 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8124 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8125 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8126 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8127
8128 socket_ssl.check.status = HCHK_STATUS_INI;
8129 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8130 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8131 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8132 socket_ssl.check.server = &socket_ssl;
8133
8134 socket_ssl.agent.status = HCHK_STATUS_INI;
8135 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8136 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8137 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8138 socket_ssl.agent.server = &socket_ssl;
8139
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008140 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008141 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008142
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008143 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008144 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8145 /*
8146 *
8147 * If the keyword is not known, we can search in the registered
8148 * server keywords. This is usefull to configure special SSL
8149 * features like client certificates and ssl_verify.
8150 *
8151 */
8152 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8153 if (tmp_error != 0) {
8154 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8155 abort(); /* This must be never arrives because the command line
8156 not editable by the user. */
8157 }
8158 idx += kw->skip;
8159 }
8160 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008161#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008162
8163 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008164}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008165
8166__attribute__((constructor))
8167static void __hlua_init(void)
8168{
8169 char *ptr = NULL;
8170 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8171 hap_register_build_opts(ptr, 1);
8172}