blob: 1667b4ab2f97f28f29d87231ed42529bf0b793e6 [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 FOURNIER61ba0e22017-07-12 11:41:21 +020029#include <common/hathreads.h>
Willy Tarreau0108d902018-11-25 19:14:37 +010030#include <common/initcall.h>
31#include <common/xref.h>
Christopher Faulet724a12c2018-12-13 22:12:15 +010032#include <common/h1.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010033
William Lallemand9ed62032016-11-21 17:49:11 +010034#include <types/cli.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010035#include <types/hlua.h>
36#include <types/proxy.h>
William Lallemand9ed62032016-11-21 17:49:11 +010037#include <types/stats.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010038
Thierry FOURNIER55da1652015-01-23 11:36:30 +010039#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020040#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010041#include <proto/channel.h>
William Lallemand9ed62032016-11-21 17:49:11 +010042#include <proto/cli.h>
Willy Tarreaua71f6422016-11-16 17:00:14 +010043#include <proto/connection.h>
William Lallemand9ed62032016-11-21 17:49:11 +010044#include <proto/stats.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010045#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010046#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010047#include <proto/hlua_fcn.h>
Willy Tarreau79e57332018-10-02 16:01:16 +020048#include <proto/http_fetch.h>
Christopher Faulet724a12c2018-12-13 22:12:15 +010049#include <proto/http_htx.h>
Willy Tarreau61c112a2018-10-02 16:43:32 +020050#include <proto/http_rules.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020051#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010052#include <proto/obj_type.h>
Patrick Hemmer268a7072018-05-11 12:52:31 -040053#include <proto/queue.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010054#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010055#include <proto/payload.h>
56#include <proto/proto_http.h>
57#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010058#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020059#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020060#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010061#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010062#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010063#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020064#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010065
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010066/* Lua uses longjmp to perform yield or throwing errors. This
67 * macro is used only for identifying the function that can
68 * not return because a longjmp is executed.
69 * __LJMP marks a prototype of hlua file that can use longjmp.
70 * WILL_LJMP() marks an lua function that will use longjmp.
71 * MAY_LJMP() marks an lua function that may use longjmp.
72 */
73#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020074#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010075#define MAY_LJMP(func) func
76
Thierry FOURNIERbabae282015-09-17 11:36:37 +020077/* This couple of function executes securely some Lua calls outside of
78 * the lua runtime environment. Each Lua call can return a longjmp
79 * if it encounter a memory error.
80 *
81 * Lua documentation extract:
82 *
83 * If an error happens outside any protected environment, Lua calls
84 * a panic function (see lua_atpanic) and then calls abort, thus
85 * exiting the host application. Your panic function can avoid this
86 * exit by never returning (e.g., doing a long jump to your own
87 * recovery point outside Lua).
88 *
89 * The panic function runs as if it were a message handler (see
90 * §2.3); in particular, the error message is at the top of the
91 * stack. However, there is no guarantee about stack space. To push
92 * anything on the stack, the panic function must first check the
93 * available space (see §4.2).
94 *
95 * We must check all the Lua entry point. This includes:
96 * - The include/proto/hlua.h exported functions
97 * - the task wrapper function
98 * - The action wrapper function
99 * - The converters wrapper function
100 * - The sample-fetch wrapper functions
101 *
102 * It is tolerated that the initilisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800103 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200104 *
105 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
106 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
107 * because they must be exists in the program stack when the longjmp
108 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200109 *
110 * Note that the Lua processing is not really thread safe. It provides
111 * heavy system which consists to add our own lock function in the Lua
112 * code and recompile the library. This system will probably not accepted
113 * by maintainers of various distribs.
114 *
115 * Our main excution point of the Lua is the function lua_resume(). A
116 * quick looking on the Lua sources displays a lua_lock() a the start
117 * of function and a lua_unlock() at the end of the function. So I
118 * conclude that the Lua thread safe mode just perform a mutex around
119 * all execution. So I prefer to do this in the HAProxy code, it will be
120 * easier for distro maintainers.
121 *
122 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
123 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
124 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200125 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100126__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200127THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200128static int hlua_panic_safe(lua_State *L) { return 0; }
129static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
130
131#define SET_SAFE_LJMP(__L) \
132 ({ \
133 int ret; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100134 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200135 if (setjmp(safe_ljmp_env) != 0) { \
136 lua_atpanic(__L, hlua_panic_safe); \
137 ret = 0; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100138 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200139 } else { \
140 lua_atpanic(__L, hlua_panic_ljmp); \
141 ret = 1; \
142 } \
143 ret; \
144 })
145
146/* If we are the last function catching Lua errors, we
147 * must reset the panic function.
148 */
149#define RESET_SAFE_LJMP(__L) \
150 do { \
151 lua_atpanic(__L, hlua_panic_safe); \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100152 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200153 } while(0)
154
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200155/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200156#define APPLET_DONE 0x01 /* applet processing is done. */
157#define APPLET_100C 0x02 /* 100 continue expected. */
158#define APPLET_HDR_SENT 0x04 /* Response header sent. */
159#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
160#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100161#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100162#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200163
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100164/* The main Lua execution context. */
165struct hlua gL;
166
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100167/* This is the memory pool containing struct lua for applets
168 * (including cli).
169 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100170DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100171
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100172/* Used for Socket connection. */
173static struct proxy socket_proxy;
174static struct server socket_tcp;
175#ifdef USE_OPENSSL
176static struct server socket_ssl;
177#endif
178
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100179/* List head of the function called at the initialisation time. */
180struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
181
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100182/* The following variables contains the reference of the different
183 * Lua classes. These references are useful for identify metadata
184 * associated with an object.
185 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100186static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100187static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100188static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100189static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100190static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100191static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200192static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200193static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200194static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100195
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100196/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200197 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100198 * short timeout. Lua linked with tasks doesn't have a timeout
199 * because a task may remain alive during all the haproxy execution.
200 */
201static unsigned int hlua_timeout_session = 4000; /* session timeout. */
202static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200203static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100204
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100205/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
206 * it is used for preventing infinite loops.
207 *
208 * I test the scheer with an infinite loop containing one incrementation
209 * and one test. I run this loop between 10 seconds, I raise a ceil of
210 * 710M loops from one interrupt each 9000 instructions, so I fix the value
211 * to one interrupt each 10 000 instructions.
212 *
213 * configured | Number of
214 * instructions | loops executed
215 * between two | in milions
216 * forced yields |
217 * ---------------+---------------
218 * 10 | 160
219 * 500 | 670
220 * 1000 | 680
221 * 5000 | 700
222 * 7000 | 700
223 * 8000 | 700
224 * 9000 | 710 <- ceil
225 * 10000 | 710
226 * 100000 | 710
227 * 1000000 | 710
228 *
229 */
230static unsigned int hlua_nb_instruction = 10000;
231
Willy Tarreau32f61e22015-03-18 17:54:59 +0100232/* Descriptor for the memory allocation state. If limit is not null, it will
233 * be enforced on any memory allocation.
234 */
235struct hlua_mem_allocator {
236 size_t allocated;
237 size_t limit;
238};
239
240static struct hlua_mem_allocator hlua_global_allocator;
241
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200242static const char error_500[] =
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200243 "HTTP/1.0 500 Internal Server Error\r\n"
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200244 "Cache-Control: no-cache\r\n"
245 "Connection: close\r\n"
246 "Content-Type: text/html\r\n"
247 "\r\n"
Joseph Herlant7fe15772018-11-15 10:07:32 -0800248 "<html><body><h1>500 Internal Server Error</h1>\nAn internal server error occurred.\n</body></html>\n";
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200249
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100250/* These functions converts types between HAProxy internal args or
251 * sample and LUA types. Another function permits to check if the
252 * LUA stack contains arguments according with an required ARG_T
253 * format.
254 */
255static int hlua_arg2lua(lua_State *L, const struct arg *arg);
256static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100257__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100258 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100259static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100260static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100261static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
262
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200263__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
264
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200265#define SEND_ERR(__be, __fmt, __args...) \
266 do { \
267 send_log(__be, LOG_ERR, __fmt, ## __args); \
268 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100269 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200270 } while (0)
271
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100272/* Used to check an Lua function type in the stack. It creates and
273 * returns a reference of the function. This function throws an
274 * error if the rgument is not a "function".
275 */
276__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
277{
278 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100279 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100280 WILL_LJMP(luaL_argerror(L, argno, msg));
281 }
282 lua_pushvalue(L, argno);
283 return luaL_ref(L, LUA_REGISTRYINDEX);
284}
285
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200286/* Return the string that is of the top of the stack. */
287const char *hlua_get_top_error_string(lua_State *L)
288{
289 if (lua_gettop(L) < 1)
290 return "unknown error";
291 if (lua_type(L, -1) != LUA_TSTRING)
292 return "unknown error";
293 return lua_tostring(L, -1);
294}
295
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200296__LJMP static const char *hlua_traceback(lua_State *L)
297{
298 lua_Debug ar;
299 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200300 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200301 int filled = 0;
302
303 while (lua_getstack(L, level++, &ar)) {
304
305 /* Add separator */
306 if (filled)
307 chunk_appendf(msg, ", ");
308 filled = 1;
309
310 /* Fill fields:
311 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
312 * 'l': fills in the field currentline;
313 * 'n': fills in the field name and namewhat;
314 * 't': fills in the field istailcall;
315 */
316 lua_getinfo(L, "Slnt", &ar);
317
318 /* Append code localisation */
319 if (ar.currentline > 0)
320 chunk_appendf(msg, "%s:%d ", ar.short_src, ar.currentline);
321 else
322 chunk_appendf(msg, "%s ", ar.short_src);
323
324 /*
325 * Get function name
326 *
327 * if namewhat is no empty, name is defined.
328 * what contains "Lua" for Lua function, "C" for C function,
329 * or "main" for main code.
330 */
331 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
332 chunk_appendf(msg, "%s '%s'", ar.namewhat, ar.name); /* use it */
333
334 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
335 chunk_appendf(msg, "main chunk");
336
337 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
338 chunk_appendf(msg, "C function line %d", ar.linedefined);
339
340 else /* nothing left... */
341 chunk_appendf(msg, "?");
342
343
344 /* Display tailed call */
345 if (ar.istailcall)
346 chunk_appendf(msg, " ...");
347 }
348
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200349 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200350}
351
352
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100353/* This function check the number of arguments available in the
354 * stack. If the number of arguments available is not the same
355 * then <nb> an error is throwed.
356 */
357__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
358{
359 if (lua_gettop(L) == nb)
360 return;
361 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
362}
363
Mark Lakes22154b42018-01-29 14:38:40 -0800364/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100365 * and the line number where the error is encountered.
366 */
367static int hlua_pusherror(lua_State *L, const char *fmt, ...)
368{
369 va_list argp;
370 va_start(argp, fmt);
371 luaL_where(L, 1);
372 lua_pushvfstring(L, fmt, argp);
373 va_end(argp);
374 lua_concat(L, 2);
375 return 1;
376}
377
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100378/* This functions is used with sample fetch and converters. It
379 * converts the HAProxy configuration argument in a lua stack
380 * values.
381 *
382 * It takes an array of "arg", and each entry of the array is
383 * converted and pushed in the LUA stack.
384 */
385static int hlua_arg2lua(lua_State *L, const struct arg *arg)
386{
387 switch (arg->type) {
388 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100389 case ARGT_TIME:
390 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100391 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100392 break;
393
394 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200395 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100396 break;
397
398 case ARGT_IPV4:
399 case ARGT_IPV6:
400 case ARGT_MSK4:
401 case ARGT_MSK6:
402 case ARGT_FE:
403 case ARGT_BE:
404 case ARGT_TAB:
405 case ARGT_SRV:
406 case ARGT_USR:
407 case ARGT_MAP:
408 default:
409 lua_pushnil(L);
410 break;
411 }
412 return 1;
413}
414
415/* This function take one entrie in an LUA stack at the index "ud",
416 * and try to convert it in an HAProxy argument entry. This is useful
417 * with sample fetch wrappers. The input arguments are gived to the
418 * lua wrapper and converted as arg list by thi function.
419 */
420static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
421{
422 switch (lua_type(L, ud)) {
423
424 case LUA_TNUMBER:
425 case LUA_TBOOLEAN:
426 arg->type = ARGT_SINT;
427 arg->data.sint = lua_tointeger(L, ud);
428 break;
429
430 case LUA_TSTRING:
431 arg->type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200432 arg->data.str.area = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100433 break;
434
435 case LUA_TUSERDATA:
436 case LUA_TNIL:
437 case LUA_TTABLE:
438 case LUA_TFUNCTION:
439 case LUA_TTHREAD:
440 case LUA_TLIGHTUSERDATA:
441 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200442 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100443 break;
444 }
445 return 1;
446}
447
448/* the following functions are used to convert a struct sample
449 * in Lua type. This useful to convert the return of the
450 * fetchs or converters.
451 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100452static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100453{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200454 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100455 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100456 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200457 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100458 break;
459
460 case SMP_T_BIN:
461 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200462 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100463 break;
464
465 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200466 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100467 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
468 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
469 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
470 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
471 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
472 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
473 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
474 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
475 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200476 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100477 break;
478 default:
479 lua_pushnil(L);
480 break;
481 }
482 break;
483
484 case SMP_T_IPV4:
485 case SMP_T_IPV6:
486 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200487 if (sample_casts[smp->data.type][SMP_T_STR] &&
488 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200489 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100490 else
491 lua_pushnil(L);
492 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100493 default:
494 lua_pushnil(L);
495 break;
496 }
497 return 1;
498}
499
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100500/* the following functions are used to convert a struct sample
501 * in Lua strings. This is useful to convert the return of the
502 * fetchs or converters.
503 */
504static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
505{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200506 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100507
508 case SMP_T_BIN:
509 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200510 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100511 break;
512
513 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200514 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100515 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
516 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
517 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
518 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
519 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
520 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
521 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
522 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
523 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200524 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100525 break;
526 default:
527 lua_pushstring(L, "");
528 break;
529 }
530 break;
531
532 case SMP_T_SINT:
533 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100534 case SMP_T_IPV4:
535 case SMP_T_IPV6:
536 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200537 if (sample_casts[smp->data.type][SMP_T_STR] &&
538 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200539 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100540 else
541 lua_pushstring(L, "");
542 break;
543 default:
544 lua_pushstring(L, "");
545 break;
546 }
547 return 1;
548}
549
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100550/* the following functions are used to convert an Lua type in a
551 * struct sample. This is useful to provide data from a converter
552 * to the LUA code.
553 */
554static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
555{
556 switch (lua_type(L, ud)) {
557
558 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200559 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200560 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100561 break;
562
563
564 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200565 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200566 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100567 break;
568
569 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200570 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100571 smp->flags |= SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200572 smp->data.u.str.area = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100573 break;
574
575 case LUA_TUSERDATA:
576 case LUA_TNIL:
577 case LUA_TTABLE:
578 case LUA_TFUNCTION:
579 case LUA_TTHREAD:
580 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200581 case LUA_TNONE:
582 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200583 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200584 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100585 break;
586 }
587 return 1;
588}
589
590/* This function check the "argp" builded by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800591 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100592 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100593 *
594 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
595 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100596 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100597__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100598 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100599{
600 int min_arg;
601 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100602 struct proxy *px;
603 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100604
605 idx = 0;
606 min_arg = ARGM(mask);
607 mask >>= ARGM_BITS;
608
609 while (1) {
610
611 /* Check oversize. */
612 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100613 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100614 }
615
616 /* Check for mandatory arguments. */
617 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100618 if (idx < min_arg) {
619
620 /* If miss other argument than the first one, we return an error. */
621 if (idx > 0)
622 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
623
624 /* If first argument have a certain type, some default values
625 * may be used. See the function smp_resolve_args().
626 */
627 switch (mask & ARGT_MASK) {
628
629 case ARGT_FE:
630 if (!(p->cap & PR_CAP_FE))
631 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
632 argp[idx].data.prx = p;
633 argp[idx].type = ARGT_FE;
634 argp[idx+1].type = ARGT_STOP;
635 break;
636
637 case ARGT_BE:
638 if (!(p->cap & PR_CAP_BE))
639 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
640 argp[idx].data.prx = p;
641 argp[idx].type = ARGT_BE;
642 argp[idx+1].type = ARGT_STOP;
643 break;
644
645 case ARGT_TAB:
646 argp[idx].data.prx = p;
647 argp[idx].type = ARGT_TAB;
648 argp[idx+1].type = ARGT_STOP;
649 break;
650
651 default:
652 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
653 break;
654 }
655 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100656 return 0;
657 }
658
659 /* Check for exceed the number of requiered argument. */
660 if ((mask & ARGT_MASK) == ARGT_STOP &&
661 argp[idx].type != ARGT_STOP) {
662 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
663 }
664
665 if ((mask & ARGT_MASK) == ARGT_STOP &&
666 argp[idx].type == ARGT_STOP) {
667 return 0;
668 }
669
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100670 /* Convert some argument types. */
671 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100672 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100673 if (argp[idx].type != ARGT_SINT)
674 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
675 argp[idx].type = ARGT_SINT;
676 break;
677
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100678 case ARGT_TIME:
679 if (argp[idx].type != ARGT_SINT)
680 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200681 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100682 break;
683
684 case ARGT_SIZE:
685 if (argp[idx].type != ARGT_SINT)
686 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200687 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100688 break;
689
690 case ARGT_FE:
691 if (argp[idx].type != ARGT_STR)
692 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200693 memcpy(trash.area, argp[idx].data.str.area,
694 argp[idx].data.str.data);
695 trash.area[argp[idx].data.str.data] = 0;
696 argp[idx].data.prx = proxy_fe_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100697 if (!argp[idx].data.prx)
698 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
699 argp[idx].type = ARGT_FE;
700 break;
701
702 case ARGT_BE:
703 if (argp[idx].type != ARGT_STR)
704 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200705 memcpy(trash.area, argp[idx].data.str.area,
706 argp[idx].data.str.data);
707 trash.area[argp[idx].data.str.data] = 0;
708 argp[idx].data.prx = proxy_be_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100709 if (!argp[idx].data.prx)
710 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
711 argp[idx].type = ARGT_BE;
712 break;
713
714 case ARGT_TAB:
715 if (argp[idx].type != ARGT_STR)
716 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200717 memcpy(trash.area, argp[idx].data.str.area,
718 argp[idx].data.str.data);
719 trash.area[argp[idx].data.str.data] = 0;
720 argp[idx].data.prx = proxy_tbl_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100721 if (!argp[idx].data.prx)
722 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
723 argp[idx].type = ARGT_TAB;
724 break;
725
726 case ARGT_SRV:
727 if (argp[idx].type != ARGT_STR)
728 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200729 memcpy(trash.area, argp[idx].data.str.area,
730 argp[idx].data.str.data);
731 trash.area[argp[idx].data.str.data] = 0;
732 sname = strrchr(trash.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100733 if (sname) {
734 *sname++ = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200735 pname = trash.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200736 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100737 if (!px)
738 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
739 }
740 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200741 sname = trash.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100742 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100743 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100744 argp[idx].data.srv = findserver(px, sname);
745 if (!argp[idx].data.srv)
746 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
747 argp[idx].type = ARGT_SRV;
748 break;
749
750 case ARGT_IPV4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200751 memcpy(trash.area, argp[idx].data.str.area,
752 argp[idx].data.str.data);
753 trash.area[argp[idx].data.str.data] = 0;
754 if (inet_pton(AF_INET, trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100755 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
756 argp[idx].type = ARGT_IPV4;
757 break;
758
759 case ARGT_MSK4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200760 memcpy(trash.area, argp[idx].data.str.area,
761 argp[idx].data.str.data);
762 trash.area[argp[idx].data.str.data] = 0;
763 if (!str2mask(trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100764 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
765 argp[idx].type = ARGT_MSK4;
766 break;
767
768 case ARGT_IPV6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200769 memcpy(trash.area, argp[idx].data.str.area,
770 argp[idx].data.str.data);
771 trash.area[argp[idx].data.str.data] = 0;
772 if (inet_pton(AF_INET6, trash.area, &argp[idx].data.ipv6))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100773 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
774 argp[idx].type = ARGT_IPV6;
775 break;
776
777 case ARGT_MSK6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200778 memcpy(trash.area, argp[idx].data.str.area,
779 argp[idx].data.str.data);
780 trash.area[argp[idx].data.str.data] = 0;
781 if (!str2mask6(trash.area, &argp[idx].data.ipv6))
Tim Duesterhusb814da62018-01-25 16:24:50 +0100782 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 mask"));
783 argp[idx].type = ARGT_MSK6;
784 break;
785
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100786 case ARGT_MAP:
787 case ARGT_REG:
788 case ARGT_USR:
789 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100790 break;
791 }
792
793 /* Check for type of argument. */
794 if ((mask & ARGT_MASK) != argp[idx].type) {
795 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
796 arg_type_names[(mask & ARGT_MASK)],
797 arg_type_names[argp[idx].type & ARGT_MASK]);
798 WILL_LJMP(luaL_argerror(L, first + idx, msg));
799 }
800
801 /* Next argument. */
802 mask >>= ARGT_BITS;
803 idx++;
804 }
805}
806
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100807/*
808 * The following functions are used to make correspondance between the the
809 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100810 *
811 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100812 * - hlua_sethlua : create the association between hlua context and lua_state.
813 */
814static inline struct hlua *hlua_gethlua(lua_State *L)
815{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100816 struct hlua **hlua = lua_getextraspace(L);
817 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100818}
819static inline void hlua_sethlua(struct hlua *hlua)
820{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100821 struct hlua **hlua_store = lua_getextraspace(hlua->T);
822 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100823}
824
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100825/* This function is used to send logs. It try to send on screen (stderr)
826 * and on the default syslog server.
827 */
828static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
829{
830 struct tm tm;
831 char *p;
832
833 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200834 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100835 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200836 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200837 /* Break the message if exceed the buffer size. */
838 *(p-4) = ' ';
839 *(p-3) = '.';
840 *(p-2) = '.';
841 *(p-1) = '.';
842 break;
843 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100844 if (isprint(*msg))
845 *p = *msg;
846 else
847 *p = '.';
848 }
849 *p = '\0';
850
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200851 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100852 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200853 get_localtime(date.tv_sec, &tm);
854 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100855 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200856 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100857 fflush(stderr);
858 }
859}
860
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100861/* This function just ensure that the yield will be always
862 * returned with a timeout and permit to set some flags
863 */
864__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100865 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100866{
867 struct hlua *hlua = hlua_gethlua(L);
868
869 /* Set the wake timeout. If timeout is required, we set
870 * the expiration time.
871 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200872 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100873
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100874 hlua->flags |= flags;
875
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100876 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +0200877 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100878}
879
Willy Tarreau87b09662015-04-03 00:22:06 +0200880/* This function initialises the Lua environment stored in the stream.
881 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100882 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200883 *
884 * This function is particular. it initialises a new Lua thread. If the
885 * initialisation fails (example: out of memory error), the lua function
886 * throws an error (longjmp).
887 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100888 * In some case (at least one), this function can be called from safe
889 * environement, so we must not initialise it. While the support of
890 * threads appear, the safe environment set a lock to ensure only one
891 * Lua execution at a time. If we initialize safe environment in another
892 * safe environmenet, we have a dead lock.
893 *
894 * set "already_safe" true if the context is initialized form safe
895 * Lua fonction.
896 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800897 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200898 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800899 * MUST NOT manipulate the created thread stack state, because it is not
900 * proctected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100901 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100902int hlua_ctx_init(struct hlua *lua, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100903{
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100904 if (!already_safe) {
905 if (!SET_SAFE_LJMP(gL.T)) {
906 lua->Tref = LUA_REFNIL;
907 return 0;
908 }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200909 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100910 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100911 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100912 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100913 lua->T = lua_newthread(gL.T);
914 if (!lua->T) {
915 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100916 if (!already_safe)
917 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100918 return 0;
919 }
920 hlua_sethlua(lua);
921 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
922 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100923 if (!already_safe)
924 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100925 return 1;
926}
927
Willy Tarreau87b09662015-04-03 00:22:06 +0200928/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100929 * is destroyed. The destroy also the memory context. The struct "lua"
930 * is not freed.
931 */
932void hlua_ctx_destroy(struct hlua *lua)
933{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100934 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100935 return;
936
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100937 if (!lua->T)
938 goto end;
939
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100940 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +0200941 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100942
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200943 if (!SET_SAFE_LJMP(lua->T))
944 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100945 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200946 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200947
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200948 if (!SET_SAFE_LJMP(gL.T))
949 return;
950 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
951 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200952 /* Forces a garbage collecting process. If the Lua program is finished
953 * without error, we run the GC on the thread pointer. Its freed all
954 * the unused memory.
955 * If the thread is finnish with an error or is currently yielded,
956 * it seems that the GC applied on the thread doesn't clean anything,
957 * so e run the GC on the main thread.
958 * NOTE: maybe this action locks all the Lua threads untiml the en of
959 * the garbage collection.
960 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200961 if (lua->flags & HLUA_MUST_GC) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200962 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200963 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200964 lua_gc(gL.T, LUA_GCCOLLECT, 0);
965 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200966 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200967
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200968 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100969
970end:
Willy Tarreaubafbe012017-11-24 17:34:44 +0100971 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100972}
973
974/* This function is used to restore the Lua context when a coroutine
975 * fails. This function copy the common memory between old coroutine
976 * and the new coroutine. The old coroutine is destroyed, and its
977 * replaced by the new coroutine.
978 * If the flag "keep_msg" is set, the last entry of the old is assumed
979 * as string error message and it is copied in the new stack.
980 */
981static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
982{
983 lua_State *T;
984 int new_ref;
985
986 /* Renew the main LUA stack doesn't have sense. */
987 if (lua == &gL)
988 return 0;
989
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100990 /* New Lua coroutine. */
991 T = lua_newthread(gL.T);
992 if (!T)
993 return 0;
994
995 /* Copy last error message. */
996 if (keep_msg)
997 lua_xmove(lua->T, T, 1);
998
999 /* Copy data between the coroutines. */
1000 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1001 lua_xmove(lua->T, T, 1);
1002 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
1003
1004 /* Destroy old data. */
1005 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1006
1007 /* The thread is garbage collected by Lua. */
1008 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
1009
1010 /* Fill the struct with the new coroutine values. */
1011 lua->Mref = new_ref;
1012 lua->T = T;
1013 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
1014
1015 /* Set context. */
1016 hlua_sethlua(lua);
1017
1018 return 1;
1019}
1020
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001021void hlua_hook(lua_State *L, lua_Debug *ar)
1022{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001023 struct hlua *hlua = hlua_gethlua(L);
1024
1025 /* Lua cannot yield when its returning from a function,
1026 * so, we can fix the interrupt hook to 1 instruction,
1027 * expecting that the function is finnished.
1028 */
1029 if (lua_gethookmask(L) & LUA_MASKRET) {
1030 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1031 return;
1032 }
1033
1034 /* restore the interrupt condition. */
1035 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1036
1037 /* If we interrupt the Lua processing in yieldable state, we yield.
1038 * If the state is not yieldable, trying yield causes an error.
1039 */
1040 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001041 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001042
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001043 /* If we cannot yield, update the clock and check the timeout. */
1044 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001045 hlua->run_time += now_ms - hlua->start_time;
1046 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001047 lua_pushfstring(L, "execution timeout");
1048 WILL_LJMP(lua_error(L));
1049 }
1050
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001051 /* Update the start time. */
1052 hlua->start_time = now_ms;
1053
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001054 /* Try to interrupt the process at the end of the current
1055 * unyieldable function.
1056 */
1057 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001058}
1059
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001060/* This function start or resumes the Lua stack execution. If the flag
1061 * "yield_allowed" if no set and the LUA stack execution returns a yield
1062 * The function return an error.
1063 *
1064 * The function can returns 4 values:
1065 * - HLUA_E_OK : The execution is terminated without any errors.
1066 * - HLUA_E_AGAIN : The execution must continue at the next associated
1067 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001068 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001069 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001070 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001071 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001072 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001073 * LUA code.
1074 */
1075static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1076{
1077 int ret;
1078 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001079 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001080
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001081 /* Initialise run time counter. */
1082 if (!HLUA_IS_RUNNING(lua))
1083 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001084
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001085 /* Lock the whole Lua execution. This lock must be before the
1086 * label "resume_execution".
1087 */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001088 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001089
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001090resume_execution:
1091
1092 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1093 * instructions. it is used for preventing infinite loops.
1094 */
1095 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1096
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001097 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001098 HLUA_SET_RUN(lua);
1099 HLUA_CLR_CTRLYIELD(lua);
1100 HLUA_CLR_WAKERESWR(lua);
1101 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001102
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001103 /* Update the start time. */
1104 lua->start_time = now_ms;
1105
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001106 /* Call the function. */
1107 ret = lua_resume(lua->T, gL.T, lua->nargs);
1108 switch (ret) {
1109
1110 case LUA_OK:
1111 ret = HLUA_E_OK;
1112 break;
1113
1114 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001115 /* Check if the execution timeout is expired. It it is the case, we
1116 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001117 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001118 tv_update_date(0, 1);
1119 lua->run_time += now_ms - lua->start_time;
1120 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001121 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001122 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001123 break;
1124 }
1125 /* Process the forced yield. if the general yield is not allowed or
1126 * if no task were associated this the current Lua execution
1127 * coroutine, we resume the execution. Else we want to return in the
1128 * scheduler and we want to be waked up again, to continue the
1129 * current Lua execution. So we schedule our own task.
1130 */
1131 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001132 if (!yield_allowed || !lua->task)
1133 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001134 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001135 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001136 if (!yield_allowed) {
1137 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001138 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001139 break;
1140 }
1141 ret = HLUA_E_AGAIN;
1142 break;
1143
1144 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001145
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001146 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001147 * because the errors ares the only one mean to return immediately
1148 * from and lua execution.
1149 */
1150 if (lua->flags & HLUA_EXIT) {
1151 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001152 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001153 break;
1154 }
1155
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001156 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001157 if (!lua_checkstack(lua->T, 1)) {
1158 ret = HLUA_E_ERR;
1159 break;
1160 }
1161 msg = lua_tostring(lua->T, -1);
1162 lua_settop(lua->T, 0); /* Empty the stack. */
1163 lua_pop(lua->T, 1);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001164 trace = hlua_traceback(lua->T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001165 if (msg)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001166 lua_pushfstring(lua->T, "runtime error: %s from %s", msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001167 else
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001168 lua_pushfstring(lua->T, "unknown runtime error from %s", trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001169 ret = HLUA_E_ERRMSG;
1170 break;
1171
1172 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001173 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001174 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001175 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001176 break;
1177
1178 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001179 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001180 if (!lua_checkstack(lua->T, 1)) {
1181 ret = HLUA_E_ERR;
1182 break;
1183 }
1184 msg = lua_tostring(lua->T, -1);
1185 lua_settop(lua->T, 0); /* Empty the stack. */
1186 lua_pop(lua->T, 1);
1187 if (msg)
1188 lua_pushfstring(lua->T, "message handler error: %s", msg);
1189 else
1190 lua_pushfstring(lua->T, "message handler error");
1191 ret = HLUA_E_ERRMSG;
1192 break;
1193
1194 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001195 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001196 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001197 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001198 break;
1199 }
1200
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001201 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001202 if (lua->flags & HLUA_MUST_GC &&
1203 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001204 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1205
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001206 switch (ret) {
1207 case HLUA_E_AGAIN:
1208 break;
1209
1210 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001211 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001212 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001213 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001214 break;
1215
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001216 case HLUA_E_ETMOUT:
1217 case HLUA_E_NOMEM:
1218 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001219 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001220 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001221 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001222 hlua_ctx_renew(lua, 0);
1223 break;
1224
1225 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001226 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001227 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001228 break;
1229 }
1230
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001231 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001232 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001233
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001234 return ret;
1235}
1236
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001237/* This function exit the current code. */
1238__LJMP static int hlua_done(lua_State *L)
1239{
1240 struct hlua *hlua = hlua_gethlua(L);
1241
1242 hlua->flags |= HLUA_EXIT;
1243 WILL_LJMP(lua_error(L));
1244
1245 return 0;
1246}
1247
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001248/* This function is an LUA binding. It provides a function
1249 * for deleting ACL from a referenced ACL file.
1250 */
1251__LJMP static int hlua_del_acl(lua_State *L)
1252{
1253 const char *name;
1254 const char *key;
1255 struct pat_ref *ref;
1256
1257 MAY_LJMP(check_args(L, 2, "del_acl"));
1258
1259 name = MAY_LJMP(luaL_checkstring(L, 1));
1260 key = MAY_LJMP(luaL_checkstring(L, 2));
1261
1262 ref = pat_ref_lookup(name);
1263 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001264 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001265
1266 pat_ref_delete(ref, key);
1267 return 0;
1268}
1269
1270/* This function is an LUA binding. It provides a function
1271 * for deleting map entry from a referenced map file.
1272 */
1273static int hlua_del_map(lua_State *L)
1274{
1275 const char *name;
1276 const char *key;
1277 struct pat_ref *ref;
1278
1279 MAY_LJMP(check_args(L, 2, "del_map"));
1280
1281 name = MAY_LJMP(luaL_checkstring(L, 1));
1282 key = MAY_LJMP(luaL_checkstring(L, 2));
1283
1284 ref = pat_ref_lookup(name);
1285 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001286 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001287
1288 pat_ref_delete(ref, key);
1289 return 0;
1290}
1291
1292/* This function is an LUA binding. It provides a function
1293 * for adding ACL pattern from a referenced ACL file.
1294 */
1295static int hlua_add_acl(lua_State *L)
1296{
1297 const char *name;
1298 const char *key;
1299 struct pat_ref *ref;
1300
1301 MAY_LJMP(check_args(L, 2, "add_acl"));
1302
1303 name = MAY_LJMP(luaL_checkstring(L, 1));
1304 key = MAY_LJMP(luaL_checkstring(L, 2));
1305
1306 ref = pat_ref_lookup(name);
1307 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001308 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001309
1310 if (pat_ref_find_elt(ref, key) == NULL)
1311 pat_ref_add(ref, key, NULL, NULL);
1312 return 0;
1313}
1314
1315/* This function is an LUA binding. It provides a function
1316 * for setting map pattern and sample from a referenced map
1317 * file.
1318 */
1319static int hlua_set_map(lua_State *L)
1320{
1321 const char *name;
1322 const char *key;
1323 const char *value;
1324 struct pat_ref *ref;
1325
1326 MAY_LJMP(check_args(L, 3, "set_map"));
1327
1328 name = MAY_LJMP(luaL_checkstring(L, 1));
1329 key = MAY_LJMP(luaL_checkstring(L, 2));
1330 value = MAY_LJMP(luaL_checkstring(L, 3));
1331
1332 ref = pat_ref_lookup(name);
1333 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001334 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001335
1336 if (pat_ref_find_elt(ref, key) != NULL)
1337 pat_ref_set(ref, key, value, NULL);
1338 else
1339 pat_ref_add(ref, key, value, NULL);
1340 return 0;
1341}
1342
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001343/* A class is a lot of memory that contain data. This data can be a table,
1344 * an integer or user data. This data is associated with a metatable. This
1345 * metatable have an original version registred in the global context with
1346 * the name of the object (_G[<name>] = <metable> ).
1347 *
1348 * A metable is a table that modify the standard behavior of a standard
1349 * access to the associated data. The entries of this new metatable are
1350 * defined as is:
1351 *
1352 * http://lua-users.org/wiki/MetatableEvents
1353 *
1354 * __index
1355 *
1356 * we access an absent field in a table, the result is nil. This is
1357 * true, but it is not the whole truth. Actually, such access triggers
1358 * the interpreter to look for an __index metamethod: If there is no
1359 * such method, as usually happens, then the access results in nil;
1360 * otherwise, the metamethod will provide the result.
1361 *
1362 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1363 * the key does not appear in the table, but the metatable has an __index
1364 * property:
1365 *
1366 * - if the value is a function, the function is called, passing in the
1367 * table and the key; the return value of that function is returned as
1368 * the result.
1369 *
1370 * - if the value is another table, the value of the key in that table is
1371 * asked for and returned (and if it doesn't exist in that table, but that
1372 * table's metatable has an __index property, then it continues on up)
1373 *
1374 * - Use "rawget(myTable,key)" to skip this metamethod.
1375 *
1376 * http://www.lua.org/pil/13.4.1.html
1377 *
1378 * __newindex
1379 *
1380 * Like __index, but control property assignment.
1381 *
1382 * __mode - Control weak references. A string value with one or both
1383 * of the characters 'k' and 'v' which specifies that the the
1384 * keys and/or values in the table are weak references.
1385 *
1386 * __call - Treat a table like a function. When a table is followed by
1387 * parenthesis such as "myTable( 'foo' )" and the metatable has
1388 * a __call key pointing to a function, that function is invoked
1389 * (passing any specified arguments) and the return value is
1390 * returned.
1391 *
1392 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1393 * called, if the metatable for myTable has a __metatable
1394 * key, the value of that key is returned instead of the
1395 * actual metatable.
1396 *
1397 * __tostring - Control string representation. When the builtin
1398 * "tostring( myTable )" function is called, if the metatable
1399 * for myTable has a __tostring property set to a function,
1400 * that function is invoked (passing myTable to it) and the
1401 * return value is used as the string representation.
1402 *
1403 * __len - Control table length. When the table length is requested using
1404 * the length operator ( '#' ), if the metatable for myTable has
1405 * a __len key pointing to a function, that function is invoked
1406 * (passing myTable to it) and the return value used as the value
1407 * of "#myTable".
1408 *
1409 * __gc - Userdata finalizer code. When userdata is set to be garbage
1410 * collected, if the metatable has a __gc field pointing to a
1411 * function, that function is first invoked, passing the userdata
1412 * to it. The __gc metamethod is not called for tables.
1413 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1414 *
1415 * Special metamethods for redefining standard operators:
1416 * http://www.lua.org/pil/13.1.html
1417 *
1418 * __add "+"
1419 * __sub "-"
1420 * __mul "*"
1421 * __div "/"
1422 * __unm "!"
1423 * __pow "^"
1424 * __concat ".."
1425 *
1426 * Special methods for redfining standar relations
1427 * http://www.lua.org/pil/13.2.html
1428 *
1429 * __eq "=="
1430 * __lt "<"
1431 * __le "<="
1432 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001433
1434/*
1435 *
1436 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001437 * Class Map
1438 *
1439 *
1440 */
1441
1442/* Returns a struct hlua_map if the stack entry "ud" is
1443 * a class session, otherwise it throws an error.
1444 */
1445__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1446{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001447 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001448}
1449
1450/* This function is the map constructor. It don't need
1451 * the class Map object. It creates and return a new Map
1452 * object. It must be called only during "body" or "init"
1453 * context because it process some filesystem accesses.
1454 */
1455__LJMP static int hlua_map_new(struct lua_State *L)
1456{
1457 const char *fn;
1458 int match = PAT_MATCH_STR;
1459 struct sample_conv conv;
1460 const char *file = "";
1461 int line = 0;
1462 lua_Debug ar;
1463 char *err = NULL;
1464 struct arg args[2];
1465
1466 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1467 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1468
1469 fn = MAY_LJMP(luaL_checkstring(L, 1));
1470
1471 if (lua_gettop(L) >= 2) {
1472 match = MAY_LJMP(luaL_checkinteger(L, 2));
1473 if (match < 0 || match >= PAT_MATCH_NUM)
1474 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1475 }
1476
1477 /* Get Lua filename and line number. */
1478 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1479 lua_getinfo(L, "Sl", &ar); /* get info about it */
1480 if (ar.currentline > 0) { /* is there info? */
1481 file = ar.short_src;
1482 line = ar.currentline;
1483 }
1484 }
1485
1486 /* fill fake sample_conv struct. */
1487 conv.kw = ""; /* unused. */
1488 conv.process = NULL; /* unused. */
1489 conv.arg_mask = 0; /* unused. */
1490 conv.val_args = NULL; /* unused. */
1491 conv.out_type = SMP_T_STR;
1492 conv.private = (void *)(long)match;
1493 switch (match) {
1494 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1495 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1496 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1497 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1498 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1499 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1500 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001501 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001502 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1503 default:
1504 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1505 }
1506
1507 /* fill fake args. */
1508 args[0].type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001509 args[0].data.str.area = (char *)fn;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001510 args[1].type = ARGT_STOP;
1511
1512 /* load the map. */
1513 if (!sample_load_map(args, &conv, file, line, &err)) {
1514 /* error case: we cant use luaL_error because we must
1515 * free the err variable.
1516 */
1517 luaL_where(L, 1);
1518 lua_pushfstring(L, "'new': %s.", err);
1519 lua_concat(L, 2);
1520 free(err);
1521 WILL_LJMP(lua_error(L));
1522 }
1523
1524 /* create the lua object. */
1525 lua_newtable(L);
1526 lua_pushlightuserdata(L, args[0].data.map);
1527 lua_rawseti(L, -2, 0);
1528
1529 /* Pop a class Map metatable and affect it to the userdata. */
1530 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1531 lua_setmetatable(L, -2);
1532
1533
1534 return 1;
1535}
1536
1537__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1538{
1539 struct map_descriptor *desc;
1540 struct pattern *pat;
1541 struct sample smp;
1542
1543 MAY_LJMP(check_args(L, 2, "lookup"));
1544 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001545 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001546 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001547 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001548 }
1549 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001550 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001551 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001552 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 +02001553 }
1554
1555 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001556 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001557 if (str)
1558 lua_pushstring(L, "");
1559 else
1560 lua_pushnil(L);
1561 return 1;
1562 }
1563
1564 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001565 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001566 return 1;
1567}
1568
1569__LJMP static int hlua_map_lookup(struct lua_State *L)
1570{
1571 return _hlua_map_lookup(L, 0);
1572}
1573
1574__LJMP static int hlua_map_slookup(struct lua_State *L)
1575{
1576 return _hlua_map_lookup(L, 1);
1577}
1578
1579/*
1580 *
1581 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001582 * Class Socket
1583 *
1584 *
1585 */
1586
1587__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1588{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001589 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001590}
1591
1592/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001593 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001594 * received.
1595 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001596static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001597{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001598 struct stream_interface *si = appctx->owner;
Olivier Houchard9aaf7782017-09-13 18:30:23 +02001599 struct connection *c = cs_conn(objt_cs(si_opposite(si)->end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001600
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001601 if (appctx->ctx.hlua_cosocket.die) {
1602 si_shutw(si);
1603 si_shutr(si);
1604 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001605 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1606 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001607 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1608 }
1609
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001610 /* If the connection object is not available, close all the
1611 * streams and wakeup everything waiting for.
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001612 */
1613 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001614 si_shutw(si);
1615 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001616 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001617 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1618 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001619 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001620 }
1621
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001622 /* If we cant write, wakeup the pending write signals. */
1623 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001624 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001625
1626 /* If we cant read, wakeup the pending read signals. */
1627 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001628 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001629
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001630 /* if the connection is not estabkished, inform the stream that we want
1631 * to be notified whenever the connection completes.
1632 */
1633 if (!(c->flags & CO_FL_CONNECTED)) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01001634 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01001635 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01001636 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001637 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001638 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001639
1640 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001641 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001642
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001643 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001644 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001645 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001646
1647 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001648 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001649 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001650
1651 /* Some data were injected in the buffer, notify the stream
1652 * interface.
1653 */
1654 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001655 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001656
1657 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001658 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001659 */
1660 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01001661 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001662}
1663
Willy Tarreau87b09662015-04-03 00:22:06 +02001664/* This function is called when the "struct stream" is destroyed.
1665 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001666 * Wake all the pending signals.
1667 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001668static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001669{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001670 struct xref *peer;
1671
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001672 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001673 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1674 if (peer)
1675 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001676
1677 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001678 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1679 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001680}
1681
1682/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001683 * uses this object. If the stream does not exists, just quit.
1684 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001685 * pending signal can rest in the read and write lists. destroy
1686 * it.
1687 */
1688__LJMP static int hlua_socket_gc(lua_State *L)
1689{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001690 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001691 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001692 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001693
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001694 MAY_LJMP(check_args(L, 1, "__gc"));
1695
1696 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001697 peer = xref_get_peer_and_lock(&socket->xref);
1698 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001699 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001700 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001701
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001702 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001703 appctx->ctx.hlua_cosocket.die = 1;
1704 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001705
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001706 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001707 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001708 return 0;
1709}
1710
1711/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001712 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001713 */
sada05ed3302018-05-11 11:48:18 -07001714__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001715{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001716 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001717 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001718 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001719
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001720 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001721
1722 /* Check if we run on the same thread than the xreator thread.
1723 * We cannot access to the socket if the thread is different.
1724 */
1725 if (socket->tid != tid)
1726 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1727
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001728 peer = xref_get_peer_and_lock(&socket->xref);
1729 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001730 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001731 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001732
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001733 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001734 appctx->ctx.hlua_cosocket.die = 1;
1735 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001736
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001737 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001738 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001739 return 0;
1740}
1741
sada05ed3302018-05-11 11:48:18 -07001742/* The close function calls close_helper.
1743 */
1744__LJMP static int hlua_socket_close(lua_State *L)
1745{
1746 MAY_LJMP(check_args(L, 1, "close"));
1747 return hlua_socket_close_helper(L);
1748}
1749
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001750/* This Lua function assumes that the stack contain three parameters.
1751 * 1 - USERDATA containing a struct socket
1752 * 2 - INTEGER with values of the macro defined below
1753 * If the integer is -1, we must read at most one line.
1754 * If the integer is -2, we ust read all the data until the
1755 * end of the stream.
1756 * If the integer is positive value, we must read a number of
1757 * bytes corresponding to this value.
1758 */
1759#define HLSR_READ_LINE (-1)
1760#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001761__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001762{
1763 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1764 int wanted = lua_tointeger(L, 2);
1765 struct hlua *hlua = hlua_gethlua(L);
1766 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001767 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001768 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02001769 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001770 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02001771 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001772 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001773 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001774 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001775 struct stream_interface *si;
1776 struct stream *s;
1777 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001778 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001779
1780 /* Check if this lua stack is schedulable. */
1781 if (!hlua || !hlua->task)
1782 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1783 "'frontend', 'backend' or 'task'"));
1784
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001785 /* Check if we run on the same thread than the xreator thread.
1786 * We cannot access to the socket if the thread is different.
1787 */
1788 if (socket->tid != tid)
1789 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1790
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001791 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001792 peer = xref_get_peer_and_lock(&socket->xref);
1793 if (!peer)
1794 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001795 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1796 si = appctx->owner;
1797 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001798
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001799 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001800 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001801 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001802 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001803 if (nblk < 0) /* Connection close. */
1804 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001805 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001806 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001807
1808 /* remove final \r\n. */
1809 if (nblk == 1) {
1810 if (blk1[len1-1] == '\n') {
1811 len1--;
1812 skip_at_end++;
1813 if (blk1[len1-1] == '\r') {
1814 len1--;
1815 skip_at_end++;
1816 }
1817 }
1818 }
1819 else {
1820 if (blk2[len2-1] == '\n') {
1821 len2--;
1822 skip_at_end++;
1823 if (blk2[len2-1] == '\r') {
1824 len2--;
1825 skip_at_end++;
1826 }
1827 }
1828 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001829 }
1830
1831 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001832 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001833 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001834 if (nblk < 0) /* Connection close. */
1835 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001836 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001837 goto connection_empty;
1838 }
1839
1840 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001841 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001842 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001843 if (nblk < 0) /* Connection close. */
1844 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001845 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001846 goto connection_empty;
1847
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001848 missing_bytes = wanted - socket->b.n;
1849 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001850 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001851 len1 = missing_bytes;
1852 } if (nblk == 2 && len1 + len2 > missing_bytes)
1853 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001854 }
1855
1856 len = len1;
1857
1858 luaL_addlstring(&socket->b, blk1, len1);
1859 if (nblk == 2) {
1860 len += len2;
1861 luaL_addlstring(&socket->b, blk2, len2);
1862 }
1863
1864 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001865 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001866
1867 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02001868 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001869
1870 /* If the pattern reclaim to read all the data
1871 * in the connection, got out.
1872 */
1873 if (wanted == HLSR_READ_ALL)
1874 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001875 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001876 goto connection_empty;
1877
1878 /* Return result. */
1879 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001880 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001881 return 1;
1882
1883connection_closed:
1884
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001885 xref_unlock(&socket->xref, peer);
1886
1887no_peer:
1888
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001889 /* If the buffer containds data. */
1890 if (socket->b.n > 0) {
1891 luaL_pushresult(&socket->b);
1892 return 1;
1893 }
1894 lua_pushnil(L);
1895 lua_pushstring(L, "connection closed.");
1896 return 2;
1897
1898connection_empty:
1899
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001900 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1901 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001902 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001903 }
1904 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02001905 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001906 return 0;
1907}
1908
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001909/* This Lua function gets two parameters. The first one can be string
1910 * or a number. If the string is "*l", the user requires one line. If
1911 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001912 * If the value is a number, the user require a number of bytes equal
1913 * to the value. The default value is "*l" (a line).
1914 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001915 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001916 * integer takes this values:
1917 * -1 : read a line
1918 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001919 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001920 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001921 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001922 * concatenated with the read data.
1923 */
1924__LJMP static int hlua_socket_receive(struct lua_State *L)
1925{
1926 int wanted = HLSR_READ_LINE;
1927 const char *pattern;
1928 int type;
1929 char *error;
1930 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001931 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001932
1933 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1934 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1935
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001936 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001937
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001938 /* Check if we run on the same thread than the xreator thread.
1939 * We cannot access to the socket if the thread is different.
1940 */
1941 if (socket->tid != tid)
1942 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1943
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001944 /* check for pattern. */
1945 if (lua_gettop(L) >= 2) {
1946 type = lua_type(L, 2);
1947 if (type == LUA_TSTRING) {
1948 pattern = lua_tostring(L, 2);
1949 if (strcmp(pattern, "*a") == 0)
1950 wanted = HLSR_READ_ALL;
1951 else if (strcmp(pattern, "*l") == 0)
1952 wanted = HLSR_READ_LINE;
1953 else {
1954 wanted = strtoll(pattern, &error, 10);
1955 if (*error != '\0')
1956 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1957 }
1958 }
1959 else if (type == LUA_TNUMBER) {
1960 wanted = lua_tointeger(L, 2);
1961 if (wanted < 0)
1962 WILL_LJMP(luaL_error(L, "Unsupported size."));
1963 }
1964 }
1965
1966 /* Set pattern. */
1967 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01001968
1969 /* Check if we would replace the top by itself. */
1970 if (lua_gettop(L) != 2)
1971 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001972
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001973 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001974 luaL_buffinit(L, &socket->b);
1975
1976 /* Check prefix. */
1977 if (lua_gettop(L) >= 3) {
1978 if (lua_type(L, 3) != LUA_TSTRING)
1979 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1980 pattern = lua_tolstring(L, 3, &len);
1981 luaL_addlstring(&socket->b, pattern, len);
1982 }
1983
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001984 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001985}
1986
1987/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08001988 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001989 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001990static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001991{
1992 struct hlua_socket *socket;
1993 struct hlua *hlua = hlua_gethlua(L);
1994 struct appctx *appctx;
1995 size_t buf_len;
1996 const char *buf;
1997 int len;
1998 int send_len;
1999 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002000 struct xref *peer;
2001 struct stream_interface *si;
2002 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002003
2004 /* Check if this lua stack is schedulable. */
2005 if (!hlua || !hlua->task)
2006 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2007 "'frontend', 'backend' or 'task'"));
2008
2009 /* Get object */
2010 socket = MAY_LJMP(hlua_checksocket(L, 1));
2011 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002012 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002013
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002014 /* Check if we run on the same thread than the xreator thread.
2015 * We cannot access to the socket if the thread is different.
2016 */
2017 if (socket->tid != tid)
2018 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2019
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002020 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002021 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002022 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002023 lua_pushinteger(L, -1);
2024 return 1;
2025 }
2026 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2027 si = appctx->owner;
2028 s = si_strm(si);
2029
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002030 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002031 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002032 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002033 lua_pushinteger(L, -1);
2034 return 1;
2035 }
2036
2037 /* Update the input buffer data. */
2038 buf += sent;
2039 send_len = buf_len - sent;
2040
2041 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002042 if (sent >= buf_len) {
2043 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002044 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002045 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002046
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002047 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002048 * the request buffer if its not required.
2049 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002050 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002051 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002052 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002053 }
2054
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002055 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002056 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002057 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002058 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002059 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002060
2061 /* send data */
2062 if (len < send_len)
2063 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002064 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002065
2066 /* "Not enough space" (-1), "Buffer too little to contain
2067 * the data" (-2) are not expected because the available length
2068 * is tested.
2069 * Other unknown error are also not expected.
2070 */
2071 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002072 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002073 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002074
sada05ed3302018-05-11 11:48:18 -07002075 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002076 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002077 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002078 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002079 return 1;
2080 }
2081
2082 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002083 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002084
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002085 s->req.rex = TICK_ETERNITY;
2086 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002087
2088 /* Update length sent. */
2089 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002090 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002091
2092 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002093 if (sent + len >= buf_len) {
2094 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002095 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002096 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002097
2098hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002099 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2100 xref_unlock(&socket->xref, peer);
2101 WILL_LJMP(luaL_error(L, "out of memory"));
2102 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002103 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002104 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002105 return 0;
2106}
2107
2108/* This function initiate the send of data. It just check the input
2109 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002110 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002111 * "hlua_socket_write_yield" that can yield.
2112 *
2113 * The Lua function gets between 3 and 4 parameters. The first one is
2114 * the associated object. The second is a string buffer. The third is
2115 * a facultative integer that represents where is the buffer position
2116 * of the start of the data that can send. The first byte is the
2117 * position "1". The default value is "1". The fourth argument is a
2118 * facultative integer that represents where is the buffer position
2119 * of the end of the data that can send. The default is the last byte.
2120 */
2121static int hlua_socket_send(struct lua_State *L)
2122{
2123 int i;
2124 int j;
2125 const char *buf;
2126 size_t buf_len;
2127
2128 /* Check number of arguments. */
2129 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2130 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2131
2132 /* Get the string. */
2133 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2134
2135 /* Get and check j. */
2136 if (lua_gettop(L) == 4) {
2137 j = MAY_LJMP(luaL_checkinteger(L, 4));
2138 if (j < 0)
2139 j = buf_len + j + 1;
2140 if (j > buf_len)
2141 j = buf_len + 1;
2142 lua_pop(L, 1);
2143 }
2144 else
2145 j = buf_len;
2146
2147 /* Get and check i. */
2148 if (lua_gettop(L) == 3) {
2149 i = MAY_LJMP(luaL_checkinteger(L, 3));
2150 if (i < 0)
2151 i = buf_len + i + 1;
2152 if (i > buf_len)
2153 i = buf_len + 1;
2154 lua_pop(L, 1);
2155 } else
2156 i = 1;
2157
2158 /* Check bth i and j. */
2159 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002160 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002161 return 1;
2162 }
2163 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002164 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002165 return 1;
2166 }
2167 if (i == 0)
2168 i = 1;
2169 if (j == 0)
2170 j = 1;
2171
2172 /* Pop the string. */
2173 lua_pop(L, 1);
2174
2175 /* Update the buffer length. */
2176 buf += i - 1;
2177 buf_len = j - i + 1;
2178 lua_pushlstring(L, buf, buf_len);
2179
2180 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002181 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002182
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002183 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002184}
2185
Willy Tarreau22b0a682015-06-17 19:43:49 +02002186#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002187__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2188{
2189 static char buffer[SOCKET_INFO_MAX_LEN];
2190 int ret;
2191 int len;
2192 char *p;
2193
2194 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2195 if (ret <= 0) {
2196 lua_pushnil(L);
2197 return 1;
2198 }
2199
2200 if (ret == AF_UNIX) {
2201 lua_pushstring(L, buffer+1);
2202 return 1;
2203 }
2204 else if (ret == AF_INET6) {
2205 buffer[0] = '[';
2206 len = strlen(buffer);
2207 buffer[len] = ']';
2208 len++;
2209 buffer[len] = ':';
2210 len++;
2211 p = buffer;
2212 }
2213 else if (ret == AF_INET) {
2214 p = buffer + 1;
2215 len = strlen(p);
2216 p[len] = ':';
2217 len++;
2218 }
2219 else {
2220 lua_pushnil(L);
2221 return 1;
2222 }
2223
2224 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2225 lua_pushnil(L);
2226 return 1;
2227 }
2228
2229 lua_pushstring(L, p);
2230 return 1;
2231}
2232
2233/* Returns information about the peer of the connection. */
2234__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2235{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002236 struct hlua_socket *socket;
2237 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002238 struct xref *peer;
2239 struct appctx *appctx;
2240 struct stream_interface *si;
2241 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002242 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002243
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002244 MAY_LJMP(check_args(L, 1, "getpeername"));
2245
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002246 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002247
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002248 /* Check if we run on the same thread than the xreator thread.
2249 * We cannot access to the socket if the thread is different.
2250 */
2251 if (socket->tid != tid)
2252 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2253
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002254 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002255 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002256 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002257 lua_pushnil(L);
2258 return 1;
2259 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002260 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2261 si = appctx->owner;
2262 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002263
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002264 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002265 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002266 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002267 lua_pushnil(L);
2268 return 1;
2269 }
2270
Willy Tarreaua71f6422016-11-16 17:00:14 +01002271 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002272 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002273 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002274 lua_pushnil(L);
2275 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002276 }
2277
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002278 ret = MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2279 xref_unlock(&socket->xref, peer);
2280 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002281}
2282
2283/* Returns information about my connection side. */
2284static int hlua_socket_getsockname(struct lua_State *L)
2285{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002286 struct hlua_socket *socket;
2287 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002288 struct appctx *appctx;
2289 struct xref *peer;
2290 struct stream_interface *si;
2291 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002292 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002293
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002294 MAY_LJMP(check_args(L, 1, "getsockname"));
2295
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002296 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002297
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002298 /* Check if we run on the same thread than the xreator thread.
2299 * We cannot access to the socket if the thread is different.
2300 */
2301 if (socket->tid != tid)
2302 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2303
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002304 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002305 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002306 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002307 lua_pushnil(L);
2308 return 1;
2309 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002310 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2311 si = appctx->owner;
2312 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002314 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002315 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002316 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002317 lua_pushnil(L);
2318 return 1;
2319 }
2320
Willy Tarreaua71f6422016-11-16 17:00:14 +01002321 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002322 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002323 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002324 lua_pushnil(L);
2325 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002326 }
2327
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002328 ret = hlua_socket_info(L, &conn->addr.from);
2329 xref_unlock(&socket->xref, peer);
2330 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002331}
2332
2333/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002334static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002335 .obj_type = OBJ_TYPE_APPLET,
2336 .name = "<LUA_TCP>",
2337 .fct = hlua_socket_handler,
2338 .release = hlua_socket_release,
2339};
2340
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002341__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002342{
2343 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2344 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002345 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002346 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002347 struct stream_interface *si;
2348 struct stream *s;
2349
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002350 /* Check if we run on the same thread than the xreator thread.
2351 * We cannot access to the socket if the thread is different.
2352 */
2353 if (socket->tid != tid)
2354 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2355
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002356 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002357 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002358 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002359 lua_pushnil(L);
2360 lua_pushstring(L, "Can't connect");
2361 return 2;
2362 }
2363 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2364 si = appctx->owner;
2365 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002366
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002367 /* Check if we run on the same thread than the xreator thread.
2368 * We cannot access to the socket if the thread is different.
2369 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002370 if (socket->tid != tid) {
2371 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002372 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002373 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002374
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002375 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002376 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002377 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002378 lua_pushnil(L);
2379 lua_pushstring(L, "Can't connect");
2380 return 2;
2381 }
2382
Willy Tarreaue09101e2018-10-16 17:37:12 +02002383 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002384
2385 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002386 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002387 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002388 lua_pushinteger(L, 1);
2389 return 1;
2390 }
2391
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002392 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2393 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002394 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002395 }
2396 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002397 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002398 return 0;
2399}
2400
2401/* This function fail or initite the connection. */
2402__LJMP static int hlua_socket_connect(struct lua_State *L)
2403{
2404 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002405 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002406 const char *ip;
2407 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002408 struct hlua *hlua;
2409 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002410 int low, high;
2411 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002412 struct xref *peer;
2413 struct stream_interface *si;
2414 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002415
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002416 if (lua_gettop(L) < 2)
2417 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002418
2419 /* Get args. */
2420 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002421
2422 /* Check if we run on the same thread than the xreator thread.
2423 * We cannot access to the socket if the thread is different.
2424 */
2425 if (socket->tid != tid)
2426 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2427
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002428 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002429 if (lua_gettop(L) >= 3) {
2430 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002431 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002432
Tim Duesterhus6edab862018-01-06 19:04:45 +01002433 /* Force the ip to end with a colon, to support IPv6 addresses
2434 * that are not enclosed within square brackets.
2435 */
2436 if (port > 0) {
2437 luaL_buffinit(L, &b);
2438 luaL_addstring(&b, ip);
2439 luaL_addchar(&b, ':');
2440 luaL_pushresult(&b);
2441 ip = lua_tolstring(L, lua_gettop(L), NULL);
2442 }
2443 }
2444
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002445 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002446 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002447 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002448 lua_pushnil(L);
2449 return 1;
2450 }
2451 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2452 si = appctx->owner;
2453 s = si_strm(si);
2454
2455 /* Initialise connection. */
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002456 conn = cs_conn(si_alloc_cs(&s->si[1], NULL));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002457 if (!conn) {
2458 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002459 WILL_LJMP(luaL_error(L, "connect: internal error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002460 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002461
Willy Tarreau3adac082015-09-26 17:51:09 +02002462 /* needed for the connection not to be closed */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002463 conn->target = s->target;
Willy Tarreau3adac082015-09-26 17:51:09 +02002464
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002465 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002466 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002467 if (!addr) {
2468 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002469 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002470 }
2471 if (low != high) {
2472 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002473 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002474 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002475 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002476
2477 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002478 if (low == 0) {
2479 if (conn->addr.to.ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002480 if (port == -1) {
2481 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002482 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002483 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002484 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2485 } else if (conn->addr.to.ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002486 if (port == -1) {
2487 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002488 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002489 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002490 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2491 }
2492 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002493
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002494 hlua = hlua_gethlua(L);
Willy Tarreaue09101e2018-10-16 17:37:12 +02002495 appctx = __objt_appctx(s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002496
2497 /* inform the stream that we want to be notified whenever the
2498 * connection completes.
2499 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002500 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002501 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002502 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002503
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002504 hlua->flags |= HLUA_MUST_GC;
2505
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002506 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2507 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002508 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002509 }
2510 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002511
2512 task_wakeup(s->task, TASK_WOKEN_INIT);
2513 /* Return yield waiting for connection. */
2514
Willy Tarreau9635e032018-10-16 17:52:55 +02002515 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002516
2517 return 0;
2518}
2519
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002520#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002521__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2522{
2523 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002524 struct xref *peer;
2525 struct appctx *appctx;
2526 struct stream_interface *si;
2527 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002528
2529 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2530 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002531
2532 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002533 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002534 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002535 lua_pushnil(L);
2536 return 1;
2537 }
2538 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2539 si = appctx->owner;
2540 s = si_strm(si);
2541
2542 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002543 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002544 return MAY_LJMP(hlua_socket_connect(L));
2545}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002546#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002547
2548__LJMP static int hlua_socket_setoption(struct lua_State *L)
2549{
2550 return 0;
2551}
2552
2553__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2554{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002555 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002556 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002557 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002558 struct xref *peer;
2559 struct appctx *appctx;
2560 struct stream_interface *si;
2561 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002562
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002563 MAY_LJMP(check_args(L, 2, "settimeout"));
2564
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002565 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002566
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002567 /* convert the timeout to millis */
2568 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002569
Thierry Fournier17a921b2018-03-08 09:59:02 +01002570 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002571 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002572 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2573
Mark Lakes56cc1252018-03-27 09:48:06 +02002574 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002575 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002576
2577 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002578 if (tmout == 0)
2579 tmout++; /* very small timeouts are adjusted to a minium of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002580
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002581 /* Check if we run on the same thread than the xreator thread.
2582 * We cannot access to the socket if the thread is different.
2583 */
2584 if (socket->tid != tid)
2585 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2586
Mark Lakes56cc1252018-03-27 09:48:06 +02002587 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002588 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002589 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002590 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2591 WILL_LJMP(lua_error(L));
2592 return 0;
2593 }
2594 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2595 si = appctx->owner;
2596 s = si_strm(si);
2597
Cyril Bonté7bb63452018-08-17 23:51:02 +02002598 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002599 s->req.rto = tmout;
2600 s->req.wto = tmout;
2601 s->res.rto = tmout;
2602 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002603 s->req.rex = tick_add_ifset(now_ms, tmout);
2604 s->req.wex = tick_add_ifset(now_ms, tmout);
2605 s->res.rex = tick_add_ifset(now_ms, tmout);
2606 s->res.wex = tick_add_ifset(now_ms, tmout);
2607
2608 s->task->expire = tick_add_ifset(now_ms, tmout);
2609 task_queue(s->task);
2610
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002611 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002612
Thierry Fourniere9636f12018-03-08 09:54:32 +01002613 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002614 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002615}
2616
2617__LJMP static int hlua_socket_new(lua_State *L)
2618{
2619 struct hlua_socket *socket;
2620 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002621 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002622 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002623
2624 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002625 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002626 hlua_pusherror(L, "socket: full stack");
2627 goto out_fail_conf;
2628 }
2629
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002630 /* Create the object: obj[0] = userdata. */
2631 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002632 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002633 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002634 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002635 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002636
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002637 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002638 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002639 hlua_pusherror(L, "socket: uninitialized pools.");
2640 goto out_fail_conf;
2641 }
2642
Willy Tarreau87b09662015-04-03 00:22:06 +02002643 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002644 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2645 lua_setmetatable(L, -2);
2646
Willy Tarreaud420a972015-04-06 00:39:18 +02002647 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002648 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002649 if (!appctx) {
2650 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002651 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002652 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002653
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002654 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002655 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002656 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2657 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002658
Willy Tarreaud420a972015-04-06 00:39:18 +02002659 /* Now create a session, task and stream for this applet */
2660 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2661 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002662 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002663 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002664 }
2665
Willy Tarreau87787ac2017-08-28 16:22:54 +02002666 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002667 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002668 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002669 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002670 }
2671
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002672 /* Initialise cross reference between stream and Lua socket object. */
2673 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002674
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002675 /* Configure "right" stream interface. this "si" is used to connect
2676 * and retrieve data from the server. The connection is initialized
2677 * with the "struct server".
2678 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002679 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002680
2681 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002682 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2683 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002684
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002685 return 1;
2686
Willy Tarreaud420a972015-04-06 00:39:18 +02002687 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002688 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002689 out_fail_sess:
2690 appctx_free(appctx);
2691 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002692 WILL_LJMP(lua_error(L));
2693 return 0;
2694}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002695
2696/*
2697 *
2698 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002699 * Class Channel
2700 *
2701 *
2702 */
2703
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002704/* This function is called before the Lua execution. It stores
2705 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002706 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002707static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002708{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002709 c->mode = stream->be->mode;
2710 switch (c->mode) {
2711 case PR_MODE_HTTP:
2712 c->data.http.dir = opt & SMP_OPT_DIR;
2713 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2714 c->data.http.state = stream->txn->req.msg_state;
2715 else
2716 c->data.http.state = stream->txn->rsp.msg_state;
2717 break;
2718 default:
2719 break;
2720 }
2721}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002722
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002723/* This function is called after the Lua execution. it
2724 * returns true if the parser state is consistent, otherwise,
2725 * it return false.
2726 *
2727 * In HTTP mode, the parser state must be in the same state
2728 * or greater when we exit the function. Even if we do a
2729 * control yield. This prevent to break the HTTP message
2730 * from the Lua code.
2731 */
2732static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2733{
2734 if (c->mode != stream->be->mode)
2735 return 0;
2736
2737 switch (c->mode) {
2738 case PR_MODE_HTTP:
2739 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002740 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002741 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2742 return stream->txn->req.msg_state >= c->data.http.state;
2743 else
2744 return stream->txn->rsp.msg_state >= c->data.http.state;
2745 default:
2746 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002747 }
2748 return 1;
2749}
2750
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002751/* Returns the struct hlua_channel join to the class channel in the
2752 * stack entry "ud" or throws an argument error.
2753 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002754__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002755{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002756 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002757}
2758
Willy Tarreau47860ed2015-03-10 14:07:50 +01002759/* Pushes the channel onto the top of the stack. If the stask does not have a
2760 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002761 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002762static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002763{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002764 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002765 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002766 return 0;
2767
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002768 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002769 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002770 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002771
2772 /* Pop a class sesison metatable and affect it to the userdata. */
2773 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2774 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002775 return 1;
2776}
2777
2778/* Duplicate all the data present in the input channel and put it
2779 * in a string LUA variables. Returns -1 and push a nil value in
2780 * the stack if the channel is closed and all the data are consumed,
2781 * returns 0 if no data are available, otherwise it returns the length
2782 * of the builded string.
2783 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002784static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002785{
2786 char *blk1;
2787 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002788 size_t len1;
2789 size_t len2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002790 int ret;
2791 luaL_Buffer b;
2792
Willy Tarreau06d80a92017-10-19 14:32:15 +02002793 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002794 if (unlikely(ret == 0))
2795 return 0;
2796
2797 if (unlikely(ret < 0)) {
2798 lua_pushnil(L);
2799 return -1;
2800 }
2801
2802 luaL_buffinit(L, &b);
2803 luaL_addlstring(&b, blk1, len1);
2804 if (unlikely(ret == 2))
2805 luaL_addlstring(&b, blk2, len2);
2806 luaL_pushresult(&b);
2807
2808 if (unlikely(ret == 2))
2809 return len1 + len2;
2810 return len1;
2811}
2812
2813/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2814 * a yield. This function keep the data in the buffer.
2815 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002816__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002817{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002818 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002819
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002820 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2821
Christopher Faulet3f829a42018-12-13 21:56:45 +01002822 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2823 WILL_LJMP(lua_error(L));
2824
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002825 if (_hlua_channel_dup(chn, L) == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002826 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002827 return 1;
2828}
2829
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002830/* Check arguments for the function "hlua_channel_dup_yield". */
2831__LJMP static int hlua_channel_dup(lua_State *L)
2832{
2833 MAY_LJMP(check_args(L, 1, "dup"));
2834 MAY_LJMP(hlua_checkchannel(L, 1));
2835 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2836}
2837
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002838/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2839 * a yield. This function consumes the data in the buffer. It returns
2840 * a string containing the data or a nil pointer if no data are available
2841 * and the channel is closed.
2842 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002843__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002844{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002845 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002846 int ret;
2847
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002848 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002849
Christopher Faulet3f829a42018-12-13 21:56:45 +01002850 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2851 WILL_LJMP(lua_error(L));
2852
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002853 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002854 if (unlikely(ret == 0))
Willy Tarreau9635e032018-10-16 17:52:55 +02002855 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002856
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002857 if (unlikely(ret == -1))
2858 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002859
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002860 b_sub(&chn->buf, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002861 return 1;
2862}
2863
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002864/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002865__LJMP static int hlua_channel_get(lua_State *L)
2866{
2867 MAY_LJMP(check_args(L, 1, "get"));
2868 MAY_LJMP(hlua_checkchannel(L, 1));
2869 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2870}
2871
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002872/* This functions consumes and returns one line. If the channel is closed,
2873 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002874 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002875 * value.
2876 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002877__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002878{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002879 char *blk1;
2880 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002881 size_t len1;
2882 size_t len2;
2883 size_t len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002884 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002885 int ret;
2886 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002887
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002888 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2889
Christopher Faulet3f829a42018-12-13 21:56:45 +01002890 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2891 WILL_LJMP(lua_error(L));
2892
Willy Tarreau06d80a92017-10-19 14:32:15 +02002893 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002894 if (ret == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002895 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002896
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002897 if (ret == -1) {
2898 lua_pushnil(L);
2899 return 1;
2900 }
2901
2902 luaL_buffinit(L, &b);
2903 luaL_addlstring(&b, blk1, len1);
2904 len = len1;
2905 if (unlikely(ret == 2)) {
2906 luaL_addlstring(&b, blk2, len2);
2907 len += len2;
2908 }
2909 luaL_pushresult(&b);
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002910 b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn) + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002911 return 1;
2912}
2913
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002914/* Check arguments for the function "hlua_channel_getline_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002915__LJMP static int hlua_channel_getline(lua_State *L)
2916{
2917 MAY_LJMP(check_args(L, 1, "getline"));
2918 MAY_LJMP(hlua_checkchannel(L, 1));
2919 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2920}
2921
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002922/* This function takes a string as input, and append it at the
2923 * input side of channel. If the data is too big, but a space
2924 * is probably available after sending some data, the function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002925 * yields. If the data is bigger than the buffer, or if the
2926 * channel is closed, it returns -1. Otherwise, it returns the
2927 * amount of data written.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002928 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002929__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002930{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002931 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002932 size_t len;
2933 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2934 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2935 int ret;
2936 int max;
2937
Christopher Faulet3f829a42018-12-13 21:56:45 +01002938 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2939 WILL_LJMP(lua_error(L));
2940
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002941 /* Check if the buffer is available because HAProxy doesn't allocate
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002942 * the request buffer if its not required.
2943 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002944 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01002945 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02002946 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002947 }
2948
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002949 max = channel_recv_limit(chn) - b_data(&chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002950 if (max > len - l)
2951 max = len - l;
2952
Willy Tarreau06d80a92017-10-19 14:32:15 +02002953 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002954 if (ret == -2 || ret == -3) {
2955 lua_pushinteger(L, -1);
2956 return 1;
2957 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002958 if (ret == -1) {
2959 chn->flags |= CF_WAKE_WRITE;
Willy Tarreau9635e032018-10-16 17:52:55 +02002960 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002961 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002962 l += ret;
2963 lua_pop(L, 1);
2964 lua_pushinteger(L, l);
2965
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002966 max = channel_recv_limit(chn) - b_data(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02002967 if (max == 0 && co_data(chn) == 0) {
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002968 /* There are no space available, and the output buffer is empty.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002969 * in this case, we cannot add more data, so we cannot yield,
2970 * we return the amount of copyied data.
2971 */
2972 return 1;
2973 }
2974 if (l < len)
Willy Tarreau9635e032018-10-16 17:52:55 +02002975 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002976 return 1;
2977}
2978
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002979/* Just a wrapper of "hlua_channel_append_yield". It returns the length
2980 * of the written string, or -1 if the channel is closed or if the
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002981 * buffer size is too little for the data.
2982 */
2983__LJMP static int hlua_channel_append(lua_State *L)
2984{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002985 size_t len;
2986
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002987 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002988 MAY_LJMP(hlua_checkchannel(L, 1));
2989 MAY_LJMP(luaL_checklstring(L, 2, &len));
2990 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002991 lua_pushinteger(L, 0);
2992
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002993 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002994}
2995
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002996/* Just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002997 * his process by cleaning the buffer. The result is a replacement
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002998 * of the current data. It returns the length of the written string,
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002999 * or -1 if the channel is closed or if the buffer size is too
3000 * little for the data.
3001 */
3002__LJMP static int hlua_channel_set(lua_State *L)
3003{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003004 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003005
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003006 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003007 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003008 lua_pushinteger(L, 0);
3009
Christopher Faulet3f829a42018-12-13 21:56:45 +01003010 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
3011 WILL_LJMP(lua_error(L));
3012
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003013 b_set_data(&chn->buf, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003014
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003015 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003016}
3017
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003018/* Append data in the output side of the buffer. This data is immediately
3019 * sent. The function returns the amount of data written. If the buffer
3020 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003021 * if the channel is closed.
3022 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003023__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003024{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003025 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003026 size_t len;
3027 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3028 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3029 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003030 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003031
Christopher Faulet3f829a42018-12-13 21:56:45 +01003032 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
3033 WILL_LJMP(lua_error(L));
3034
Willy Tarreau47860ed2015-03-10 14:07:50 +01003035 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003036 lua_pushinteger(L, -1);
3037 return 1;
3038 }
3039
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003040 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003041 * the request buffer if its not required.
3042 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003043 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01003044 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02003045 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003046 }
3047
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003048 /* The written data will be immediately sent, so we can check
3049 * the available space without taking in account the reserve.
3050 * The reserve is guaranteed for the processing of incoming
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003051 * data, because the buffer will be flushed.
3052 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003053 max = b_room(&chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003054
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003055 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003056 * in this case, we cannot add more data, so we cannot yield,
3057 * we return the amount of copyied data.
3058 */
Willy Tarreaua79021a2018-06-15 18:07:57 +02003059 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003060 return 1;
3061
3062 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003063 if (max > len - l)
3064 max = len - l;
3065
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003066 /* The buffer available size may be not contiguous. This test
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003067 * detects a non contiguous buffer and realign it.
3068 */
Willy Tarreau3f679992018-06-15 15:06:42 +02003069 if (ci_space_for_replace(chn) < max)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003070 channel_slow_realign(chn, trash.area);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003071
3072 /* Copy input data in the buffer. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003073 max = b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn), str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003074
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003075 /* buffer replace considers that the input part is filled.
3076 * so, I must forward these new data in the output part.
3077 */
Willy Tarreaubcbd3932018-06-06 07:13:22 +02003078 c_adv(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003079
3080 l += max;
3081 lua_pop(L, 1);
3082 lua_pushinteger(L, l);
3083
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003084 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003085 * in this case, we cannot add more data, so we cannot yield,
3086 * we return the amount of copyied data.
3087 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003088 max = b_room(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003089 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003090 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003091
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003092 if (l < len) {
3093 /* If we are waiting for space in the response buffer, we
3094 * must set the flag WAKERESWR. This flag required the task
3095 * wake up if any activity is detected on the response buffer.
3096 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003097 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003098 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003099 else
3100 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003101 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003102 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003103
3104 return 1;
3105}
3106
3107/* Just a wraper of "_hlua_channel_send". This wrapper permits
3108 * yield the LUA process, and resume it without checking the
3109 * input arguments.
3110 */
3111__LJMP static int hlua_channel_send(lua_State *L)
3112{
3113 MAY_LJMP(check_args(L, 2, "send"));
3114 lua_pushinteger(L, 0);
3115
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003116 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003117}
3118
3119/* This function forward and amount of butes. The data pass from
3120 * the input side of the buffer to the output side, and can be
3121 * forwarded. This function never fails.
3122 *
3123 * The Lua function takes an amount of bytes to be forwarded in
3124 * imput. It returns the number of bytes forwarded.
3125 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003126__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003127{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003128 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003129 int len;
3130 int l;
3131 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003132 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003133
3134 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003135
3136 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
3137 WILL_LJMP(lua_error(L));
3138
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003139 len = MAY_LJMP(luaL_checkinteger(L, 2));
3140 l = MAY_LJMP(luaL_checkinteger(L, -1));
3141
3142 max = len - l;
Willy Tarreaua79021a2018-06-15 18:07:57 +02003143 if (max > ci_data(chn))
3144 max = ci_data(chn);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003145 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003146 l += max;
3147
3148 lua_pop(L, 1);
3149 lua_pushinteger(L, l);
3150
3151 /* Check if it miss bytes to forward. */
3152 if (l < len) {
3153 /* The the input channel or the output channel are closed, we
3154 * must return the amount of data forwarded.
3155 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003156 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003157 return 1;
3158
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003159 /* If we are waiting for space data in the response buffer, we
3160 * must set the flag WAKERESWR. This flag required the task
3161 * wake up if any activity is detected on the response buffer.
3162 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003163 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003164 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003165 else
3166 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003167
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003168 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003169 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003170 }
3171
3172 return 1;
3173}
3174
3175/* Just check the input and prepare the stack for the previous
3176 * function "hlua_channel_forward_yield"
3177 */
3178__LJMP static int hlua_channel_forward(lua_State *L)
3179{
3180 MAY_LJMP(check_args(L, 2, "forward"));
3181 MAY_LJMP(hlua_checkchannel(L, 1));
3182 MAY_LJMP(luaL_checkinteger(L, 2));
3183
3184 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003185 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003186}
3187
3188/* Just returns the number of bytes available in the input
3189 * side of the buffer. This function never fails.
3190 */
3191__LJMP static int hlua_channel_get_in_len(lua_State *L)
3192{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003193 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003194
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003195 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003196 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003197 if (IS_HTX_STRM(chn_strm(chn))) {
3198 struct htx *htx = htxbuf(&chn->buf);
3199 lua_pushinteger(L, htx->data - co_data(chn));
3200 }
3201 else
3202 lua_pushinteger(L, ci_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003203 return 1;
3204}
3205
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003206/* Returns true if the channel is full. */
3207__LJMP static int hlua_channel_is_full(lua_State *L)
3208{
3209 struct channel *chn;
3210 int rem;
3211
3212 MAY_LJMP(check_args(L, 1, "is_full"));
3213 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3214
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003215 if (IS_HTX_STRM(chn_strm(chn))) {
3216 struct htx *htx = htxbuf(&chn->buf);
3217
3218 rem = htx_free_data_space(htx);
3219 }
3220 else
3221 rem = b_room(&chn->buf);
3222
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003223 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
3224
3225 lua_pushboolean(L, rem <= 0);
3226 return 1;
3227}
3228
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003229/* Just returns the number of bytes available in the output
3230 * side of the buffer. This function never fails.
3231 */
3232__LJMP static int hlua_channel_get_out_len(lua_State *L)
3233{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003234 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003235
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003236 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003237 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003238 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003239 return 1;
3240}
3241
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003242/*
3243 *
3244 *
3245 * Class Fetches
3246 *
3247 *
3248 */
3249
3250/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003251 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003252 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003253__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003254{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003255 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003256}
3257
3258/* This function creates and push in the stack a fetch object according
3259 * with a current TXN.
3260 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003261static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003262{
Willy Tarreau7073c472015-04-06 11:15:40 +02003263 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003264
3265 /* Check stack size. */
3266 if (!lua_checkstack(L, 3))
3267 return 0;
3268
3269 /* Create the object: obj[0] = userdata.
3270 * Note that the base of the Fetches object is the
3271 * transaction object.
3272 */
3273 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003274 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003275 lua_rawseti(L, -2, 0);
3276
Willy Tarreau7073c472015-04-06 11:15:40 +02003277 hsmp->s = txn->s;
3278 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003279 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003280 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003281
3282 /* Pop a class sesison metatable and affect it to the userdata. */
3283 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3284 lua_setmetatable(L, -2);
3285
3286 return 1;
3287}
3288
3289/* This function is an LUA binding. It is called with each sample-fetch.
3290 * It uses closure argument to store the associated sample-fetch. It
3291 * returns only one argument or throws an error. An error is thrown
3292 * only if an error is encountered during the argument parsing. If
3293 * the "sample-fetch" function fails, nil is returned.
3294 */
3295__LJMP static int hlua_run_sample_fetch(lua_State *L)
3296{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003297 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003298 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003299 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003300 int i;
3301 struct sample smp;
3302
3303 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003304 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003305
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003306 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003307 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003308
Thierry FOURNIERca988662015-12-20 18:43:03 +01003309 /* Check execution authorization. */
3310 if (f->use & SMP_USE_HTTP_ANY &&
3311 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3312 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3313 "is not available in Lua services", f->kw);
3314 WILL_LJMP(lua_error(L));
3315 }
3316
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003317 /* Get extra arguments. */
3318 for (i = 0; i < lua_gettop(L) - 1; i++) {
3319 if (i >= ARGM_NBARGS)
3320 break;
3321 hlua_lua2arg(L, i + 2, &args[i]);
3322 }
3323 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003324 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003325
3326 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003327 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003328
3329 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003330 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003331 lua_pushfstring(L, "error in arguments");
3332 WILL_LJMP(lua_error(L));
3333 }
3334
3335 /* Initialise the sample. */
3336 memset(&smp, 0, sizeof(smp));
3337
3338 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003339 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003340 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003341 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003342 lua_pushstring(L, "");
3343 else
3344 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003345 return 1;
3346 }
3347
3348 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003349 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003350 hlua_smp2lua_str(L, &smp);
3351 else
3352 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003353 return 1;
3354}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003355
3356/*
3357 *
3358 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003359 * Class Converters
3360 *
3361 *
3362 */
3363
3364/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003365 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003366 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003367__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003368{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003369 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003370}
3371
3372/* This function creates and push in the stack a Converters object
3373 * according with a current TXN.
3374 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003375static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003376{
Willy Tarreau7073c472015-04-06 11:15:40 +02003377 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003378
3379 /* Check stack size. */
3380 if (!lua_checkstack(L, 3))
3381 return 0;
3382
3383 /* Create the object: obj[0] = userdata.
3384 * Note that the base of the Converters object is the
3385 * same than the TXN object.
3386 */
3387 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003388 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003389 lua_rawseti(L, -2, 0);
3390
Willy Tarreau7073c472015-04-06 11:15:40 +02003391 hsmp->s = txn->s;
3392 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003393 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003394 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003395
Willy Tarreau87b09662015-04-03 00:22:06 +02003396 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003397 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3398 lua_setmetatable(L, -2);
3399
3400 return 1;
3401}
3402
3403/* This function is an LUA binding. It is called with each converter.
3404 * It uses closure argument to store the associated converter. It
3405 * returns only one argument or throws an error. An error is thrown
3406 * only if an error is encountered during the argument parsing. If
3407 * the converter function function fails, nil is returned.
3408 */
3409__LJMP static int hlua_run_sample_conv(lua_State *L)
3410{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003411 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003412 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003413 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003414 int i;
3415 struct sample smp;
3416
3417 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003418 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003419
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003420 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003421 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003422
3423 /* Get extra arguments. */
3424 for (i = 0; i < lua_gettop(L) - 2; i++) {
3425 if (i >= ARGM_NBARGS)
3426 break;
3427 hlua_lua2arg(L, i + 3, &args[i]);
3428 }
3429 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003430 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003431
3432 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003433 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003434
3435 /* Run the special args checker. */
3436 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3437 hlua_pusherror(L, "error in arguments");
3438 WILL_LJMP(lua_error(L));
3439 }
3440
3441 /* Initialise the sample. */
3442 if (!hlua_lua2smp(L, 2, &smp)) {
3443 hlua_pusherror(L, "error in the input argument");
3444 WILL_LJMP(lua_error(L));
3445 }
3446
Willy Tarreau1777ea62016-03-10 16:15:46 +01003447 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3448
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003449 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003450 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003451 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003452 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003453 WILL_LJMP(lua_error(L));
3454 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003455 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3456 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003457 hlua_pusherror(L, "error during the input argument casting");
3458 WILL_LJMP(lua_error(L));
3459 }
3460
3461 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003462 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003463 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003464 lua_pushstring(L, "");
3465 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003466 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003467 return 1;
3468 }
3469
3470 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003471 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003472 hlua_smp2lua_str(L, &smp);
3473 else
3474 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003475 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003476}
3477
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003478/*
3479 *
3480 *
3481 * Class AppletTCP
3482 *
3483 *
3484 */
3485
3486/* Returns a struct hlua_txn if the stack entry "ud" is
3487 * a class stream, otherwise it throws an error.
3488 */
3489__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3490{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003491 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003492}
3493
3494/* This function creates and push in the stack an Applet object
3495 * according with a current TXN.
3496 */
3497static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3498{
3499 struct hlua_appctx *appctx;
3500 struct stream_interface *si = ctx->owner;
3501 struct stream *s = si_strm(si);
3502 struct proxy *p = s->be;
3503
3504 /* Check stack size. */
3505 if (!lua_checkstack(L, 3))
3506 return 0;
3507
3508 /* Create the object: obj[0] = userdata.
3509 * Note that the base of the Converters object is the
3510 * same than the TXN object.
3511 */
3512 lua_newtable(L);
3513 appctx = lua_newuserdata(L, sizeof(*appctx));
3514 lua_rawseti(L, -2, 0);
3515 appctx->appctx = ctx;
3516 appctx->htxn.s = s;
3517 appctx->htxn.p = p;
3518
3519 /* Create the "f" field that contains a list of fetches. */
3520 lua_pushstring(L, "f");
3521 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3522 return 0;
3523 lua_settable(L, -3);
3524
3525 /* Create the "sf" field that contains a list of stringsafe fetches. */
3526 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003527 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003528 return 0;
3529 lua_settable(L, -3);
3530
3531 /* Create the "c" field that contains a list of converters. */
3532 lua_pushstring(L, "c");
3533 if (!hlua_converters_new(L, &appctx->htxn, 0))
3534 return 0;
3535 lua_settable(L, -3);
3536
3537 /* Create the "sc" field that contains a list of stringsafe converters. */
3538 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003539 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003540 return 0;
3541 lua_settable(L, -3);
3542
3543 /* Pop a class stream metatable and affect it to the table. */
3544 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3545 lua_setmetatable(L, -2);
3546
3547 return 1;
3548}
3549
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003550__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3551{
3552 struct hlua_appctx *appctx;
3553 struct stream *s;
3554 const char *name;
3555 size_t len;
3556 struct sample smp;
3557
3558 MAY_LJMP(check_args(L, 3, "set_var"));
3559
3560 /* It is useles to retrieve the stream, but this function
3561 * runs only in a stream context.
3562 */
3563 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3564 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3565 s = appctx->htxn.s;
3566
3567 /* Converts the third argument in a sample. */
3568 hlua_lua2smp(L, 3, &smp);
3569
3570 /* Store the sample in a variable. */
3571 smp_set_owner(&smp, s->be, s->sess, s, 0);
3572 vars_set_by_name(name, len, &smp);
3573 return 0;
3574}
3575
3576__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3577{
3578 struct hlua_appctx *appctx;
3579 struct stream *s;
3580 const char *name;
3581 size_t len;
3582 struct sample smp;
3583
3584 MAY_LJMP(check_args(L, 2, "unset_var"));
3585
3586 /* It is useles to retrieve the stream, but this function
3587 * runs only in a stream context.
3588 */
3589 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3590 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3591 s = appctx->htxn.s;
3592
3593 /* Unset the variable. */
3594 smp_set_owner(&smp, s->be, s->sess, s, 0);
3595 vars_unset_by_name(name, len, &smp);
3596 return 0;
3597}
3598
3599__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3600{
3601 struct hlua_appctx *appctx;
3602 struct stream *s;
3603 const char *name;
3604 size_t len;
3605 struct sample smp;
3606
3607 MAY_LJMP(check_args(L, 2, "get_var"));
3608
3609 /* It is useles to retrieve the stream, but this function
3610 * runs only in a stream context.
3611 */
3612 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3613 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3614 s = appctx->htxn.s;
3615
3616 smp_set_owner(&smp, s->be, s->sess, s, 0);
3617 if (!vars_get_by_name(name, len, &smp)) {
3618 lua_pushnil(L);
3619 return 1;
3620 }
3621
3622 return hlua_smp2lua(L, &smp);
3623}
3624
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003625__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3626{
3627 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3628 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003629 struct hlua *hlua;
3630
3631 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003632 if (!s->hlua)
3633 return 0;
3634 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003635
3636 MAY_LJMP(check_args(L, 2, "set_priv"));
3637
3638 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003639 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003640
3641 /* Get and store new value. */
3642 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3643 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3644
3645 return 0;
3646}
3647
3648__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3649{
3650 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3651 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003652 struct hlua *hlua;
3653
3654 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003655 if (!s->hlua) {
3656 lua_pushnil(L);
3657 return 1;
3658 }
3659 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003660
3661 /* Push configuration index in the stack. */
3662 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3663
3664 return 1;
3665}
3666
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003667/* If expected data not yet available, it returns a yield. This function
3668 * consumes the data in the buffer. It returns a string containing the
3669 * data. This string can be empty.
3670 */
3671__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3672{
3673 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3674 struct stream_interface *si = appctx->appctx->owner;
3675 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003676 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003677 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003678 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003679 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003680
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003681 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003682 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003683
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003684 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003685 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003686 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003687 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003688 }
3689
3690 /* End of data: commit the total strings and return. */
3691 if (ret < 0) {
3692 luaL_pushresult(&appctx->b);
3693 return 1;
3694 }
3695
3696 /* Ensure that the block 2 length is usable. */
3697 if (ret == 1)
3698 len2 = 0;
3699
3700 /* dont check the max length read and dont check. */
3701 luaL_addlstring(&appctx->b, blk1, len1);
3702 luaL_addlstring(&appctx->b, blk2, len2);
3703
3704 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003705 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003706 luaL_pushresult(&appctx->b);
3707 return 1;
3708}
3709
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003710/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003711__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3712{
3713 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3714
3715 /* Initialise the string catenation. */
3716 luaL_buffinit(L, &appctx->b);
3717
3718 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3719}
3720
3721/* If expected data not yet available, it returns a yield. This function
3722 * consumes the data in the buffer. It returns a string containing the
3723 * data. This string can be empty.
3724 */
3725__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3726{
3727 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3728 struct stream_interface *si = appctx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003729 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003730 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003731 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003732 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003733 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003734 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003735
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003736 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003737 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003738
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003739 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003740 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003741 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003742 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003743 }
3744
3745 /* End of data: commit the total strings and return. */
3746 if (ret < 0) {
3747 luaL_pushresult(&appctx->b);
3748 return 1;
3749 }
3750
3751 /* Ensure that the block 2 length is usable. */
3752 if (ret == 1)
3753 len2 = 0;
3754
3755 if (len == -1) {
3756
3757 /* If len == -1, catenate all the data avalaile and
3758 * yield because we want to get all the data until
3759 * the end of data stream.
3760 */
3761 luaL_addlstring(&appctx->b, blk1, len1);
3762 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003763 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003764 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003765 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003766
3767 } else {
3768
3769 /* Copy the fisrt block caping to the length required. */
3770 if (len1 > len)
3771 len1 = len;
3772 luaL_addlstring(&appctx->b, blk1, len1);
3773 len -= len1;
3774
3775 /* Copy the second block. */
3776 if (len2 > len)
3777 len2 = len;
3778 luaL_addlstring(&appctx->b, blk2, len2);
3779 len -= len2;
3780
3781 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003782 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003783
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003784 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003785 if (len > 0) {
3786 lua_pushinteger(L, len);
3787 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003788 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003789 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003790 }
3791
3792 /* return the result. */
3793 luaL_pushresult(&appctx->b);
3794 return 1;
3795 }
3796
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003797 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003798 hlua_pusherror(L, "Lua: internal error");
3799 WILL_LJMP(lua_error(L));
3800 return 0;
3801}
3802
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003803/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003804__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3805{
3806 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3807 int len = -1;
3808
3809 if (lua_gettop(L) > 2)
3810 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3811 if (lua_gettop(L) >= 2) {
3812 len = MAY_LJMP(luaL_checkinteger(L, 2));
3813 lua_pop(L, 1);
3814 }
3815
3816 /* Confirm or set the required length */
3817 lua_pushinteger(L, len);
3818
3819 /* Initialise the string catenation. */
3820 luaL_buffinit(L, &appctx->b);
3821
3822 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3823}
3824
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003825/* Append data in the output side of the buffer. This data is immediately
3826 * sent. The function returns the amount of data written. If the buffer
3827 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003828 * if the channel is closed.
3829 */
3830__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3831{
3832 size_t len;
3833 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3834 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3835 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3836 struct stream_interface *si = appctx->appctx->owner;
3837 struct channel *chn = si_ic(si);
3838 int max;
3839
3840 /* Get the max amount of data which can write as input in the channel. */
3841 max = channel_recv_max(chn);
3842 if (max > (len - l))
3843 max = len - l;
3844
3845 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003846 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003847
3848 /* update counters. */
3849 l += max;
3850 lua_pop(L, 1);
3851 lua_pushinteger(L, l);
3852
3853 /* If some data is not send, declares the situation to the
3854 * applet, and returns a yield.
3855 */
3856 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01003857 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003858 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003859 }
3860
3861 return 1;
3862}
3863
3864/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3865 * yield the LUA process, and resume it without checking the
3866 * input arguments.
3867 */
3868__LJMP static int hlua_applet_tcp_send(lua_State *L)
3869{
3870 MAY_LJMP(check_args(L, 2, "send"));
3871 lua_pushinteger(L, 0);
3872
3873 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3874}
3875
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003876/*
3877 *
3878 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003879 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003880 *
3881 *
3882 */
3883
3884/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003885 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003886 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003887__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003888{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003889 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003890}
3891
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003892/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003893 * according with a current TXN.
3894 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003895static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003896{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003897 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003898 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003899 struct stream_interface *si = ctx->owner;
3900 struct stream *s = si_strm(si);
3901 struct proxy *px = s->be;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003902
3903 /* Check stack size. */
3904 if (!lua_checkstack(L, 3))
3905 return 0;
3906
3907 /* Create the object: obj[0] = userdata.
3908 * Note that the base of the Converters object is the
3909 * same than the TXN object.
3910 */
3911 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003912 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003913 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003914 appctx->appctx = ctx;
3915 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003916 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003917 appctx->htxn.s = s;
3918 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003919
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003920 /* Create the "f" field that contains a list of fetches. */
3921 lua_pushstring(L, "f");
3922 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3923 return 0;
3924 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003925
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003926 /* Create the "sf" field that contains a list of stringsafe fetches. */
3927 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003928 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003929 return 0;
3930 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003931
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003932 /* Create the "c" field that contains a list of converters. */
3933 lua_pushstring(L, "c");
3934 if (!hlua_converters_new(L, &appctx->htxn, 0))
3935 return 0;
3936 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003937
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003938 /* Create the "sc" field that contains a list of stringsafe converters. */
3939 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003940 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003941 return 0;
3942 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003943
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003944 if (IS_HTX_STRM(s)) {
3945 /* HTX version */
3946 struct htx *htx = htxbuf(&s->req.buf);
3947 struct htx_sl *sl = http_find_stline(htx);
3948 struct ist path;
3949 unsigned long long len = 0;
3950 int32_t pos;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003951
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003952 /* Stores the request method. */
3953 lua_pushstring(L, "method");
3954 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
3955 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003956
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003957 /* Stores the http version. */
3958 lua_pushstring(L, "version");
3959 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
3960 lua_settable(L, -3);
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003961
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003962 /* creates an array of headers. hlua_http_get_headers() crates and push
3963 * the array on the top of the stack.
3964 */
3965 lua_pushstring(L, "headers");
3966 htxn.s = s;
3967 htxn.p = px;
3968 htxn.dir = SMP_OPT_DIR_REQ;
3969 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3970 return 0;
3971 lua_settable(L, -3);
3972
3973 path = http_get_path(htx_sl_req_uri(sl));
3974 if (path.ptr) {
3975 char *p, *q, *end;
3976
3977 p = path.ptr;
3978 end = path.ptr + path.len;
3979 q = p;
3980 while (q < end && *q != '?')
3981 q++;
3982
3983 /* Stores the request path. */
3984 lua_pushstring(L, "path");
3985 lua_pushlstring(L, p, q - p);
3986 lua_settable(L, -3);
3987
3988 /* Stores the query string. */
3989 lua_pushstring(L, "qs");
3990 if (*q == '?')
3991 q++;
3992 lua_pushlstring(L, q, end - q);
3993 lua_settable(L, -3);
3994 }
3995
3996 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3997 struct htx_blk *blk = htx_get_blk(htx, pos);
3998 enum htx_blk_type type = htx_get_blk_type(blk);
3999
4000 if (type == HTX_BLK_EOM || type == HTX_BLK_EOD)
4001 break;
4002 if (type == HTX_BLK_DATA)
4003 len += htx_get_blksz(blk);
4004 }
4005 if (htx->extra != ULLONG_MAX)
4006 len += htx->extra;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004007
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004008 /* Stores the request path. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004009 lua_pushstring(L, "length");
4010 lua_pushinteger(L, len);
4011 lua_settable(L, -3);
4012 }
4013 else {
4014 /* Legacy HTTP version */
4015 struct http_txn *txn = s->txn;
4016 const char *path;
4017 const char *end;
4018 const char *p;
4019
4020 /* Stores the request method. */
4021 lua_pushstring(L, "method");
4022 lua_pushlstring(L, ci_head(txn->req.chn), txn->req.sl.rq.m_l);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004023 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004024
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004025 /* Stores the http version. */
4026 lua_pushstring(L, "version");
4027 lua_pushlstring(L, ci_head(txn->req.chn) + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004028 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004029
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004030 /* creates an array of headers. hlua_http_get_headers() crates and push
4031 * the array on the top of the stack.
4032 */
4033 lua_pushstring(L, "headers");
4034 htxn.s = s;
4035 htxn.p = px;
4036 htxn.dir = SMP_OPT_DIR_REQ;
4037 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
4038 return 0;
4039 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004040
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004041 /* Get path and qs */
4042 path = http_txn_get_path(txn);
4043 if (path) {
4044 end = ci_head(txn->req.chn) + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
4045 p = path;
4046 while (p < end && *p != '?')
4047 p++;
4048
4049 /* Stores the request path. */
4050 lua_pushstring(L, "path");
4051 lua_pushlstring(L, path, p - path);
4052 lua_settable(L, -3);
4053
4054 /* Stores the query string. */
4055 lua_pushstring(L, "qs");
4056 if (*p == '?')
4057 p++;
4058 lua_pushlstring(L, p, end - p);
4059 lua_settable(L, -3);
4060 }
4061
4062 /* Stores the request path. */
4063 lua_pushstring(L, "length");
4064 lua_pushinteger(L, txn->req.body_len);
4065 lua_settable(L, -3);
4066 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004067
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004068 /* Create an empty array of HTTP request headers. */
4069 lua_pushstring(L, "response");
4070 lua_newtable(L);
4071 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004072
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004073 /* Pop a class stream metatable and affect it to the table. */
4074 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4075 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004076
4077 return 1;
4078}
4079
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004080__LJMP static int hlua_applet_http_set_var(lua_State *L)
4081{
4082 struct hlua_appctx *appctx;
4083 struct stream *s;
4084 const char *name;
4085 size_t len;
4086 struct sample smp;
4087
4088 MAY_LJMP(check_args(L, 3, "set_var"));
4089
4090 /* It is useles to retrieve the stream, but this function
4091 * runs only in a stream context.
4092 */
4093 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4094 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4095 s = appctx->htxn.s;
4096
4097 /* Converts the third argument in a sample. */
4098 hlua_lua2smp(L, 3, &smp);
4099
4100 /* Store the sample in a variable. */
4101 smp_set_owner(&smp, s->be, s->sess, s, 0);
4102 vars_set_by_name(name, len, &smp);
4103 return 0;
4104}
4105
4106__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4107{
4108 struct hlua_appctx *appctx;
4109 struct stream *s;
4110 const char *name;
4111 size_t len;
4112 struct sample smp;
4113
4114 MAY_LJMP(check_args(L, 2, "unset_var"));
4115
4116 /* It is useles to retrieve the stream, but this function
4117 * runs only in a stream context.
4118 */
4119 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4120 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4121 s = appctx->htxn.s;
4122
4123 /* Unset the variable. */
4124 smp_set_owner(&smp, s->be, s->sess, s, 0);
4125 vars_unset_by_name(name, len, &smp);
4126 return 0;
4127}
4128
4129__LJMP static int hlua_applet_http_get_var(lua_State *L)
4130{
4131 struct hlua_appctx *appctx;
4132 struct stream *s;
4133 const char *name;
4134 size_t len;
4135 struct sample smp;
4136
4137 MAY_LJMP(check_args(L, 2, "get_var"));
4138
4139 /* It is useles to retrieve the stream, but this function
4140 * runs only in a stream context.
4141 */
4142 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4143 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4144 s = appctx->htxn.s;
4145
4146 smp_set_owner(&smp, s->be, s->sess, s, 0);
4147 if (!vars_get_by_name(name, len, &smp)) {
4148 lua_pushnil(L);
4149 return 1;
4150 }
4151
4152 return hlua_smp2lua(L, &smp);
4153}
4154
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004155__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4156{
4157 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4158 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004159 struct hlua *hlua;
4160
4161 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004162 if (!s->hlua)
4163 return 0;
4164 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004165
4166 MAY_LJMP(check_args(L, 2, "set_priv"));
4167
4168 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004169 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004170
4171 /* Get and store new value. */
4172 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4173 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4174
4175 return 0;
4176}
4177
4178__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4179{
4180 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4181 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004182 struct hlua *hlua;
4183
4184 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004185 if (!s->hlua) {
4186 lua_pushnil(L);
4187 return 1;
4188 }
4189 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004190
4191 /* Push configuration index in the stack. */
4192 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4193
4194 return 1;
4195}
4196
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004197__LJMP static void hlua_applet_htx_reply_100_continue(lua_State *L)
4198{
4199 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4200 struct stream_interface *si = appctx->appctx->owner;
4201 struct channel *res = si_ic(si);
4202 struct htx *htx = htx_from_buf(&res->buf);
4203 struct htx_sl *sl;
4204 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
4205 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4206 size_t data;
4207
4208 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4209 ist("HTTP/1.1"), ist("100"), ist("Continue"));
4210 if (!sl)
4211 goto fail;
4212 sl->info.res.status = 100;
4213 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
4214 goto fail;
4215
4216 data = htx->data - co_data(res);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004217 channel_add_input(res, data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004218 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004219 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004220 return;
4221
4222 fail:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004223 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004224 hlua_pusherror(L, "Lua applet http '%s': Failed to create 100-Continue response.\n",
4225 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4226 WILL_LJMP(lua_error(L));
4227}
4228
4229
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004230/* If expected data not yet available, it returns a yield. This function
4231 * consumes the data in the buffer. It returns a string containing the
4232 * data. This string can be empty.
4233 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004234__LJMP static int hlua_applet_htx_getline_yield(lua_State *L, int status, lua_KContext ctx)
4235{
4236 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4237 struct stream_interface *si = appctx->appctx->owner;
4238 struct channel *req = si_oc(si);
4239 struct htx *htx;
4240 struct htx_blk *blk;
4241 size_t count;
4242 int stop = 0;
4243
4244 /* Maybe we cant send a 100-continue ? */
4245 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C)
4246 MAY_LJMP(hlua_applet_htx_reply_100_continue(L));
4247
4248 htx = htx_from_buf(&req->buf);
4249 count = co_data(req);
4250 blk = htx_get_head_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004251
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004252 while (count && !stop && blk) {
4253 enum htx_blk_type type = htx_get_blk_type(blk);
4254 uint32_t sz = htx_get_blksz(blk);
4255 struct ist v;
4256 uint32_t vlen;
4257 char *nl;
4258
Christopher Faulete461e342018-12-18 16:43:35 +01004259 if (type == HTX_BLK_EOM) {
4260 stop = 1;
4261 break;
4262 }
4263
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004264 vlen = sz;
4265 if (vlen > count) {
4266 if (type != HTX_BLK_DATA)
4267 break;
4268 vlen = count;
4269 }
4270
4271 switch (type) {
4272 case HTX_BLK_UNUSED:
4273 break;
4274
4275 case HTX_BLK_DATA:
4276 v = htx_get_blk_value(htx, blk);
4277 v.len = vlen;
4278 nl = istchr(v, '\n');
4279 if (nl != NULL) {
4280 stop = 1;
4281 vlen = nl - v.ptr + 1;
4282 }
4283 luaL_addlstring(&appctx->b, v.ptr, vlen);
4284 break;
4285
4286 case HTX_BLK_EOD:
4287 case HTX_BLK_TLR:
4288 case HTX_BLK_EOM:
4289 stop = 1;
4290 break;
4291
4292 default:
4293 break;
4294 }
4295
4296 co_set_data(req, co_data(req) - vlen);
4297 count -= vlen;
4298 if (sz == vlen)
4299 blk = htx_remove_blk(htx, blk);
4300 else {
4301 htx_cut_data_blk(htx, blk, vlen);
4302 break;
4303 }
4304 }
4305
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004306 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004307 if (!stop) {
4308 si_cant_get(si);
4309 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_getline_yield, TICK_ETERNITY, 0));
4310 }
4311
4312 /* return the result. */
4313 luaL_pushresult(&appctx->b);
4314 return 1;
4315}
4316
4317
4318/* If expected data not yet available, it returns a yield. This function
4319 * consumes the data in the buffer. It returns a string containing the
4320 * data. This string can be empty.
4321 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004322__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004323{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004324 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4325 struct stream_interface *si = appctx->appctx->owner;
4326 struct channel *chn = si_ic(si);
4327 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004328 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004329 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004330 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004331 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004332
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004333 /* Maybe we cant send a 100-continue ? */
4334 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02004335 ret = ci_putblk(chn, HTTP_100.ptr, HTTP_100.len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004336 /* if ret == -2 or -3 the channel closed or the message si too
4337 * big for the buffers. We cant send anything. So, we ignoring
4338 * the error, considers that the 100-continue is sent, and try
4339 * to receive.
4340 * If ret is -1, we dont have room in the buffer, so we yield.
4341 */
4342 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004343 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004344 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004345 }
4346 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4347 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004348
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004349 /* Check for the end of the data. */
4350 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4351 luaL_pushresult(&appctx->b);
4352 return 1;
4353 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004354
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004355 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004356 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004357
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004358 /* Data not yet available. return yield. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004359 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004360 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004361 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004362 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004363
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004364 /* End of data: commit the total strings and return. */
4365 if (ret < 0) {
4366 luaL_pushresult(&appctx->b);
4367 return 1;
4368 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004369
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004370 /* Ensure that the block 2 length is usable. */
4371 if (ret == 1)
4372 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004373
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004374 /* Copy the fisrt block caping to the length required. */
4375 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4376 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4377 luaL_addlstring(&appctx->b, blk1, len1);
4378 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004379
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004380 /* Copy the second block. */
4381 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4382 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4383 luaL_addlstring(&appctx->b, blk2, len2);
4384 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004385
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004386 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004387 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004388 luaL_pushresult(&appctx->b);
4389 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004390}
4391
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004392/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004393__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004394{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004395 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004396
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004397 /* Initialise the string catenation. */
4398 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004399
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004400 if (IS_HTX_STRM(si_strm(appctx->appctx->owner)))
4401 return MAY_LJMP(hlua_applet_htx_getline_yield(L, 0, 0));
4402 else
4403 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004404}
4405
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004406/* If expected data not yet available, it returns a yield. This function
4407 * consumes the data in the buffer. It returns a string containing the
4408 * data. This string can be empty.
4409 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004410__LJMP static int hlua_applet_htx_recv_yield(lua_State *L, int status, lua_KContext ctx)
4411{
4412 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4413 struct stream_interface *si = appctx->appctx->owner;
4414 struct channel *req = si_oc(si);
4415 struct htx *htx;
4416 struct htx_blk *blk;
4417 size_t count;
4418 int len;
4419
4420 /* Maybe we cant send a 100-continue ? */
4421 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C)
4422 MAY_LJMP(hlua_applet_htx_reply_100_continue(L));
4423
4424 htx = htx_from_buf(&req->buf);
4425 len = MAY_LJMP(luaL_checkinteger(L, 2));
4426 count = co_data(req);
4427 blk = htx_get_head_blk(htx);
4428 while (count && len && blk) {
4429 enum htx_blk_type type = htx_get_blk_type(blk);
4430 uint32_t sz = htx_get_blksz(blk);
4431 struct ist v;
4432 uint32_t vlen;
4433
Christopher Faulete461e342018-12-18 16:43:35 +01004434 if (type == HTX_BLK_EOM) {
4435 len = 0;
4436 break;
4437 }
4438
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004439 vlen = sz;
4440 if (len > 0 && vlen > len)
4441 vlen = len;
4442 if (vlen > count) {
4443 if (type != HTX_BLK_DATA)
4444 break;
4445 vlen = count;
4446 }
4447
4448 switch (type) {
4449 case HTX_BLK_UNUSED:
4450 break;
4451
4452 case HTX_BLK_DATA:
4453 v = htx_get_blk_value(htx, blk);
4454 luaL_addlstring(&appctx->b, v.ptr, vlen);
4455 break;
4456
4457 case HTX_BLK_EOD:
4458 case HTX_BLK_TLR:
4459 case HTX_BLK_EOM:
4460 len = 0;
4461 break;
4462
4463 default:
4464 break;
4465 }
4466
4467 co_set_data(req, co_data(req) - vlen);
4468 count -= vlen;
4469 if (len > 0)
4470 len -= vlen;
4471 if (sz == vlen)
4472 blk = htx_remove_blk(htx, blk);
4473 else {
4474 htx_cut_data_blk(htx, blk, vlen);
4475 break;
4476 }
4477 }
4478
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004479 htx_to_buf(htx, &req->buf);
4480
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004481 /* If we are no other data available, yield waiting for new data. */
4482 if (len) {
4483 if (len > 0) {
4484 lua_pushinteger(L, len);
4485 lua_replace(L, 2);
4486 }
4487 si_cant_get(si);
4488 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_recv_yield, TICK_ETERNITY, 0));
4489 }
4490
4491 /* return the result. */
4492 luaL_pushresult(&appctx->b);
4493 return 1;
4494}
4495
4496/* If expected data not yet available, it returns a yield. This function
4497 * consumes the data in the buffer. It returns a string containing the
4498 * data. This string can be empty.
4499 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004500__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004501{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004502 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4503 struct stream_interface *si = appctx->appctx->owner;
4504 int len = MAY_LJMP(luaL_checkinteger(L, 2));
4505 struct channel *chn = si_ic(si);
4506 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004507 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004508 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004509 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004510 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004511
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004512 /* Maybe we cant send a 100-continue ? */
4513 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02004514 ret = ci_putblk(chn, HTTP_100.ptr, HTTP_100.len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004515 /* if ret == -2 or -3 the channel closed or the message si too
4516 * big for the buffers. We cant send anything. So, we ignoring
4517 * the error, considers that the 100-continue is sent, and try
4518 * to receive.
4519 * If ret is -1, we dont have room in the buffer, so we yield.
4520 */
4521 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004522 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004523 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004524 }
4525 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4526 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004527
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004528 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004529 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004530
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004531 /* Data not yet available. return yield. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004532 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004533 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004534 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004535 }
4536
4537 /* End of data: commit the total strings and return. */
4538 if (ret < 0) {
4539 luaL_pushresult(&appctx->b);
4540 return 1;
4541 }
4542
4543 /* Ensure that the block 2 length is usable. */
4544 if (ret == 1)
4545 len2 = 0;
4546
4547 /* Copy the fisrt block caping to the length required. */
4548 if (len1 > len)
4549 len1 = len;
4550 luaL_addlstring(&appctx->b, blk1, len1);
4551 len -= len1;
4552
4553 /* Copy the second block. */
4554 if (len2 > len)
4555 len2 = len;
4556 luaL_addlstring(&appctx->b, blk2, len2);
4557 len -= len2;
4558
4559 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004560 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004561 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4562 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4563
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004564 /* If we are no other data available, yield waiting for new data. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004565 if (len > 0) {
4566 lua_pushinteger(L, len);
4567 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004568 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004569 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004570 }
4571
4572 /* return the result. */
4573 luaL_pushresult(&appctx->b);
4574 return 1;
4575}
4576
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004577/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004578__LJMP static int hlua_applet_http_recv(lua_State *L)
4579{
4580 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4581 int len = -1;
4582
4583 /* Check arguments. */
4584 if (lua_gettop(L) > 2)
4585 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4586 if (lua_gettop(L) >= 2) {
4587 len = MAY_LJMP(luaL_checkinteger(L, 2));
4588 lua_pop(L, 1);
4589 }
4590
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004591 if (IS_HTX_STRM(si_strm(appctx->appctx->owner))) {
4592 /* HTX version */
4593 lua_pushinteger(L, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004594
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004595 /* Initialise the string catenation. */
4596 luaL_buffinit(L, &appctx->b);
4597
4598 return MAY_LJMP(hlua_applet_htx_recv_yield(L, 0, 0));
4599 }
4600 else {
4601 /* Legacy HTTP version */
4602 /* Check the required length */
4603 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4604 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4605 lua_pushinteger(L, len);
4606
4607 /* Initialise the string catenation. */
4608 luaL_buffinit(L, &appctx->b);
4609
4610 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4611 }
4612}
4613
4614/* Append data in the output side of the buffer. This data is immediately
4615 * sent. The function returns the amount of data written. If the buffer
4616 * cannot contain the data, the function yields. The function returns -1
4617 * if the channel is closed.
4618 */
4619__LJMP static int hlua_applet_htx_send_yield(lua_State *L, int status, lua_KContext ctx)
4620{
4621 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4622 struct stream_interface *si = appctx->appctx->owner;
4623 struct channel *res = si_ic(si);
4624 struct htx *htx = htx_from_buf(&res->buf);
4625 const char *data;
4626 size_t len;
4627 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4628 int max;
4629
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004630 max = channel_htx_recv_max(res, htx);
4631 if (!max)
4632 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004633
4634 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
4635
4636 /* Get the max amount of data which can write as input in the channel. */
4637 if (max > (len - l))
4638 max = len - l;
4639
4640 /* Copy data. */
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004641 if (!htx_add_data(htx, ist2(data + l, max)))
4642 goto snd_yield;
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004643 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004644
4645 /* update counters. */
4646 l += max;
4647 lua_pop(L, 1);
4648 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004649
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004650 /* If some data is not send, declares the situation to the
4651 * applet, and returns a yield.
4652 */
4653 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004654 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004655 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004656 si_rx_room_blk(si);
4657 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_send_yield, TICK_ETERNITY, 0));
4658 }
4659
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004660 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004661 return 1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004662}
4663
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004664/* Append data in the output side of the buffer. This data is immediately
4665 * sent. The function returns the amount of data written. If the buffer
4666 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004667 * if the channel is closed.
4668 */
4669__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4670{
4671 size_t len;
4672 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4673 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4674 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4675 struct stream_interface *si = appctx->appctx->owner;
4676 struct channel *chn = si_ic(si);
4677 int max;
4678
4679 /* Get the max amount of data which can write as input in the channel. */
4680 max = channel_recv_max(chn);
4681 if (max > (len - l))
4682 max = len - l;
4683
4684 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004685 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004686
4687 /* update counters. */
4688 l += max;
4689 lua_pop(L, 1);
4690 lua_pushinteger(L, l);
4691
4692 /* If some data is not send, declares the situation to the
4693 * applet, and returns a yield.
4694 */
4695 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004696 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004697 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004698 }
4699
4700 return 1;
4701}
4702
4703/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4704 * yield the LUA process, and resume it without checking the
4705 * input arguments.
4706 */
4707__LJMP static int hlua_applet_http_send(lua_State *L)
4708{
4709 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004710
4711 /* We want to send some data. Headers must be sent. */
4712 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4713 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4714 WILL_LJMP(lua_error(L));
4715 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004716
4717 if (IS_HTX_STRM(si_strm(appctx->appctx->owner))) {
4718 /* HTX version */
4719 /* This interger is used for followinf the amount of data sent. */
4720 lua_pushinteger(L, 0);
4721
4722 return MAY_LJMP(hlua_applet_htx_send_yield(L, 0, 0));
4723 }
4724 else {
4725 /* Legacy HTTP version */
4726 size_t len;
4727 char hex[10];
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004728
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004729 MAY_LJMP(luaL_checklstring(L, 2, &len));
4730
4731 /* If transfer encoding chunked is selected, we surround the data
4732 * by chunk data.
4733 */
4734 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4735 snprintf(hex, 9, "%x", (unsigned int)len);
4736 lua_pushfstring(L, "%s\r\n", hex);
4737 lua_insert(L, 2); /* swap the last 2 entries. */
4738 lua_pushstring(L, "\r\n");
4739 lua_concat(L, 3);
4740 }
4741
4742 /* This interger is used for followinf the amount of data sent. */
4743 lua_pushinteger(L, 0);
4744
4745 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4746 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004747}
4748
4749__LJMP static int hlua_applet_http_addheader(lua_State *L)
4750{
4751 const char *name;
4752 int ret;
4753
4754 MAY_LJMP(hlua_checkapplet_http(L, 1));
4755 name = MAY_LJMP(luaL_checkstring(L, 2));
4756 MAY_LJMP(luaL_checkstring(L, 3));
4757
4758 /* Push in the stack the "response" entry. */
4759 ret = lua_getfield(L, 1, "response");
4760 if (ret != LUA_TTABLE) {
4761 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4762 "is expected as an array. %s found", lua_typename(L, ret));
4763 WILL_LJMP(lua_error(L));
4764 }
4765
4766 /* check if the header is already registered if it is not
4767 * the case, register it.
4768 */
4769 ret = lua_getfield(L, -1, name);
4770 if (ret == LUA_TNIL) {
4771
4772 /* Entry not found. */
4773 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4774
4775 /* Insert the new header name in the array in the top of the stack.
4776 * It left the new array in the top of the stack.
4777 */
4778 lua_newtable(L);
4779 lua_pushvalue(L, 2);
4780 lua_pushvalue(L, -2);
4781 lua_settable(L, -4);
4782
4783 } else if (ret != LUA_TTABLE) {
4784
4785 /* corruption error. */
4786 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4787 "is expected as an array. %s found", name, lua_typename(L, ret));
4788 WILL_LJMP(lua_error(L));
4789 }
4790
4791 /* Now the top od thestack is an array of values. We push
4792 * the header value as new entry.
4793 */
4794 lua_pushvalue(L, 3);
4795 ret = lua_rawlen(L, -2);
4796 lua_rawseti(L, -2, ret + 1);
4797 lua_pushboolean(L, 1);
4798 return 1;
4799}
4800
4801__LJMP static int hlua_applet_http_status(lua_State *L)
4802{
4803 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4804 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004805 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004806
4807 if (status < 100 || status > 599) {
4808 lua_pushboolean(L, 0);
4809 return 1;
4810 }
4811
4812 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004813 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004814 lua_pushboolean(L, 1);
4815 return 1;
4816}
4817
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004818
4819__LJMP static int hlua_applet_htx_send_response(lua_State *L)
4820{
4821 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4822 struct stream_interface *si = appctx->appctx->owner;
4823 struct channel *res = si_ic(si);
4824 struct htx *htx;
4825 struct htx_sl *sl;
4826 struct h1m h1m;
4827 const char *status, *reason;
4828 const char *name, *value;
4829 size_t nlen, vlen;
4830 unsigned int flags;
4831
4832 /* Send the message at once. */
4833 htx = htx_from_buf(&res->buf);
4834 h1m_init_res(&h1m);
4835
4836 /* Use the same http version than the request. */
4837 status = ultoa_r(appctx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
4838 reason = appctx->appctx->ctx.hlua_apphttp.reason;
4839 if (reason == NULL)
4840 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
4841 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
4842 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
4843 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
4844 }
4845 else {
4846 flags = HTX_SL_F_IS_RESP;
4847 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
4848 }
4849 if (!sl) {
4850 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
4851 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4852 WILL_LJMP(lua_error(L));
4853 }
4854 sl->info.res.status = appctx->appctx->ctx.hlua_apphttp.status;
4855
4856 /* Get the array associated to the field "response" in the object AppletHTTP. */
4857 lua_pushvalue(L, 0);
4858 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4859 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4860 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4861 WILL_LJMP(lua_error(L));
4862 }
4863
4864 /* Browse the list of headers. */
4865 lua_pushnil(L);
4866 while(lua_next(L, -2) != 0) {
4867 /* We expect a string as -2. */
4868 if (lua_type(L, -2) != LUA_TSTRING) {
4869 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4870 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4871 lua_typename(L, lua_type(L, -2)));
4872 WILL_LJMP(lua_error(L));
4873 }
4874 name = lua_tolstring(L, -2, &nlen);
4875
4876 /* We expect an array as -1. */
4877 if (lua_type(L, -1) != LUA_TTABLE) {
4878 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4879 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4880 name,
4881 lua_typename(L, lua_type(L, -1)));
4882 WILL_LJMP(lua_error(L));
4883 }
4884
4885 /* Browse the table who is on the top of the stack. */
4886 lua_pushnil(L);
4887 while(lua_next(L, -2) != 0) {
4888 int id;
4889
4890 /* We expect a number as -2. */
4891 if (lua_type(L, -2) != LUA_TNUMBER) {
4892 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4893 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4894 name,
4895 lua_typename(L, lua_type(L, -2)));
4896 WILL_LJMP(lua_error(L));
4897 }
4898 id = lua_tointeger(L, -2);
4899
4900 /* We expect a string as -2. */
4901 if (lua_type(L, -1) != LUA_TSTRING) {
4902 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4903 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4904 name, id,
4905 lua_typename(L, lua_type(L, -1)));
4906 WILL_LJMP(lua_error(L));
4907 }
4908 value = lua_tolstring(L, -1, &vlen);
4909
4910 /* Simple Protocol checks. */
4911 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
4912 h1_parse_xfer_enc_header(&h1m, ist2(name, nlen));
4913 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
4914 struct ist v = ist2(value, vlen);
4915 int ret;
4916
4917 ret = h1_parse_cont_len_header(&h1m, &v);
4918 if (ret < 0) {
4919 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
4920 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4921 name);
4922 WILL_LJMP(lua_error(L));
4923 }
4924 else if (ret == 0)
4925 goto next; /* Skip it */
4926 }
4927
4928 /* Add a new header */
4929 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
4930 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
4931 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4932 name);
4933 WILL_LJMP(lua_error(L));
4934 }
4935 next:
4936 /* Remove the array from the stack, and get next element with a remaining string. */
4937 lua_pop(L, 1);
4938 }
4939
4940 /* Remove the array from the stack, and get next element with a remaining string. */
4941 lua_pop(L, 1);
4942 }
4943
4944 if (h1m.flags & H1_MF_CHNK)
4945 h1m.flags &= ~H1_MF_CLEN;
4946 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
4947 h1m.flags |= H1_MF_XFER_LEN;
4948
4949 /* Uset HTX start-line flags */
4950 if (h1m.flags & H1_MF_XFER_ENC)
4951 flags |= HTX_SL_F_XFER_ENC;
4952 if (h1m.flags & H1_MF_XFER_LEN) {
4953 flags |= HTX_SL_F_XFER_LEN;
4954 if (h1m.flags & H1_MF_CHNK)
4955 flags |= HTX_SL_F_CHNK;
4956 else if (h1m.flags & H1_MF_CLEN)
4957 flags |= HTX_SL_F_CLEN;
4958 if (h1m.body_len == 0)
4959 flags |= HTX_SL_F_BODYLESS;
4960 }
4961 sl->flags |= flags;
4962
4963 /* If we dont have a content-length set, and the HTTP version is 1.1
4964 * and the status code implies the presence of a message body, we must
4965 * announce a transfer encoding chunked. This is required by haproxy
4966 * for the keepalive compliance. If the applet annouces a transfer-encoding
4967 * chunked itslef, don't do anything.
4968 */
4969 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
4970 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4971 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4972 appctx->appctx->ctx.hlua_apphttp.status != 304) {
4973 /* Add a new header */
4974 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
4975 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
4976 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
4977 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4978 WILL_LJMP(lua_error(L));
4979 }
4980 }
4981
4982 /* Finalize headers. */
4983 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
4984 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
4985 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4986 WILL_LJMP(lua_error(L));
4987 }
4988
4989 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
4990 b_reset(&res->buf);
4991 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4992 WILL_LJMP(lua_error(L));
4993 }
4994
4995 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004996 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004997
4998 /* Headers sent, set the flag. */
4999 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
5000 return 0;
5001
5002}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005003/* We will build the status line and the headers of the HTTP response.
5004 * We will try send at once if its not possible, we give back the hand
5005 * waiting for more room.
5006 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005007__LJMP static int hlua_applet_htx_start_response_yield(lua_State *L, int status, lua_KContext ctx)
5008{
5009 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5010 struct stream_interface *si = appctx->appctx->owner;
5011 struct channel *res = si_ic(si);
5012
5013 if (co_data(res)) {
5014 si_rx_room_blk(si);
5015 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_start_response_yield, TICK_ETERNITY, 0));
5016 }
5017 return MAY_LJMP(hlua_applet_htx_send_response(L));
5018}
5019
5020
5021__LJMP static int hlua_applet_htx_start_response(lua_State *L)
5022{
5023 return MAY_LJMP(hlua_applet_htx_start_response_yield(L, 0, 0));
5024}
5025
5026/* We will build the status line and the headers of the HTTP response.
5027 * We will try send at once if its not possible, we give back the hand
5028 * waiting for more room.
5029 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005030__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
5031{
5032 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5033 struct stream_interface *si = appctx->appctx->owner;
5034 struct channel *chn = si_ic(si);
5035 int ret;
5036 size_t len;
5037 const char *msg;
5038
5039 /* Get the message as the first argument on the stack. */
5040 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
5041
5042 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02005043 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005044
5045 /* if ret == -2 or -3 the channel closed or the message si too
5046 * big for the buffers.
5047 */
5048 if (ret == -2 || ret == -3) {
5049 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5050 WILL_LJMP(lua_error(L));
5051 }
5052
5053 /* If ret is -1, we dont have room in the buffer, so we yield. */
5054 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01005055 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005056 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005057 }
5058
5059 /* Headers sent, set the flag. */
5060 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
5061 return 0;
5062}
5063
5064__LJMP static int hlua_applet_http_start_response(lua_State *L)
5065{
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005066 struct buffer *tmp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005067 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005068 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02005069 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005070 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02005071 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005072 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005073 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005074 int hdr_chunked = 0;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005075 const char *reason;
5076
5077 if (IS_HTX_STRM(si_strm(appctx->appctx->owner)))
5078 return MAY_LJMP(hlua_applet_htx_start_response(L));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005079
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005080 reason = appctx->appctx->ctx.hlua_apphttp.reason;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005081 if (reason == NULL)
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02005082 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005083
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005084 tmp = get_trash_chunk();
5085
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005086 /* Use the same http version than the request. */
5087 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01005088 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005089 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005090 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005091
5092 /* Get the array associated to the field "response" in the object AppletHTTP. */
5093 lua_pushvalue(L, 0);
5094 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5095 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
5096 appctx->appctx->rule->arg.hlua_rule->fcn.name);
5097 WILL_LJMP(lua_error(L));
5098 }
5099
5100 /* Browse the list of headers. */
5101 lua_pushnil(L);
5102 while(lua_next(L, -2) != 0) {
5103
5104 /* We expect a string as -2. */
5105 if (lua_type(L, -2) != LUA_TSTRING) {
5106 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
5107 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5108 lua_typename(L, lua_type(L, -2)));
5109 WILL_LJMP(lua_error(L));
5110 }
Willy Tarreaua3294632017-08-23 11:24:47 +02005111 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005112
5113 /* We expect an array as -1. */
5114 if (lua_type(L, -1) != LUA_TTABLE) {
5115 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
5116 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5117 name,
5118 lua_typename(L, lua_type(L, -1)));
5119 WILL_LJMP(lua_error(L));
5120 }
5121
5122 /* Browse the table who is on the top of the stack. */
5123 lua_pushnil(L);
5124 while(lua_next(L, -2) != 0) {
5125
5126 /* We expect a number as -2. */
5127 if (lua_type(L, -2) != LUA_TNUMBER) {
5128 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
5129 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5130 name,
5131 lua_typename(L, lua_type(L, -2)));
5132 WILL_LJMP(lua_error(L));
5133 }
5134 id = lua_tointeger(L, -2);
5135
5136 /* We expect a string as -2. */
5137 if (lua_type(L, -1) != LUA_TSTRING) {
5138 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
5139 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5140 name, id,
5141 lua_typename(L, lua_type(L, -1)));
5142 WILL_LJMP(lua_error(L));
5143 }
Willy Tarreaua3294632017-08-23 11:24:47 +02005144 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005145
5146 /* Catenate a new header. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005147 if (tmp->data + name_len + 2 + value_len + 2 < tmp->size) {
5148 memcpy(tmp->area + tmp->data, name, name_len);
5149 tmp->data += name_len;
5150 tmp->area[tmp->data++] = ':';
5151 tmp->area[tmp->data++] = ' ';
Willy Tarreaua3294632017-08-23 11:24:47 +02005152
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005153 memcpy(tmp->area + tmp->data, value,
5154 value_len);
5155 tmp->data += value_len;
5156 tmp->area[tmp->data++] = '\r';
5157 tmp->area[tmp->data++] = '\n';
Willy Tarreaua3294632017-08-23 11:24:47 +02005158 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005159
5160 /* Protocol checks. */
5161
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005162 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005163 * is done without control. If it contains a bad value,
5164 * the content-length remains negative so that we can
5165 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005166 */
Willy Tarreaua3294632017-08-23 11:24:47 +02005167 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005168 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005169
5170 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02005171 if (name_len == 17 && value_len == 7 &&
5172 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005173 strcasecmp("chunked", value) == 0)
5174 hdr_chunked = 1;
5175
5176 /* Remove the array from the stack, and get next element with a remaining string. */
5177 lua_pop(L, 1);
5178 }
5179
5180 /* Remove the array from the stack, and get next element with a remaining string. */
5181 lua_pop(L, 1);
5182 }
5183
Willy Tarreau06c75fe2017-08-23 09:10:38 +02005184 /* If we dont have a content-length set, and the HTTP version is 1.1
5185 * and the status code implies the presence of a message body, we must
5186 * announce a transfer encoding chunked. This is required by haproxy
5187 * for the keepalive compliance. If the applet annouces a transfer-encoding
5188 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005189 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005190 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02005191 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
5192 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
5193 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
5194 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005195 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
5196 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
5197 }
5198
5199 /* Finalize headers. */
5200 chunk_appendf(tmp, "\r\n");
5201
5202 /* Remove the last entry and the array of headers */
5203 lua_pop(L, 2);
5204
5205 /* Push the headers block. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005206 lua_pushlstring(L, tmp->area, tmp->data);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005207
5208 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
5209}
5210
5211/*
5212 *
5213 *
5214 * Class HTTP
5215 *
5216 *
5217 */
5218
5219/* Returns a struct hlua_txn if the stack entry "ud" is
5220 * a class stream, otherwise it throws an error.
5221 */
5222__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
5223{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005224 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005225}
5226
5227/* This function creates and push in the stack a HTTP object
5228 * according with a current TXN.
5229 */
5230static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5231{
5232 struct hlua_txn *htxn;
5233
5234 /* Check stack size. */
5235 if (!lua_checkstack(L, 3))
5236 return 0;
5237
5238 /* Create the object: obj[0] = userdata.
5239 * Note that the base of the Converters object is the
5240 * same than the TXN object.
5241 */
5242 lua_newtable(L);
5243 htxn = lua_newuserdata(L, sizeof(*htxn));
5244 lua_rawseti(L, -2, 0);
5245
5246 htxn->s = txn->s;
5247 htxn->p = txn->p;
5248
5249 /* Pop a class stream metatable and affect it to the table. */
5250 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5251 lua_setmetatable(L, -2);
5252
5253 return 1;
5254}
5255
5256/* This function creates ans returns an array of HTTP headers.
5257 * This function does not fails. It is used as wrapper with the
5258 * 2 following functions.
5259 */
5260__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5261{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005262 /* Create the table. */
5263 lua_newtable(L);
5264
5265 if (!htxn->s->txn)
5266 return 1;
5267
Christopher Faulet724a12c2018-12-13 22:12:15 +01005268 if (IS_HTX_STRM(htxn->s)) {
5269 /* HTX version */
5270 struct htx *htx = htxbuf(&msg->chn->buf);
5271 int32_t pos;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005272
Christopher Faulet724a12c2018-12-13 22:12:15 +01005273 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5274 struct htx_blk *blk = htx_get_blk(htx, pos);
5275 enum htx_blk_type type = htx_get_blk_type(blk);
5276 struct ist n, v;
5277 int len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005278
Christopher Faulet724a12c2018-12-13 22:12:15 +01005279 if (type == HTX_BLK_HDR) {
5280 n = htx_get_blk_name(htx,blk);
5281 v = htx_get_blk_value(htx, blk);
5282 }
5283 else if (type == HTX_BLK_EOH)
5284 break;
5285 else
5286 continue;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005287
Christopher Faulet724a12c2018-12-13 22:12:15 +01005288 /* Check for existing entry:
5289 * assume that the table is on the top of the stack, and
5290 * push the key in the stack, the function lua_gettable()
5291 * perform the lookup.
5292 */
5293 lua_pushlstring(L, n.ptr, n.len);
5294 lua_gettable(L, -2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005295
Christopher Faulet724a12c2018-12-13 22:12:15 +01005296 switch (lua_type(L, -1)) {
5297 case LUA_TNIL:
5298 /* Table not found, create it. */
5299 lua_pop(L, 1); /* remove the nil value. */
5300 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5301 lua_newtable(L); /* create and push empty table. */
5302 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5303 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5304 lua_rawset(L, -3); /* index new table with header name (pop the values). */
5305 break;
5306
5307 case LUA_TTABLE:
5308 /* Entry found: push the value in the table. */
5309 len = lua_rawlen(L, -1);
5310 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5311 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5312 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5313 break;
5314
5315 default:
5316 /* Other cases are errors. */
5317 hlua_pusherror(L, "internal error during the parsing of headers.");
5318 WILL_LJMP(lua_error(L));
5319 }
5320 }
5321 }
5322 else {
5323 /* Legacy HTTP version */
5324 const char *cur_ptr, *cur_next, *p;
5325 int old_idx, cur_idx;
5326 struct hdr_idx_elem *cur_hdr;
5327 const char *hn, *hv;
5328 int hnl, hvl;
5329 const char *in;
5330 char *out;
5331 int len;
5332
5333 /* Build array of headers. */
5334 old_idx = 0;
5335 cur_next = ci_head(msg->chn) + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
5336
5337 while (1) {
5338 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
5339 if (!cur_idx)
5340 break;
5341 old_idx = cur_idx;
5342
5343 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
5344 cur_ptr = cur_next;
5345 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
5346
5347 /* Now we have one full header at cur_ptr of len cur_hdr->len,
5348 * and the next header starts at cur_next. We'll check
5349 * this header in the list as well as against the default
5350 * rule.
5351 */
5352
5353 /* look for ': *'. */
5354 hn = cur_ptr;
5355 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
5356 if (p >= cur_ptr+cur_hdr->len)
5357 continue;
5358 hnl = p - hn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005359 p++;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005360 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
5361 p++;
5362 if (p >= cur_ptr+cur_hdr->len)
5363 continue;
5364 hv = p;
5365 hvl = cur_ptr+cur_hdr->len-p;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005366
Christopher Faulet724a12c2018-12-13 22:12:15 +01005367 /* Lowercase the key. Don't check the size of trash, it have
5368 * the size of one buffer and the input data contains in one
5369 * buffer.
5370 */
5371 out = trash.area;
5372 for (in=hn; in<hn+hnl; in++, out++)
5373 *out = tolower(*in);
5374 *out = '\0';
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005375
Christopher Faulet724a12c2018-12-13 22:12:15 +01005376 /* Check for existing entry:
5377 * assume that the table is on the top of the stack, and
5378 * push the key in the stack, the function lua_gettable()
5379 * perform the lookup.
5380 */
5381 lua_pushlstring(L, trash.area, hnl);
5382 lua_gettable(L, -2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005383
Christopher Faulet724a12c2018-12-13 22:12:15 +01005384 switch (lua_type(L, -1)) {
5385 case LUA_TNIL:
5386 /* Table not found, create it. */
5387 lua_pop(L, 1); /* remove the nil value. */
5388 lua_pushlstring(L, trash.area, hnl); /* push the header name as key. */
5389 lua_newtable(L); /* create and push empty table. */
5390 lua_pushlstring(L, hv, hvl); /* push header value. */
5391 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5392 lua_rawset(L, -3); /* index new table with header name (pop the values). */
5393 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005394
Christopher Faulet724a12c2018-12-13 22:12:15 +01005395 case LUA_TTABLE:
5396 /* Entry found: push the value in the table. */
5397 len = lua_rawlen(L, -1);
5398 lua_pushlstring(L, hv, hvl); /* push header value. */
5399 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5400 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5401 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005402
Christopher Faulet724a12c2018-12-13 22:12:15 +01005403 default:
5404 /* Other cases are errors. */
5405 hlua_pusherror(L, "internal error during the parsing of headers.");
5406 WILL_LJMP(lua_error(L));
5407 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005408 }
5409 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005410 return 1;
5411}
5412
5413__LJMP static int hlua_http_req_get_headers(lua_State *L)
5414{
5415 struct hlua_txn *htxn;
5416
5417 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5418 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5419
5420 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
5421}
5422
5423__LJMP static int hlua_http_res_get_headers(lua_State *L)
5424{
5425 struct hlua_txn *htxn;
5426
5427 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5428 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5429
5430 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
5431}
5432
5433/* This function replace full header, or just a value in
5434 * the request or in the response. It is a wrapper fir the
5435 * 4 following functions.
5436 */
5437__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
5438 struct http_msg *msg, int action)
5439{
5440 size_t name_len;
5441 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5442 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5443 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
5444 struct my_regex re;
5445
5446 if (!regex_comp(reg, &re, 1, 1, NULL))
5447 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5448
5449 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
5450 regex_free(&re);
5451 return 0;
5452}
5453
5454__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5455{
5456 struct hlua_txn *htxn;
5457
5458 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5459 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5460
5461 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
5462}
5463
5464__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5465{
5466 struct hlua_txn *htxn;
5467
5468 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5469 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5470
5471 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
5472}
5473
5474__LJMP static int hlua_http_req_rep_val(lua_State *L)
5475{
5476 struct hlua_txn *htxn;
5477
5478 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5479 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5480
5481 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
5482}
5483
5484__LJMP static int hlua_http_res_rep_val(lua_State *L)
5485{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005486 struct hlua_txn *htxn;
5487
5488 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5489 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5490
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02005491 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005492}
5493
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005494/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005495 * It is a wrapper for the 2 following functions.
5496 */
5497__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5498{
5499 size_t len;
5500 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005501
Christopher Faulet724a12c2018-12-13 22:12:15 +01005502 if (IS_HTX_STRM(htxn->s)) {
5503 /* HTX version */
5504 struct htx *htx = htxbuf(&msg->chn->buf);
5505 struct http_hdr_ctx ctx;
5506
5507 ctx.blk = NULL;
5508 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5509 http_remove_header(htx, &ctx);
5510 }
5511 else {
5512 /* Legacy HTTP version */
5513 struct hdr_ctx ctx;
5514 struct http_txn *txn = htxn->s->txn;
5515
5516 ctx.idx = 0;
5517 while (http_find_header2(name, len, ci_head(msg->chn), &txn->hdr_idx, &ctx))
5518 http_remove_header2(msg, &txn->hdr_idx, &ctx);
5519 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005520 return 0;
5521}
5522
5523__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5524{
5525 struct hlua_txn *htxn;
5526
5527 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5528 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5529
Willy Tarreaueee5b512015-04-03 23:46:31 +02005530 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005531}
5532
5533__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5534{
5535 struct hlua_txn *htxn;
5536
5537 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5538 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5539
Willy Tarreaueee5b512015-04-03 23:46:31 +02005540 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005541}
5542
5543/* This function adds an header. It is a wrapper used by
5544 * the 2 following functions.
5545 */
5546__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5547{
5548 size_t name_len;
5549 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5550 size_t value_len;
5551 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
5552 char *p;
5553
Christopher Faulet724a12c2018-12-13 22:12:15 +01005554 if (IS_HTX_STRM(htxn->s)) {
5555 /* HTX version */
5556 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005557
Christopher Faulet724a12c2018-12-13 22:12:15 +01005558 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5559 ist2(value, value_len)));
5560 }
5561 else {
5562 /* Legacy HTTP version */
5563 /* Check length. */
5564 trash.data = value_len + name_len + 2;
5565 if (trash.data > trash.size)
5566 return 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005567
Christopher Faulet724a12c2018-12-13 22:12:15 +01005568 /* Creates the header string. */
5569 p = trash.area;
5570 memcpy(p, name, name_len);
5571 p += name_len;
5572 *p = ':';
5573 p++;
5574 *p = ' ';
5575 p++;
5576 memcpy(p, value, value_len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005577
Christopher Faulet724a12c2018-12-13 22:12:15 +01005578 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
5579 trash.area, trash.data) != 0);
5580 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005581 return 0;
5582}
5583
5584__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5585{
5586 struct hlua_txn *htxn;
5587
5588 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5589 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5590
Willy Tarreaueee5b512015-04-03 23:46:31 +02005591 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005592}
5593
5594__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5595{
5596 struct hlua_txn *htxn;
5597
5598 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5599 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5600
Willy Tarreaueee5b512015-04-03 23:46:31 +02005601 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005602}
5603
5604static int hlua_http_req_set_hdr(lua_State *L)
5605{
5606 struct hlua_txn *htxn;
5607
5608 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5609 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5610
Willy Tarreaueee5b512015-04-03 23:46:31 +02005611 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
5612 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005613}
5614
5615static int hlua_http_res_set_hdr(lua_State *L)
5616{
5617 struct hlua_txn *htxn;
5618
5619 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5620 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5621
Willy Tarreaueee5b512015-04-03 23:46:31 +02005622 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
5623 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005624}
5625
5626/* This function set the method. */
5627static int hlua_http_req_set_meth(lua_State *L)
5628{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005629 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005630 size_t name_len;
5631 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005632
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005633 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005634 return 1;
5635}
5636
5637/* This function set the method. */
5638static int hlua_http_req_set_path(lua_State *L)
5639{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005640 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005641 size_t name_len;
5642 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005643
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005644 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005645 return 1;
5646}
5647
5648/* This function set the query-string. */
5649static int hlua_http_req_set_query(lua_State *L)
5650{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005651 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005652 size_t name_len;
5653 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005654
5655 /* Check length. */
5656 if (name_len > trash.size - 1) {
5657 lua_pushboolean(L, 0);
5658 return 1;
5659 }
5660
5661 /* Add the mark question as prefix. */
5662 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005663 trash.area[trash.data++] = '?';
5664 memcpy(trash.area + trash.data, name, name_len);
5665 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005666
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005667 lua_pushboolean(L,
5668 http_replace_req_line(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005669 return 1;
5670}
5671
5672/* This function set the uri. */
5673static int hlua_http_req_set_uri(lua_State *L)
5674{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005675 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005676 size_t name_len;
5677 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005678
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005679 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005680 return 1;
5681}
5682
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005683/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005684static int hlua_http_res_set_status(lua_State *L)
5685{
5686 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5687 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005688 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005689
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005690 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005691 return 0;
5692}
5693
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005694/*
5695 *
5696 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005697 * Class TXN
5698 *
5699 *
5700 */
5701
5702/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005703 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005704 */
5705__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5706{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005707 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005708}
5709
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005710__LJMP static int hlua_set_var(lua_State *L)
5711{
5712 struct hlua_txn *htxn;
5713 const char *name;
5714 size_t len;
5715 struct sample smp;
5716
5717 MAY_LJMP(check_args(L, 3, "set_var"));
5718
5719 /* It is useles to retrieve the stream, but this function
5720 * runs only in a stream context.
5721 */
5722 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5723 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5724
5725 /* Converts the third argument in a sample. */
5726 hlua_lua2smp(L, 3, &smp);
5727
5728 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005729 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005730 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005731 return 0;
5732}
5733
Christopher Faulet85d79c92016-11-09 16:54:56 +01005734__LJMP static int hlua_unset_var(lua_State *L)
5735{
5736 struct hlua_txn *htxn;
5737 const char *name;
5738 size_t len;
5739 struct sample smp;
5740
5741 MAY_LJMP(check_args(L, 2, "unset_var"));
5742
5743 /* It is useles to retrieve the stream, but this function
5744 * runs only in a stream context.
5745 */
5746 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5747 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5748
5749 /* Unset the variable. */
5750 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5751 vars_unset_by_name(name, len, &smp);
5752 return 0;
5753}
5754
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005755__LJMP static int hlua_get_var(lua_State *L)
5756{
5757 struct hlua_txn *htxn;
5758 const char *name;
5759 size_t len;
5760 struct sample smp;
5761
5762 MAY_LJMP(check_args(L, 2, "get_var"));
5763
5764 /* It is useles to retrieve the stream, but this function
5765 * runs only in a stream context.
5766 */
5767 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5768 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5769
Willy Tarreau7560dd42016-03-10 16:28:58 +01005770 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005771 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005772 lua_pushnil(L);
5773 return 1;
5774 }
5775
5776 return hlua_smp2lua(L, &smp);
5777}
5778
Willy Tarreau59551662015-03-10 14:23:13 +01005779__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005780{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005781 struct hlua *hlua;
5782
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005783 MAY_LJMP(check_args(L, 2, "set_priv"));
5784
Willy Tarreau87b09662015-04-03 00:22:06 +02005785 /* It is useles to retrieve the stream, but this function
5786 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005787 */
5788 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005789 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005790
5791 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005792 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005793
5794 /* Get and store new value. */
5795 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5796 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5797
5798 return 0;
5799}
5800
Willy Tarreau59551662015-03-10 14:23:13 +01005801__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005802{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005803 struct hlua *hlua;
5804
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005805 MAY_LJMP(check_args(L, 1, "get_priv"));
5806
Willy Tarreau87b09662015-04-03 00:22:06 +02005807 /* It is useles to retrieve the stream, but this function
5808 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005809 */
5810 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005811 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005812
5813 /* Push configuration index in the stack. */
5814 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5815
5816 return 1;
5817}
5818
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005819/* Create stack entry containing a class TXN. This function
5820 * return 0 if the stack does not contains free slots,
5821 * otherwise it returns 1.
5822 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005823static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005824{
Willy Tarreaude491382015-04-06 11:04:28 +02005825 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005826
5827 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005828 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005829 return 0;
5830
5831 /* NOTE: The allocation never fails. The failure
5832 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005833 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005834 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005835 /* Create the object: obj[0] = userdata. */
5836 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005837 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005838 lua_rawseti(L, -2, 0);
5839
Willy Tarreaude491382015-04-06 11:04:28 +02005840 htxn->s = s;
5841 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005842 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005843 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005844
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005845 /* Create the "f" field that contains a list of fetches. */
5846 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005847 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005848 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005849 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005850
5851 /* Create the "sf" field that contains a list of stringsafe fetches. */
5852 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005853 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005854 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005855 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005856
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005857 /* Create the "c" field that contains a list of converters. */
5858 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005859 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005860 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005861 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005862
5863 /* Create the "sc" field that contains a list of stringsafe converters. */
5864 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005865 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005866 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005867 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005868
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005869 /* Create the "req" field that contains the request channel object. */
5870 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005871 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005872 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005873 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005874
5875 /* Create the "res" field that contains the response channel object. */
5876 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005877 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005878 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005879 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005880
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005881 /* Creates the HTTP object is the current proxy allows http. */
5882 lua_pushstring(L, "http");
5883 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005884 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005885 return 0;
5886 }
5887 else
5888 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005889 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005890
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005891 /* Pop a class sesison metatable and affect it to the userdata. */
5892 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5893 lua_setmetatable(L, -2);
5894
5895 return 1;
5896}
5897
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005898__LJMP static int hlua_txn_deflog(lua_State *L)
5899{
5900 const char *msg;
5901 struct hlua_txn *htxn;
5902
5903 MAY_LJMP(check_args(L, 2, "deflog"));
5904 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5905 msg = MAY_LJMP(luaL_checkstring(L, 2));
5906
5907 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5908 return 0;
5909}
5910
5911__LJMP static int hlua_txn_log(lua_State *L)
5912{
5913 int level;
5914 const char *msg;
5915 struct hlua_txn *htxn;
5916
5917 MAY_LJMP(check_args(L, 3, "log"));
5918 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5919 level = MAY_LJMP(luaL_checkinteger(L, 2));
5920 msg = MAY_LJMP(luaL_checkstring(L, 3));
5921
5922 if (level < 0 || level >= NB_LOG_LEVELS)
5923 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5924
5925 hlua_sendlog(htxn->s->be, level, msg);
5926 return 0;
5927}
5928
5929__LJMP static int hlua_txn_log_debug(lua_State *L)
5930{
5931 const char *msg;
5932 struct hlua_txn *htxn;
5933
5934 MAY_LJMP(check_args(L, 2, "Debug"));
5935 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5936 msg = MAY_LJMP(luaL_checkstring(L, 2));
5937 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5938 return 0;
5939}
5940
5941__LJMP static int hlua_txn_log_info(lua_State *L)
5942{
5943 const char *msg;
5944 struct hlua_txn *htxn;
5945
5946 MAY_LJMP(check_args(L, 2, "Info"));
5947 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5948 msg = MAY_LJMP(luaL_checkstring(L, 2));
5949 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5950 return 0;
5951}
5952
5953__LJMP static int hlua_txn_log_warning(lua_State *L)
5954{
5955 const char *msg;
5956 struct hlua_txn *htxn;
5957
5958 MAY_LJMP(check_args(L, 2, "Warning"));
5959 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5960 msg = MAY_LJMP(luaL_checkstring(L, 2));
5961 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5962 return 0;
5963}
5964
5965__LJMP static int hlua_txn_log_alert(lua_State *L)
5966{
5967 const char *msg;
5968 struct hlua_txn *htxn;
5969
5970 MAY_LJMP(check_args(L, 2, "Alert"));
5971 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5972 msg = MAY_LJMP(luaL_checkstring(L, 2));
5973 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5974 return 0;
5975}
5976
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005977__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5978{
5979 struct hlua_txn *htxn;
5980 int ll;
5981
5982 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5983 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5984 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5985
5986 if (ll < 0 || ll > 7)
5987 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5988
5989 htxn->s->logs.level = ll;
5990 return 0;
5991}
5992
5993__LJMP static int hlua_txn_set_tos(lua_State *L)
5994{
5995 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005996 int tos;
5997
5998 MAY_LJMP(check_args(L, 2, "set_tos"));
5999 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6000 tos = MAY_LJMP(luaL_checkinteger(L, 2));
6001
Willy Tarreau1a18b542018-12-11 16:37:42 +01006002 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006003 return 0;
6004}
6005
6006__LJMP static int hlua_txn_set_mark(lua_State *L)
6007{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006008 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006009 int mark;
6010
6011 MAY_LJMP(check_args(L, 2, "set_mark"));
6012 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6013 mark = MAY_LJMP(luaL_checkinteger(L, 2));
6014
Willy Tarreau1a18b542018-12-11 16:37:42 +01006015 conn_set_tos(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006016 return 0;
6017}
6018
Patrick Hemmer268a7072018-05-11 12:52:31 -04006019__LJMP static int hlua_txn_set_priority_class(lua_State *L)
6020{
6021 struct hlua_txn *htxn;
6022
6023 MAY_LJMP(check_args(L, 2, "set_priority_class"));
6024 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6025 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
6026 return 0;
6027}
6028
6029__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
6030{
6031 struct hlua_txn *htxn;
6032
6033 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
6034 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6035 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
6036 return 0;
6037}
6038
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006039/* This function is an Lua binding that send pending data
6040 * to the client, and close the stream interface.
6041 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006042__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006043{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006044 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006045 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01006046 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006047
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006048 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006049 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006050 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006051
Thierry FOURNIERab00df62016-07-14 11:42:37 +02006052 /* If the flags NOTERM is set, we cannot terminate the http
6053 * session, so we just end the execution of the current
6054 * lua code.
6055 */
6056 if (htxn->flags & HLUA_TXN_NOTERM) {
6057 WILL_LJMP(hlua_done(L));
6058 return 0;
6059 }
6060
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006061 ic = &htxn->s->req;
6062 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01006063
Willy Tarreau630ef452015-08-28 10:06:15 +02006064 if (htxn->s->txn) {
6065 /* HTTP mode, let's stay in sync with the stream */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02006066 b_del(&ic->buf, htxn->s->txn->req.sov);
Willy Tarreau630ef452015-08-28 10:06:15 +02006067 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
6068 htxn->s->txn->req.sov = 0;
6069 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
6070 oc->analysers = AN_RES_HTTP_XFER_BODY;
6071 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
6072 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
6073
Willy Tarreau630ef452015-08-28 10:06:15 +02006074 /* Note that if we want to support keep-alive, we need
6075 * to bypass the close/shutr_now calls below, but that
6076 * may only be done if the HTTP request was already
6077 * processed and the connection header is known (ie
6078 * not during TCP rules).
6079 */
6080 }
6081
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02006082 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01006083 channel_abort(ic);
6084 channel_auto_close(ic);
6085 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02006086
6087 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01006088 channel_auto_read(oc);
6089 channel_auto_close(oc);
6090 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006091
Willy Tarreau0458b082015-08-28 09:40:04 +02006092 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006093
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006094 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006095 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006096 return 0;
6097}
6098
6099__LJMP static int hlua_log(lua_State *L)
6100{
6101 int level;
6102 const char *msg;
6103
6104 MAY_LJMP(check_args(L, 2, "log"));
6105 level = MAY_LJMP(luaL_checkinteger(L, 1));
6106 msg = MAY_LJMP(luaL_checkstring(L, 2));
6107
6108 if (level < 0 || level >= NB_LOG_LEVELS)
6109 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
6110
6111 hlua_sendlog(NULL, level, msg);
6112 return 0;
6113}
6114
6115__LJMP static int hlua_log_debug(lua_State *L)
6116{
6117 const char *msg;
6118
6119 MAY_LJMP(check_args(L, 1, "debug"));
6120 msg = MAY_LJMP(luaL_checkstring(L, 1));
6121 hlua_sendlog(NULL, LOG_DEBUG, msg);
6122 return 0;
6123}
6124
6125__LJMP static int hlua_log_info(lua_State *L)
6126{
6127 const char *msg;
6128
6129 MAY_LJMP(check_args(L, 1, "info"));
6130 msg = MAY_LJMP(luaL_checkstring(L, 1));
6131 hlua_sendlog(NULL, LOG_INFO, msg);
6132 return 0;
6133}
6134
6135__LJMP static int hlua_log_warning(lua_State *L)
6136{
6137 const char *msg;
6138
6139 MAY_LJMP(check_args(L, 1, "warning"));
6140 msg = MAY_LJMP(luaL_checkstring(L, 1));
6141 hlua_sendlog(NULL, LOG_WARNING, msg);
6142 return 0;
6143}
6144
6145__LJMP static int hlua_log_alert(lua_State *L)
6146{
6147 const char *msg;
6148
6149 MAY_LJMP(check_args(L, 1, "alert"));
6150 msg = MAY_LJMP(luaL_checkstring(L, 1));
6151 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006152 return 0;
6153}
6154
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006155__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006156{
6157 int wakeup_ms = lua_tointeger(L, -1);
6158 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02006159 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006160 return 0;
6161}
6162
6163__LJMP static int hlua_sleep(lua_State *L)
6164{
6165 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006166 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006167
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006168 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006169
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006170 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006171 wakeup_ms = tick_add(now_ms, delay);
6172 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006173
Willy Tarreau9635e032018-10-16 17:52:55 +02006174 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006175 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006176}
6177
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006178__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006179{
6180 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006181 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006182
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006183 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006184
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006185 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006186 wakeup_ms = tick_add(now_ms, delay);
6187 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006188
Willy Tarreau9635e032018-10-16 17:52:55 +02006189 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006190 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006191}
6192
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006193/* This functionis an LUA binding. it permits to give back
6194 * the hand at the HAProxy scheduler. It is used when the
6195 * LUA processing consumes a lot of time.
6196 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006197__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006198{
6199 return 0;
6200}
6201
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006202__LJMP static int hlua_yield(lua_State *L)
6203{
Willy Tarreau9635e032018-10-16 17:52:55 +02006204 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006205 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006206}
6207
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006208/* This function change the nice of the currently executed
6209 * task. It is used set low or high priority at the current
6210 * task.
6211 */
Willy Tarreau59551662015-03-10 14:23:13 +01006212__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006213{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006214 struct hlua *hlua;
6215 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006216
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006217 MAY_LJMP(check_args(L, 1, "set_nice"));
6218 hlua = hlua_gethlua(L);
6219 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006220
6221 /* If he task is not set, I'm in a start mode. */
6222 if (!hlua || !hlua->task)
6223 return 0;
6224
6225 if (nice < -1024)
6226 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006227 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006228 nice = 1024;
6229
6230 hlua->task->nice = nice;
6231 return 0;
6232}
6233
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006234/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006235 * HAProxy task subsystem when the task is awaked. The LUA runtime can
6236 * return an E_AGAIN signal, the emmiter of this signal must set a
6237 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006238 *
6239 * Task wrapper are longjmp safe because the only one Lua code
6240 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006241 */
Olivier Houchard9f6af332018-05-25 14:04:04 +02006242static struct task *hlua_process_task(struct task *task, void *context, unsigned short state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006243{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006244 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006245 enum hlua_exec status;
6246
Christopher Faulet5bc99722018-04-25 10:34:45 +02006247 if (task->thread_mask == MAX_THREADS_MASK)
6248 task_set_affinity(task, tid_bit);
6249
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006250 /* If it is the first call to the task, we must initialize the
6251 * execution timeouts.
6252 */
6253 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006254 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006255
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006256 /* Execute the Lua code. */
6257 status = hlua_ctx_resume(hlua, 1);
6258
6259 switch (status) {
6260 /* finished or yield */
6261 case HLUA_E_OK:
6262 hlua_ctx_destroy(hlua);
6263 task_delete(task);
6264 task_free(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02006265 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006266 break;
6267
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006268 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01006269 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02006270 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006271 break;
6272
6273 /* finished with error. */
6274 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006275 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006276 hlua_ctx_destroy(hlua);
6277 task_delete(task);
6278 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006279 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006280 break;
6281
6282 case HLUA_E_ERR:
6283 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006284 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006285 hlua_ctx_destroy(hlua);
6286 task_delete(task);
6287 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006288 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006289 break;
6290 }
Emeric Brun253e53e2017-10-17 18:58:40 +02006291 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006292}
6293
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006294/* This function is an LUA binding that register LUA function to be
6295 * executed after the HAProxy configuration parsing and before the
6296 * HAProxy scheduler starts. This function expect only one LUA
6297 * argument that is a function. This function returns nothing, but
6298 * throws if an error is encountered.
6299 */
6300__LJMP static int hlua_register_init(lua_State *L)
6301{
6302 struct hlua_init_function *init;
6303 int ref;
6304
6305 MAY_LJMP(check_args(L, 1, "register_init"));
6306
6307 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6308
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006309 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006310 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006311 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006312
6313 init->function_ref = ref;
6314 LIST_ADDQ(&hlua_init_functions, &init->l);
6315 return 0;
6316}
6317
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006318/* This functio is an LUA binding. It permits to register a task
6319 * executed in parallel of the main HAroxy activity. The task is
6320 * created and it is set in the HAProxy scheduler. It can be called
6321 * from the "init" section, "post init" or during the runtime.
6322 *
6323 * Lua prototype:
6324 *
6325 * <none> core.register_task(<function>)
6326 */
6327static int hlua_register_task(lua_State *L)
6328{
6329 struct hlua *hlua;
6330 struct task *task;
6331 int ref;
6332
6333 MAY_LJMP(check_args(L, 1, "register_task"));
6334
6335 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6336
Willy Tarreaubafbe012017-11-24 17:34:44 +01006337 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006338 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006339 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006340
Emeric Brunc60def82017-09-27 14:59:38 +02006341 task = task_new(MAX_THREADS_MASK);
Willy Tarreaue09101e2018-10-16 17:37:12 +02006342 if (!task)
6343 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
6344
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006345 task->context = hlua;
6346 task->process = hlua_process_task;
6347
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006348 if (!hlua_ctx_init(hlua, task, 1))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006349 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006350
6351 /* Restore the function in the stack. */
6352 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
6353 hlua->nargs = 0;
6354
6355 /* Schedule task. */
6356 task_schedule(task, now_ms);
6357
6358 return 0;
6359}
6360
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006361/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
6362 * doesn't allow "yield" functions because the HAProxy engine cannot
6363 * resume converters.
6364 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006365static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006366{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006367 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006368 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006369 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006370
Willy Tarreaube508f12016-03-10 11:47:01 +01006371 if (!stream)
6372 return 0;
6373
Willy Tarreau87b09662015-04-03 00:22:06 +02006374 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006375 * Lua context can be not initialized. This behavior
6376 * permits to save performances because a systematic
6377 * Lua initialization cause 5% performances loss.
6378 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006379 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006380 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006381 if (!stream->hlua) {
6382 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6383 return 0;
6384 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006385 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006386 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6387 return 0;
6388 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006389 }
6390
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006391 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006392 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006393
6394 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006395 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6396 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6397 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006398 else
6399 error = "critical error";
6400 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006401 return 0;
6402 }
6403
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006404 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006405 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006406 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006407 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006408 return 0;
6409 }
6410
6411 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006412 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006413
6414 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006415 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006416 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006417 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006418 return 0;
6419 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006420 hlua_smp2lua(stream->hlua->T, smp);
6421 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006422
6423 /* push keywords in the stack. */
6424 if (arg_p) {
6425 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006426 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006427 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006428 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006429 return 0;
6430 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006431 hlua_arg2lua(stream->hlua->T, arg_p);
6432 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006433 }
6434 }
6435
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006436 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006437 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006438
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006439 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006440 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006441 }
6442
6443 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006444 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006445 /* finished. */
6446 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006447 /* If the stack is empty, the function fails. */
6448 if (lua_gettop(stream->hlua->T) <= 0)
6449 return 0;
6450
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006451 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006452 hlua_lua2smp(stream->hlua->T, -1, smp);
6453 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006454 return 1;
6455
6456 /* yield. */
6457 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006458 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006459 return 0;
6460
6461 /* finished with error. */
6462 case HLUA_E_ERRMSG:
6463 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006464 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006465 fcn->name, lua_tostring(stream->hlua->T, -1));
6466 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006467 return 0;
6468
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006469 case HLUA_E_ETMOUT:
6470 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
6471 return 0;
6472
6473 case HLUA_E_NOMEM:
6474 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
6475 return 0;
6476
6477 case HLUA_E_YIELD:
6478 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
6479 return 0;
6480
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006481 case HLUA_E_ERR:
6482 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006483 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006484
6485 default:
6486 return 0;
6487 }
6488}
6489
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006490/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
6491 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01006492 * resume sample-fetches. This function will be called by the sample
6493 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006494 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02006495static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
6496 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006497{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006498 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006499 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006500 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006501 const struct buffer msg = { };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006502
Willy Tarreaube508f12016-03-10 11:47:01 +01006503 if (!stream)
6504 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01006505
Willy Tarreau87b09662015-04-03 00:22:06 +02006506 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006507 * Lua context can be not initialized. This behavior
6508 * permits to save performances because a systematic
6509 * Lua initialization cause 5% performances loss.
6510 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006511 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006512 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006513 if (!stream->hlua) {
6514 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6515 return 0;
6516 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006517 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006518 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6519 return 0;
6520 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006521 }
6522
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006523 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006524
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006525 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006526 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006527
6528 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006529 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6530 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6531 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006532 else
6533 error = "critical error";
6534 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006535 return 0;
6536 }
6537
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006538 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006539 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006540 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006541 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006542 return 0;
6543 }
6544
6545 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006546 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006547
6548 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006549 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02006550 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006551 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006552 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006553 return 0;
6554 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006555 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006556
6557 /* push keywords in the stack. */
6558 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
6559 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006560 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006561 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006562 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006563 return 0;
6564 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006565 hlua_arg2lua(stream->hlua->T, arg_p);
6566 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006567 }
6568
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006569 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006570 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006571
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006572 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006573 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006574 }
6575
6576 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006577 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006578 /* finished. */
6579 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006580 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006581 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006582 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006583 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006584 /* If the stack is empty, the function fails. */
6585 if (lua_gettop(stream->hlua->T) <= 0)
6586 return 0;
6587
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006588 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006589 hlua_lua2smp(stream->hlua->T, -1, smp);
6590 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006591
6592 /* Set the end of execution flag. */
6593 smp->flags &= ~SMP_F_MAY_CHANGE;
6594 return 1;
6595
6596 /* yield. */
6597 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006598 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006599 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006600 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006601 return 0;
6602
6603 /* finished with error. */
6604 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006605 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006606 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006607 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006608 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006609 fcn->name, lua_tostring(stream->hlua->T, -1));
6610 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006611 return 0;
6612
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006613 case HLUA_E_ETMOUT:
6614 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006615 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006616 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
6617 return 0;
6618
6619 case HLUA_E_NOMEM:
6620 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006621 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006622 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
6623 return 0;
6624
6625 case HLUA_E_YIELD:
6626 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006627 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006628 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
6629 return 0;
6630
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006631 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006632 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006633 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006634 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006635 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006636
6637 default:
6638 return 0;
6639 }
6640}
6641
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006642/* This function is an LUA binding used for registering
6643 * "sample-conv" functions. It expects a converter name used
6644 * in the haproxy configuration file, and an LUA function.
6645 */
6646__LJMP static int hlua_register_converters(lua_State *L)
6647{
6648 struct sample_conv_kw_list *sck;
6649 const char *name;
6650 int ref;
6651 int len;
6652 struct hlua_function *fcn;
6653
6654 MAY_LJMP(check_args(L, 2, "register_converters"));
6655
6656 /* First argument : converter name. */
6657 name = MAY_LJMP(luaL_checkstring(L, 1));
6658
6659 /* Second argument : lua function. */
6660 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6661
6662 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006663 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006664 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006665 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006666 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006667 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006668 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006669
6670 /* Fill fcn. */
6671 fcn->name = strdup(name);
6672 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006673 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006674 fcn->function_ref = ref;
6675
6676 /* List head */
6677 sck->list.n = sck->list.p = NULL;
6678
6679 /* converter keyword. */
6680 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006681 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006682 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006683 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006684
6685 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6686 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006687 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 +01006688 sck->kw[0].val_args = NULL;
6689 sck->kw[0].in_type = SMP_T_STR;
6690 sck->kw[0].out_type = SMP_T_STR;
6691 sck->kw[0].private = fcn;
6692
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006693 /* Register this new converter */
6694 sample_register_convs(sck);
6695
6696 return 0;
6697}
6698
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006699/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006700 * "sample-fetch" functions. It expects a converter name used
6701 * in the haproxy configuration file, and an LUA function.
6702 */
6703__LJMP static int hlua_register_fetches(lua_State *L)
6704{
6705 const char *name;
6706 int ref;
6707 int len;
6708 struct sample_fetch_kw_list *sfk;
6709 struct hlua_function *fcn;
6710
6711 MAY_LJMP(check_args(L, 2, "register_fetches"));
6712
6713 /* First argument : sample-fetch name. */
6714 name = MAY_LJMP(luaL_checkstring(L, 1));
6715
6716 /* Second argument : lua function. */
6717 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6718
6719 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006720 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006721 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006722 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006723 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006724 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006725 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006726
6727 /* Fill fcn. */
6728 fcn->name = strdup(name);
6729 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006730 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006731 fcn->function_ref = ref;
6732
6733 /* List head */
6734 sfk->list.n = sfk->list.p = NULL;
6735
6736 /* sample-fetch keyword. */
6737 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006738 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006739 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006740 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006741
6742 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6743 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006744 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 +01006745 sfk->kw[0].val_args = NULL;
6746 sfk->kw[0].out_type = SMP_T_STR;
6747 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6748 sfk->kw[0].val = 0;
6749 sfk->kw[0].private = fcn;
6750
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006751 /* Register this new fetch. */
6752 sample_register_fetches(sfk);
6753
6754 return 0;
6755}
6756
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006757/* This function is a wrapper to execute each LUA function declared
6758 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006759 * return ACT_RET_CONT if the processing is finished (with or without
6760 * error) and return ACT_RET_YIELD if the function must be called again
6761 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006762 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006763static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006764 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006765{
6766 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006767 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006768 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006769 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006770 const struct buffer msg = { };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006771
6772 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01006773 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
6774 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
6775 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
6776 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006777 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006778 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006779 return ACT_RET_CONT;
6780 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006781
Willy Tarreau87b09662015-04-03 00:22:06 +02006782 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006783 * Lua context can be not initialized. This behavior
6784 * permits to save performances because a systematic
6785 * Lua initialization cause 5% performances loss.
6786 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006787 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006788 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006789 if (!s->hlua) {
6790 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6791 rule->arg.hlua_rule->fcn.name);
6792 return ACT_RET_CONT;
6793 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006794 if (!hlua_ctx_init(s->hlua, s->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006795 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6796 rule->arg.hlua_rule->fcn.name);
6797 return ACT_RET_CONT;
6798 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006799 }
6800
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006801 consistency_set(s, dir, &s->hlua->cons);
6802
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006803 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006804 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006805
6806 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006807 if (!SET_SAFE_LJMP(s->hlua->T)) {
6808 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6809 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006810 else
6811 error = "critical error";
6812 SEND_ERR(px, "Lua function '%s': %s.\n",
6813 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006814 return ACT_RET_CONT;
6815 }
6816
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006817 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006818 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006819 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006820 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006821 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006822 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006823 }
6824
6825 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006826 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006827
Willy Tarreau87b09662015-04-03 00:22:06 +02006828 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006829 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006830 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006831 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006832 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006833 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006834 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006835 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006836
6837 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006838 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006839 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006840 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006841 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006842 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006843 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006844 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006845 lua_pushstring(s->hlua->T, *arg);
6846 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006847 }
6848
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006849 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006850 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006851
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006852 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006853 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006854 }
6855
6856 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006857 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006858 /* finished. */
6859 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006860 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006861 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006862 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006863 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006864 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006865 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006866 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006867
6868 /* yield. */
6869 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006870 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006871 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006872 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006873 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006874 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006875 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006876 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006877 /* Some actions can be wake up when a "write" event
6878 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006879 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006880 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006881 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006882 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01006883 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006884 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006885 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006886 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006887 s->req.flags |= CF_WAKE_WRITE;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006888 /* We can quit the function without consistency check
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006889 * because HAProxy is not able to manipulate data, it
6890 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006891 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006892
6893 /* finished with error. */
6894 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006895 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006896 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006897 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006898 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006899 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006900 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006901 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6902 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006903 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006904
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006905 case HLUA_E_ETMOUT:
6906 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006907 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006908 return ACT_RET_ERR;
6909 }
6910 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
6911 return 0;
6912
6913 case HLUA_E_NOMEM:
6914 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006915 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006916 return ACT_RET_ERR;
6917 }
6918 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
6919 return 0;
6920
6921 case HLUA_E_YIELD:
6922 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006923 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006924 return ACT_RET_ERR;
6925 }
6926 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6927 rule->arg.hlua_rule->fcn.name);
6928 return 0;
6929
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006930 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006931 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006932 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006933 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006934 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006935 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006936 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006937 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006938
6939 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006940 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006941 }
6942}
6943
Olivier Houchard9f6af332018-05-25 14:04:04 +02006944struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006945{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006946 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006947
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006948 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006949 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006950 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006951}
6952
6953static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6954{
6955 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006956 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006957 struct task *task;
6958 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006959 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006960
Willy Tarreaubafbe012017-11-24 17:34:44 +01006961 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006962 if (!hlua) {
6963 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6964 ctx->rule->arg.hlua_rule->fcn.name);
6965 return 0;
6966 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006967 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006968 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006969 ctx->ctx.hlua_apptcp.flags = 0;
6970
6971 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006972 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006973 if (!task) {
6974 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6975 ctx->rule->arg.hlua_rule->fcn.name);
6976 return 0;
6977 }
6978 task->nice = 0;
6979 task->context = ctx;
6980 task->process = hlua_applet_wakeup;
6981 ctx->ctx.hlua_apptcp.task = task;
6982
6983 /* In the execution wrappers linked with a stream, the
6984 * Lua context can be not initialized. This behavior
6985 * permits to save performances because a systematic
6986 * Lua initialization cause 5% performances loss.
6987 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006988 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006989 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6990 ctx->rule->arg.hlua_rule->fcn.name);
6991 return 0;
6992 }
6993
6994 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006995 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006996
6997 /* The following Lua calls can fail. */
6998 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006999 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7000 error = lua_tostring(hlua->T, -1);
7001 else
7002 error = "critical error";
7003 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
7004 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007005 return 0;
7006 }
7007
7008 /* Check stack available size. */
7009 if (!lua_checkstack(hlua->T, 1)) {
7010 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7011 ctx->rule->arg.hlua_rule->fcn.name);
7012 RESET_SAFE_LJMP(hlua->T);
7013 return 0;
7014 }
7015
7016 /* Restore the function in the stack. */
7017 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7018
7019 /* Create and and push object stream in the stack. */
7020 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
7021 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7022 ctx->rule->arg.hlua_rule->fcn.name);
7023 RESET_SAFE_LJMP(hlua->T);
7024 return 0;
7025 }
7026 hlua->nargs = 1;
7027
7028 /* push keywords in the stack. */
7029 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7030 if (!lua_checkstack(hlua->T, 1)) {
7031 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7032 ctx->rule->arg.hlua_rule->fcn.name);
7033 RESET_SAFE_LJMP(hlua->T);
7034 return 0;
7035 }
7036 lua_pushstring(hlua->T, *arg);
7037 hlua->nargs++;
7038 }
7039
7040 RESET_SAFE_LJMP(hlua->T);
7041
7042 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007043 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01007044 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007045
7046 return 1;
7047}
7048
7049static void hlua_applet_tcp_fct(struct appctx *ctx)
7050{
7051 struct stream_interface *si = ctx->owner;
7052 struct stream *strm = si_strm(si);
7053 struct channel *res = si_ic(si);
7054 struct act_rule *rule = ctx->rule;
7055 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007056 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007057
7058 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02007059 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
7060 /* eat the whole request */
7061 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007062 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02007063 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007064
7065 /* If the stream is disconnect or closed, ldo nothing. */
7066 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7067 return;
7068
7069 /* Execute the function. */
7070 switch (hlua_ctx_resume(hlua, 1)) {
7071 /* finished. */
7072 case HLUA_E_OK:
7073 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7074
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007075 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02007076 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007077 res->flags |= CF_READ_NULL;
7078 si_shutr(si);
7079 return;
7080
7081 /* yield. */
7082 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007083 if (hlua->wake_time != TICK_ETERNITY)
7084 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007085 return;
7086
7087 /* finished with error. */
7088 case HLUA_E_ERRMSG:
7089 /* Display log. */
7090 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
7091 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7092 lua_pop(hlua->T, 1);
7093 goto error;
7094
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007095 case HLUA_E_ETMOUT:
7096 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
7097 rule->arg.hlua_rule->fcn.name);
7098 goto error;
7099
7100 case HLUA_E_NOMEM:
7101 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
7102 rule->arg.hlua_rule->fcn.name);
7103 goto error;
7104
7105 case HLUA_E_YIELD: /* unexpected */
7106 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
7107 rule->arg.hlua_rule->fcn.name);
7108 goto error;
7109
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007110 case HLUA_E_ERR:
7111 /* Display log. */
7112 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
7113 rule->arg.hlua_rule->fcn.name);
7114 goto error;
7115
7116 default:
7117 goto error;
7118 }
7119
7120error:
7121
7122 /* For all other cases, just close the stream. */
7123 si_shutw(si);
7124 si_shutr(si);
7125 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7126}
7127
7128static void hlua_applet_tcp_release(struct appctx *ctx)
7129{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02007130 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007131 task_free(ctx->ctx.hlua_apptcp.task);
7132 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007133 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007134 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007135}
7136
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007137/* The function returns 1 if the initialisation is complete, 0 if
7138 * an errors occurs and -1 if more data are required for initializing
7139 * the applet.
7140 */
7141static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
7142{
7143 struct stream_interface *si = ctx->owner;
7144 struct channel *req = si_oc(si);
7145 struct http_msg *msg;
7146 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007147 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007148 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007149 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007150 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007151
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007152 txn = strm->txn;
7153 msg = &txn->req;
7154
Willy Tarreau0078bfc2015-10-07 20:20:28 +02007155 /* We want two things in HTTP mode :
7156 * - enforce server-close mode if we were in keep-alive, so that the
7157 * applet is released after each response ;
7158 * - enable request body transfer to the applet in order to resync
7159 * with the response body.
7160 */
7161 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
7162 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02007163
Willy Tarreaubafbe012017-11-24 17:34:44 +01007164 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007165 if (!hlua) {
7166 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7167 ctx->rule->arg.hlua_rule->fcn.name);
7168 return 0;
7169 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007170 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007171 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007172 ctx->ctx.hlua_apphttp.left_bytes = -1;
7173 ctx->ctx.hlua_apphttp.flags = 0;
7174
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01007175 if (txn->req.flags & HTTP_MSGF_VER_11)
7176 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
7177
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007178 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007179 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007180 if (!task) {
7181 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7182 ctx->rule->arg.hlua_rule->fcn.name);
7183 return 0;
7184 }
7185 task->nice = 0;
7186 task->context = ctx;
7187 task->process = hlua_applet_wakeup;
7188 ctx->ctx.hlua_apphttp.task = task;
7189
7190 /* In the execution wrappers linked with a stream, the
7191 * Lua context can be not initialized. This behavior
7192 * permits to save performances because a systematic
7193 * Lua initialization cause 5% performances loss.
7194 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007195 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007196 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
7197 ctx->rule->arg.hlua_rule->fcn.name);
7198 return 0;
7199 }
7200
7201 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007202 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007203
7204 /* The following Lua calls can fail. */
7205 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007206 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7207 error = lua_tostring(hlua->T, -1);
7208 else
7209 error = "critical error";
7210 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7211 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007212 return 0;
7213 }
7214
7215 /* Check stack available size. */
7216 if (!lua_checkstack(hlua->T, 1)) {
7217 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7218 ctx->rule->arg.hlua_rule->fcn.name);
7219 RESET_SAFE_LJMP(hlua->T);
7220 return 0;
7221 }
7222
7223 /* Restore the function in the stack. */
7224 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7225
7226 /* Create and and push object stream in the stack. */
7227 if (!hlua_applet_http_new(hlua->T, ctx)) {
7228 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7229 ctx->rule->arg.hlua_rule->fcn.name);
7230 RESET_SAFE_LJMP(hlua->T);
7231 return 0;
7232 }
7233 hlua->nargs = 1;
7234
7235 /* Look for a 100-continue expected. */
7236 if (msg->flags & HTTP_MSGF_VER_11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007237 if (IS_HTX_STRM(si_strm(si))) {
7238 /* HTX version */
7239 struct htx *htx = htxbuf(&req->buf);
7240 struct ist hdr = { .ptr = "Expect", .len = 6 };
7241 struct http_hdr_ctx hdr_ctx;
7242
7243 hdr_ctx.blk = NULL;
7244 /* Expect is allowed in 1.1, look for it */
7245 if (http_find_header(htx, hdr, &hdr_ctx, 0) &&
7246 unlikely(isteqi(hdr_ctx.value, ist2("100-continue", 12))))
7247 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
7248 }
7249 else {
7250 /* Legacy HTTP version */
7251 struct hdr_ctx hdr;
7252
7253 hdr.idx = 0;
7254 if (http_find_header2("Expect", 6, ci_head(req), &txn->hdr_idx, &hdr) &&
7255 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
7256 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
7257 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007258 }
7259
7260 /* push keywords in the stack. */
7261 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7262 if (!lua_checkstack(hlua->T, 1)) {
7263 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7264 ctx->rule->arg.hlua_rule->fcn.name);
7265 RESET_SAFE_LJMP(hlua->T);
7266 return 0;
7267 }
7268 lua_pushstring(hlua->T, *arg);
7269 hlua->nargs++;
7270 }
7271
7272 RESET_SAFE_LJMP(hlua->T);
7273
7274 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007275 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007276
7277 return 1;
7278}
7279
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007280static void hlua_applet_htx_fct(struct appctx *ctx)
7281{
7282 struct stream_interface *si = ctx->owner;
7283 struct stream *strm = si_strm(si);
7284 struct channel *req = si_oc(si);
7285 struct channel *res = si_ic(si);
7286 struct act_rule *rule = ctx->rule;
7287 struct proxy *px = strm->be;
7288 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
7289 struct htx *req_htx, *res_htx;
7290
7291 res_htx = htx_from_buf(&res->buf);
7292
7293 /* If the stream is disconnect or closed, ldo nothing. */
7294 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7295 goto out;
7296
7297 /* Check if the input buffer is avalaible. */
7298 if (!b_size(&res->buf)) {
7299 si_rx_room_blk(si);
7300 goto out;
7301 }
7302 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007303 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007304 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7305
7306 /* Set the currently running flag. */
7307 if (!HLUA_IS_RUNNING(hlua) &&
7308 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7309 struct htx_blk *blk;
7310 size_t count = co_data(req);
7311
7312 if (!count) {
7313 si_cant_get(si);
7314 goto out;
7315 }
7316
7317 /* We need to flush the request header. This left the body for
7318 * the Lua.
7319 */
7320 req_htx = htx_from_buf(&req->buf);
7321 blk = htx_get_head_blk(req_htx);
7322 while (count && blk) {
7323 enum htx_blk_type type = htx_get_blk_type(blk);
7324 uint32_t sz = htx_get_blksz(blk);
7325
7326 if (sz > count) {
7327 si_cant_get(si);
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007328 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007329 goto out;
7330 }
7331
7332 count -= sz;
7333 co_set_data(req, co_data(req) - sz);
7334 blk = htx_remove_blk(req_htx, blk);
7335
7336 if (type == HTX_BLK_EOH)
7337 break;
7338 }
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007339 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007340 }
7341
7342 /* Executes The applet if it is not done. */
7343 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7344
7345 /* Execute the function. */
7346 switch (hlua_ctx_resume(hlua, 1)) {
7347 /* finished. */
7348 case HLUA_E_OK:
7349 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7350 break;
7351
7352 /* yield. */
7353 case HLUA_E_AGAIN:
7354 if (hlua->wake_time != TICK_ETERNITY)
7355 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007356 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007357
7358 /* finished with error. */
7359 case HLUA_E_ERRMSG:
7360 /* Display log. */
7361 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7362 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7363 lua_pop(hlua->T, 1);
7364 goto error;
7365
7366 case HLUA_E_ETMOUT:
7367 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7368 rule->arg.hlua_rule->fcn.name);
7369 goto error;
7370
7371 case HLUA_E_NOMEM:
7372 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7373 rule->arg.hlua_rule->fcn.name);
7374 goto error;
7375
7376 case HLUA_E_YIELD: /* unexpected */
7377 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7378 rule->arg.hlua_rule->fcn.name);
7379 goto error;
7380
7381 case HLUA_E_ERR:
7382 /* Display log. */
7383 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7384 rule->arg.hlua_rule->fcn.name);
7385 goto error;
7386
7387 default:
7388 goto error;
7389 }
7390 }
7391
7392 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007393 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7394 goto done;
7395
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007396 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7397 goto error;
7398
7399 /* Don't add EOD and TLR because mux-h1 will take care of it */
7400 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
7401 si_rx_room_blk(si);
7402 goto out;
7403 }
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007404 channel_add_input(res, 1);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007405 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7406 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007407 }
7408
7409 done:
7410 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007411 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007412 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007413 si_shutr(si);
7414 }
7415
7416 /* eat the whole request */
7417 if (co_data(req)) {
7418 req_htx = htx_from_buf(&req->buf);
7419 co_htx_skip(req, req_htx, co_data(req));
7420 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007421 }
7422 }
7423
7424 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007425 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007426 return;
7427
7428 error:
7429
7430 /* If we are in HTTP mode, and we are not send any
7431 * data, return a 500 server error in best effort:
7432 * if there is no room available in the buffer,
7433 * just close the connection.
7434 */
7435 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
7436 struct buffer *err = &htx_err_chunks[HTTP_ERR_500];
7437
7438 channel_erase(res);
7439 res->buf.data = b_data(err);
7440 memcpy(res->buf.area, b_head(err), b_data(err));
7441 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007442 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007443 }
7444 if (!(strm->flags & SF_ERR_MASK))
7445 strm->flags |= SF_ERR_RESOURCE;
7446 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7447 goto done;
7448}
7449
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007450static void hlua_applet_http_fct(struct appctx *ctx)
7451{
7452 struct stream_interface *si = ctx->owner;
7453 struct stream *strm = si_strm(si);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007454 struct channel *req = si_oc(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007455 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007456 struct act_rule *rule = ctx->rule;
7457 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007458 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Willy Tarreau206ba832018-06-14 15:27:31 +02007459 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02007460 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02007461 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02007462 size_t len2;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007463 int ret;
7464
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007465 if (IS_HTX_STRM(strm))
7466 return hlua_applet_htx_fct(ctx);
7467
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007468 /* If the stream is disconnect or closed, ldo nothing. */
7469 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007470 goto out;
7471
7472 /* Check if the input buffer is avalaible. */
7473 if (!b_size(&res->buf)) {
7474 si_rx_room_blk(si);
7475 goto out;
7476 }
7477 /* check that the output is not closed */
7478 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
7479 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007480
7481 /* Set the currently running flag. */
7482 if (!HLUA_IS_RUNNING(hlua) &&
7483 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007484 /* Store the max amount of bytes that we can read. */
7485 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
7486
7487 /* We need to flush the request header. This left the body
7488 * for the Lua.
7489 */
7490
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007491 /* Read the maximum amount of data available. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007492 ret = co_getblk_nc(req, &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007493 if (ret == -1)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007494 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007495
7496 /* No data available, ask for more data. */
7497 if (ret == 1)
7498 len2 = 0;
7499 if (ret == 0)
7500 len1 = 0;
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02007501 if (len1 + len2 < strm->txn->req.eoh + strm->txn->req.eol) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007502 si_cant_get(si);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007503 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007504 }
7505
7506 /* skip the requests bytes. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007507 co_skip(req, strm->txn->req.eoh + strm->txn->req.eol);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007508 }
7509
7510 /* Executes The applet if it is not done. */
7511 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7512
7513 /* Execute the function. */
7514 switch (hlua_ctx_resume(hlua, 1)) {
7515 /* finished. */
7516 case HLUA_E_OK:
7517 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7518 break;
7519
7520 /* yield. */
7521 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007522 if (hlua->wake_time != TICK_ETERNITY)
7523 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007524 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007525
7526 /* finished with error. */
7527 case HLUA_E_ERRMSG:
7528 /* Display log. */
7529 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7530 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7531 lua_pop(hlua->T, 1);
7532 goto error;
7533
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007534 case HLUA_E_ETMOUT:
7535 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7536 rule->arg.hlua_rule->fcn.name);
7537 goto error;
7538
7539 case HLUA_E_NOMEM:
7540 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7541 rule->arg.hlua_rule->fcn.name);
7542 goto error;
7543
7544 case HLUA_E_YIELD: /* unexpected */
7545 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7546 rule->arg.hlua_rule->fcn.name);
7547 goto error;
7548
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007549 case HLUA_E_ERR:
7550 /* Display log. */
7551 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7552 rule->arg.hlua_rule->fcn.name);
7553 goto error;
7554
7555 default:
7556 goto error;
7557 }
7558 }
7559
7560 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007561 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7562 goto done;
7563
Christopher Fauletcc26b132018-12-18 21:20:57 +01007564 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7565 goto error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007566
7567 /* We must send the final chunk. */
7568 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
7569 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
7570
7571 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02007572 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007573
7574 /* critical error. */
7575 if (ret == -2 || ret == -3) {
7576 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
7577 rule->arg.hlua_rule->fcn.name);
7578 goto error;
7579 }
7580
7581 /* no enough space error. */
7582 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01007583 si_rx_room_blk(si);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007584 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007585 }
7586
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007587 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7588 ctx->ctx.hlua_apphttp.flags |= (APPLET_LAST_CHK|APPLET_RSP_SENT);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007589 }
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007590 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007591
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007592 done:
7593 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
7594 if (!(res->flags & CF_SHUTR)) {
7595 res->flags |= CF_READ_NULL;
7596 si_shutr(si);
7597 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007598
7599 /* eat the whole request */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007600 if (co_data(req))
7601 co_skip(req, co_data(req));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007602 }
7603
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007604 out:
7605 return;
7606
7607 error:
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007608
7609 /* If we are in HTTP mode, and we are not send any
7610 * data, return a 500 server error in best effort:
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007611 * if there is no room available in the buffer,
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007612 * just close the connection.
7613 */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007614 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
7615 channel_erase(res);
7616 ci_putblk(res, error_500, strlen(error_500));
7617 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007618 if (!(strm->flags & SF_ERR_MASK))
7619 strm->flags |= SF_ERR_RESOURCE;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007620 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007621 goto done;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007622}
7623
7624static void hlua_applet_http_release(struct appctx *ctx)
7625{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02007626 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007627 task_free(ctx->ctx.hlua_apphttp.task);
7628 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007629 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007630 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007631}
7632
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007633/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
7634 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007635 *
7636 * This function can fail with an abort() due to an Lua critical error.
7637 * We are in the configuration parsing process of HAProxy, this abort() is
7638 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007639 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007640static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
7641 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007642{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007643 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007644 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007645
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007646 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007647 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007648 if (!rule->arg.hlua_rule) {
7649 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007650 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007651 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007652
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007653 /* Memory for arguments. */
7654 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
7655 if (!rule->arg.hlua_rule->args) {
7656 memprintf(err, "out of memory error");
7657 return ACT_RET_PRS_ERR;
7658 }
7659
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007660 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007661 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007662
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007663 /* Expect some arguments */
7664 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007665 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007666 memprintf(err, "expect %d arguments", fcn->nargs);
7667 return ACT_RET_PRS_ERR;
7668 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007669 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007670 if (!rule->arg.hlua_rule->args[i]) {
7671 memprintf(err, "out of memory error");
7672 return ACT_RET_PRS_ERR;
7673 }
7674 (*cur_arg)++;
7675 }
7676 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007677
Thierry FOURNIER42148732015-09-02 17:17:33 +02007678 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007679 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007680 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007681}
7682
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007683static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
7684 struct act_rule *rule, char **err)
7685{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007686 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007687
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007688 /* HTTP applets are forbidden in tcp-request rules.
7689 * HTTP applet request requires everything initilized by
7690 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
7691 * The applet will be immediately initilized, but its before
7692 * the call of this analyzer.
7693 */
7694 if (rule->from != ACT_F_HTTP_REQ) {
7695 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
7696 return ACT_RET_PRS_ERR;
7697 }
7698
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007699 /* Memory for the rule. */
7700 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7701 if (!rule->arg.hlua_rule) {
7702 memprintf(err, "out of memory error");
7703 return ACT_RET_PRS_ERR;
7704 }
7705
7706 /* Reference the Lua function and store the reference. */
7707 rule->arg.hlua_rule->fcn = *fcn;
7708
7709 /* TODO: later accept arguments. */
7710 rule->arg.hlua_rule->args = NULL;
7711
7712 /* Add applet pointer in the rule. */
7713 rule->applet.obj_type = OBJ_TYPE_APPLET;
7714 rule->applet.name = fcn->name;
7715 rule->applet.init = hlua_applet_http_init;
7716 rule->applet.fct = hlua_applet_http_fct;
7717 rule->applet.release = hlua_applet_http_release;
7718 rule->applet.timeout = hlua_timeout_applet;
7719
7720 return ACT_RET_PRS_OK;
7721}
7722
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007723/* This function is an LUA binding used for registering
7724 * "sample-conv" functions. It expects a converter name used
7725 * in the haproxy configuration file, and an LUA function.
7726 */
7727__LJMP static int hlua_register_action(lua_State *L)
7728{
7729 struct action_kw_list *akl;
7730 const char *name;
7731 int ref;
7732 int len;
7733 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007734 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007735
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007736 /* Initialise the number of expected arguments at 0. */
7737 nargs = 0;
7738
7739 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7740 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007741
7742 /* First argument : converter name. */
7743 name = MAY_LJMP(luaL_checkstring(L, 1));
7744
7745 /* Second argument : environment. */
7746 if (lua_type(L, 2) != LUA_TTABLE)
7747 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7748
7749 /* Third argument : lua function. */
7750 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7751
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007752 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007753 if (lua_gettop(L) >= 4)
7754 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
7755
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007756 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007757 lua_pushnil(L);
7758 while (lua_next(L, 2) != 0) {
7759 if (lua_type(L, -1) != LUA_TSTRING)
7760 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7761
7762 /* Check required environment. Only accepted "http" or "tcp". */
7763 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007764 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007765 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007766 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007767 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007768 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007769 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007770
7771 /* Fill fcn. */
7772 fcn->name = strdup(name);
7773 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007774 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007775 fcn->function_ref = ref;
7776
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007777 /* Set the expected number od arguments. */
7778 fcn->nargs = nargs;
7779
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007780 /* List head */
7781 akl->list.n = akl->list.p = NULL;
7782
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007783 /* action keyword. */
7784 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007785 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007786 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007787 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007788
7789 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7790
7791 akl->kw[0].match_pfx = 0;
7792 akl->kw[0].private = fcn;
7793 akl->kw[0].parse = action_register_lua;
7794
7795 /* select the action registering point. */
7796 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
7797 tcp_req_cont_keywords_register(akl);
7798 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
7799 tcp_res_cont_keywords_register(akl);
7800 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
7801 http_req_keywords_register(akl);
7802 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
7803 http_res_keywords_register(akl);
7804 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007805 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007806 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
7807 "are expected.", lua_tostring(L, -1)));
7808
7809 /* pop the environment string. */
7810 lua_pop(L, 1);
7811 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007812 return ACT_RET_PRS_OK;
7813}
7814
7815static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7816 struct act_rule *rule, char **err)
7817{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007818 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007819
Christopher Fauletafd8f102018-11-08 11:34:21 +01007820 if (px->options2 & PR_O2_USE_HTX) {
7821 memprintf(err, "Lua services cannot be used when the HTX internal representation is enabled");
7822 return ACT_RET_PRS_ERR;
7823 }
7824
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007825 /* Memory for the rule. */
7826 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7827 if (!rule->arg.hlua_rule) {
7828 memprintf(err, "out of memory error");
7829 return ACT_RET_PRS_ERR;
7830 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007831
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007832 /* Reference the Lua function and store the reference. */
7833 rule->arg.hlua_rule->fcn = *fcn;
7834
7835 /* TODO: later accept arguments. */
7836 rule->arg.hlua_rule->args = NULL;
7837
7838 /* Add applet pointer in the rule. */
7839 rule->applet.obj_type = OBJ_TYPE_APPLET;
7840 rule->applet.name = fcn->name;
7841 rule->applet.init = hlua_applet_tcp_init;
7842 rule->applet.fct = hlua_applet_tcp_fct;
7843 rule->applet.release = hlua_applet_tcp_release;
7844 rule->applet.timeout = hlua_timeout_applet;
7845
7846 return 0;
7847}
7848
7849/* This function is an LUA binding used for registering
7850 * "sample-conv" functions. It expects a converter name used
7851 * in the haproxy configuration file, and an LUA function.
7852 */
7853__LJMP static int hlua_register_service(lua_State *L)
7854{
7855 struct action_kw_list *akl;
7856 const char *name;
7857 const char *env;
7858 int ref;
7859 int len;
7860 struct hlua_function *fcn;
7861
7862 MAY_LJMP(check_args(L, 3, "register_service"));
7863
7864 /* First argument : converter name. */
7865 name = MAY_LJMP(luaL_checkstring(L, 1));
7866
7867 /* Second argument : environment. */
7868 env = MAY_LJMP(luaL_checkstring(L, 2));
7869
7870 /* Third argument : lua function. */
7871 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7872
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007873 /* Allocate and fill the sample fetch keyword struct. */
7874 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7875 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007876 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007877 fcn = calloc(1, sizeof(*fcn));
7878 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007879 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007880
7881 /* Fill fcn. */
7882 len = strlen("<lua.>") + strlen(name) + 1;
7883 fcn->name = calloc(1, len);
7884 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007885 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007886 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7887 fcn->function_ref = ref;
7888
7889 /* List head */
7890 akl->list.n = akl->list.p = NULL;
7891
7892 /* converter keyword. */
7893 len = strlen("lua.") + strlen(name) + 1;
7894 akl->kw[0].kw = calloc(1, len);
7895 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007896 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007897
7898 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7899
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007900 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007901 if (strcmp(env, "tcp") == 0)
7902 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007903 else if (strcmp(env, "http") == 0)
7904 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007905 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007906 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007907 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007908
7909 akl->kw[0].match_pfx = 0;
7910 akl->kw[0].private = fcn;
7911
7912 /* End of array. */
7913 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7914
7915 /* Register this new converter */
7916 service_keywords_register(akl);
7917
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007918 return 0;
7919}
7920
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007921/* This function initialises Lua cli handler. It copies the
7922 * arguments in the Lua stack and create channel IO objects.
7923 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007924static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007925{
7926 struct hlua *hlua;
7927 struct hlua_function *fcn;
7928 int i;
7929 const char *error;
7930
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007931 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007932 appctx->ctx.hlua_cli.fcn = private;
7933
Willy Tarreaubafbe012017-11-24 17:34:44 +01007934 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007935 if (!hlua) {
7936 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007937 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007938 }
7939 HLUA_INIT(hlua);
7940 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007941
7942 /* Create task used by signal to wakeup applets.
7943 * We use the same wakeup fonction than the Lua applet_tcp and
7944 * applet_http. It is absolutely compatible.
7945 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007946 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007947 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007948 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007949 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007950 }
7951 appctx->ctx.hlua_cli.task->nice = 0;
7952 appctx->ctx.hlua_cli.task->context = appctx;
7953 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7954
7955 /* Initialises the Lua context */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007956 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007957 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007958 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007959 }
7960
7961 /* The following Lua calls can fail. */
7962 if (!SET_SAFE_LJMP(hlua->T)) {
7963 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7964 error = lua_tostring(hlua->T, -1);
7965 else
7966 error = "critical error";
7967 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7968 goto error;
7969 }
7970
7971 /* Check stack available size. */
7972 if (!lua_checkstack(hlua->T, 2)) {
7973 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7974 goto error;
7975 }
7976
7977 /* Restore the function in the stack. */
7978 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7979
7980 /* Once the arguments parsed, the CLI is like an AppletTCP,
7981 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007982 */
7983 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7984 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7985 goto error;
7986 }
7987 hlua->nargs = 1;
7988
7989 /* push keywords in the stack. */
7990 for (i = 0; *args[i]; i++) {
7991 /* Check stack available size. */
7992 if (!lua_checkstack(hlua->T, 1)) {
7993 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7994 goto error;
7995 }
7996 lua_pushstring(hlua->T, args[i]);
7997 hlua->nargs++;
7998 }
7999
8000 /* We must initialize the execution timeouts. */
8001 hlua->max_time = hlua_timeout_session;
8002
8003 /* At this point the execution is safe. */
8004 RESET_SAFE_LJMP(hlua->T);
8005
8006 /* It's ok */
8007 return 0;
8008
8009 /* It's not ok. */
8010error:
8011 RESET_SAFE_LJMP(hlua->T);
8012 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01008013 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008014 return 1;
8015}
8016
8017static int hlua_cli_io_handler_fct(struct appctx *appctx)
8018{
8019 struct hlua *hlua;
8020 struct stream_interface *si;
8021 struct hlua_function *fcn;
8022
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008023 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008024 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01008025 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008026
8027 /* If the stream is disconnect or closed, ldo nothing. */
8028 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8029 return 1;
8030
8031 /* Execute the function. */
8032 switch (hlua_ctx_resume(hlua, 1)) {
8033
8034 /* finished. */
8035 case HLUA_E_OK:
8036 return 1;
8037
8038 /* yield. */
8039 case HLUA_E_AGAIN:
8040 /* We want write. */
8041 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01008042 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008043 /* Set the timeout. */
8044 if (hlua->wake_time != TICK_ETERNITY)
8045 task_schedule(hlua->task, hlua->wake_time);
8046 return 0;
8047
8048 /* finished with error. */
8049 case HLUA_E_ERRMSG:
8050 /* Display log. */
8051 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
8052 fcn->name, lua_tostring(hlua->T, -1));
8053 lua_pop(hlua->T, 1);
8054 return 1;
8055
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008056 case HLUA_E_ETMOUT:
8057 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
8058 fcn->name);
8059 return 1;
8060
8061 case HLUA_E_NOMEM:
8062 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
8063 fcn->name);
8064 return 1;
8065
8066 case HLUA_E_YIELD: /* unexpected */
8067 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
8068 fcn->name);
8069 return 1;
8070
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008071 case HLUA_E_ERR:
8072 /* Display log. */
8073 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
8074 fcn->name);
8075 return 1;
8076
8077 default:
8078 return 1;
8079 }
8080
8081 return 1;
8082}
8083
8084static void hlua_cli_io_release_fct(struct appctx *appctx)
8085{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008086 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008087 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008088}
8089
8090/* This function is an LUA binding used for registering
8091 * new keywords in the cli. It expects a list of keywords
8092 * which are the "path". It is limited to 5 keywords. A
8093 * description of the command, a function to be executed
8094 * for the parsing and a function for io handlers.
8095 */
8096__LJMP static int hlua_register_cli(lua_State *L)
8097{
8098 struct cli_kw_list *cli_kws;
8099 const char *message;
8100 int ref_io;
8101 int len;
8102 struct hlua_function *fcn;
8103 int index;
8104 int i;
8105
8106 MAY_LJMP(check_args(L, 3, "register_cli"));
8107
8108 /* First argument : an array of maximum 5 keywords. */
8109 if (!lua_istable(L, 1))
8110 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
8111
8112 /* Second argument : string with contextual message. */
8113 message = MAY_LJMP(luaL_checkstring(L, 2));
8114
8115 /* Third and fourth argument : lua function. */
8116 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
8117
8118 /* Allocate and fill the sample fetch keyword struct. */
8119 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
8120 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008121 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008122 fcn = calloc(1, sizeof(*fcn));
8123 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008124 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008125
8126 /* Fill path. */
8127 index = 0;
8128 lua_pushnil(L);
8129 while(lua_next(L, 1) != 0) {
8130 if (index >= 5)
8131 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
8132 if (lua_type(L, -1) != LUA_TSTRING)
8133 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
8134 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
8135 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008136 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008137 index++;
8138 lua_pop(L, 1);
8139 }
8140
8141 /* Copy help message. */
8142 cli_kws->kw[0].usage = strdup(message);
8143 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008144 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008145
8146 /* Fill fcn io handler. */
8147 len = strlen("<lua.cli>") + 1;
8148 for (i = 0; i < index; i++)
8149 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
8150 fcn->name = calloc(1, len);
8151 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008152 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008153 strncat((char *)fcn->name, "<lua.cli", len);
8154 for (i = 0; i < index; i++) {
8155 strncat((char *)fcn->name, ".", len);
8156 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
8157 }
8158 strncat((char *)fcn->name, ">", len);
8159 fcn->function_ref = ref_io;
8160
8161 /* Fill last entries. */
8162 cli_kws->kw[0].private = fcn;
8163 cli_kws->kw[0].parse = hlua_cli_parse_fct;
8164 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
8165 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
8166
8167 /* Register this new converter */
8168 cli_register_kw(cli_kws);
8169
8170 return 0;
8171}
8172
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008173static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
8174 struct proxy *defpx, const char *file, int line,
8175 char **err, unsigned int *timeout)
8176{
8177 const char *error;
8178
8179 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
8180 if (error && *error != '\0') {
8181 memprintf(err, "%s: invalid timeout", args[0]);
8182 return -1;
8183 }
8184 return 0;
8185}
8186
8187static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
8188 struct proxy *defpx, const char *file, int line,
8189 char **err)
8190{
8191 return hlua_read_timeout(args, section_type, curpx, defpx,
8192 file, line, err, &hlua_timeout_session);
8193}
8194
8195static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
8196 struct proxy *defpx, const char *file, int line,
8197 char **err)
8198{
8199 return hlua_read_timeout(args, section_type, curpx, defpx,
8200 file, line, err, &hlua_timeout_task);
8201}
8202
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008203static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
8204 struct proxy *defpx, const char *file, int line,
8205 char **err)
8206{
8207 return hlua_read_timeout(args, section_type, curpx, defpx,
8208 file, line, err, &hlua_timeout_applet);
8209}
8210
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008211static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
8212 struct proxy *defpx, const char *file, int line,
8213 char **err)
8214{
8215 char *error;
8216
8217 hlua_nb_instruction = strtoll(args[1], &error, 10);
8218 if (*error != '\0') {
8219 memprintf(err, "%s: invalid number", args[0]);
8220 return -1;
8221 }
8222 return 0;
8223}
8224
Willy Tarreau32f61e22015-03-18 17:54:59 +01008225static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
8226 struct proxy *defpx, const char *file, int line,
8227 char **err)
8228{
8229 char *error;
8230
8231 if (*(args[1]) == 0) {
8232 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
8233 return -1;
8234 }
8235 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
8236 if (*error != '\0') {
8237 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
8238 return -1;
8239 }
8240 return 0;
8241}
8242
8243
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008244/* This function is called by the main configuration key "lua-load". It loads and
8245 * execute an lua file during the parsing of the HAProxy configuration file. It is
8246 * the main lua entry point.
8247 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008248 * This function runs with the HAProxy keywords API. It returns -1 if an error
8249 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008250 *
8251 * In some error case, LUA set an error message in top of the stack. This function
8252 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008253 *
8254 * This function can fail with an abort() due to an Lua critical error.
8255 * We are in the configuration parsing process of HAProxy, this abort() is
8256 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008257 */
8258static int hlua_load(char **args, int section_type, struct proxy *curpx,
8259 struct proxy *defpx, const char *file, int line,
8260 char **err)
8261{
8262 int error;
8263
8264 /* Just load and compile the file. */
8265 error = luaL_loadfile(gL.T, args[1]);
8266 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008267 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008268 lua_pop(gL.T, 1);
8269 return -1;
8270 }
8271
8272 /* If no syntax error where detected, execute the code. */
8273 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
8274 switch (error) {
8275 case LUA_OK:
8276 break;
8277 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008278 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008279 lua_pop(gL.T, 1);
8280 return -1;
8281 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008282 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008283 return -1;
8284 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008285 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008286 lua_pop(gL.T, 1);
8287 return -1;
8288 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008289 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008290 lua_pop(gL.T, 1);
8291 return -1;
8292 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008293 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008294 lua_pop(gL.T, 1);
8295 return -1;
8296 }
8297
8298 return 0;
8299}
8300
8301/* configuration keywords declaration */
8302static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008303 { CFG_GLOBAL, "lua-load", hlua_load },
8304 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
8305 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02008306 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008307 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01008308 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008309 { 0, NULL, NULL },
8310}};
8311
Willy Tarreau0108d902018-11-25 19:14:37 +01008312INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
8313
Christopher Fauletafd8f102018-11-08 11:34:21 +01008314
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008315/* This function can fail with an abort() due to an Lua critical error.
8316 * We are in the initialisation process of HAProxy, this abort() is
8317 * tolerated.
8318 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008319int hlua_post_init()
8320{
8321 struct hlua_init_function *init;
8322 const char *msg;
8323 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008324 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008325
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008326 /* Call post initialisation function in safe environement. */
8327 if (!SET_SAFE_LJMP(gL.T)) {
8328 if (lua_type(gL.T, -1) == LUA_TSTRING)
8329 error = lua_tostring(gL.T, -1);
8330 else
8331 error = "critical error";
8332 fprintf(stderr, "Lua post-init: %s.\n", error);
8333 exit(1);
8334 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02008335
8336#if USE_OPENSSL
8337 /* Initialize SSL server. */
8338 if (socket_ssl.xprt->prepare_srv) {
8339 int saved_used_backed = global.ssl_used_backend;
8340 // don't affect maxconn automatic computation
8341 socket_ssl.xprt->prepare_srv(&socket_ssl);
8342 global.ssl_used_backend = saved_used_backed;
8343 }
8344#endif
8345
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008346 hlua_fcn_post_init(gL.T);
8347 RESET_SAFE_LJMP(gL.T);
8348
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008349 list_for_each_entry(init, &hlua_init_functions, l) {
8350 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
8351 ret = hlua_ctx_resume(&gL, 0);
8352 switch (ret) {
8353 case HLUA_E_OK:
8354 lua_pop(gL.T, -1);
8355 return 1;
8356 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008357 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008358 return 0;
8359 case HLUA_E_ERRMSG:
8360 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01008361 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008362 return 0;
8363 case HLUA_E_ERR:
8364 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008365 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008366 return 0;
8367 }
8368 }
8369 return 1;
8370}
8371
Willy Tarreau32f61e22015-03-18 17:54:59 +01008372/* The memory allocator used by the Lua stack. <ud> is a pointer to the
8373 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
8374 * is the previously allocated size or the kind of object in case of a new
8375 * allocation. <nsize> is the requested new size.
8376 */
8377static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
8378{
8379 struct hlua_mem_allocator *zone = ud;
8380
8381 if (nsize == 0) {
8382 /* it's a free */
8383 if (ptr)
8384 zone->allocated -= osize;
8385 free(ptr);
8386 return NULL;
8387 }
8388
8389 if (!ptr) {
8390 /* it's a new allocation */
8391 if (zone->limit && zone->allocated + nsize > zone->limit)
8392 return NULL;
8393
8394 ptr = malloc(nsize);
8395 if (ptr)
8396 zone->allocated += nsize;
8397 return ptr;
8398 }
8399
8400 /* it's a realloc */
8401 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
8402 return NULL;
8403
8404 ptr = realloc(ptr, nsize);
8405 if (ptr)
8406 zone->allocated += nsize - osize;
8407 return ptr;
8408}
8409
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008410/* Ithis function can fail with an abort() due to an Lua critical error.
8411 * We are in the initialisation process of HAProxy, this abort() is
8412 * tolerated.
8413 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008414void hlua_init(void)
8415{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008416 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008417 int idx;
8418 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008419 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008420 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008421 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008422#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008423 struct srv_kw *kw;
8424 int tmp_error;
8425 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008426 char *args[] = { /* SSL client configuration. */
8427 "ssl",
8428 "verify",
8429 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008430 NULL
8431 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008432#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008433
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008434 /* Init main lua stack. */
8435 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01008436 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01008437 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02008438 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008439 hlua_sethlua(&gL);
8440 gL.Tref = LUA_REFNIL;
8441 gL.task = NULL;
8442
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008443 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008444 * the Lua function can fail with an abort. We are in the initialisation
8445 * process of HAProxy, this abort() is tolerated.
8446 */
8447
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008448 /* Initialise lua. */
8449 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008450
Thierry Fournier75933d42016-01-21 09:30:18 +01008451 /* Set safe environment for the initialisation. */
8452 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008453 if (lua_type(gL.T, -1) == LUA_TSTRING)
8454 error_msg = lua_tostring(gL.T, -1);
8455 else
8456 error_msg = "critical error";
8457 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01008458 exit(1);
8459 }
8460
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008461 /*
8462 *
8463 * Create "core" object.
8464 *
8465 */
8466
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01008467 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008468 lua_newtable(gL.T);
8469
8470 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008471 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008472 hlua_class_const_int(gL.T, log_levels[i], i);
8473
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008474 /* Register special functions. */
8475 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008476 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008477 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008478 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008479 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008480 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008481 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008482 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01008483 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008484 hlua_class_function(gL.T, "sleep", hlua_sleep);
8485 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01008486 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
8487 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
8488 hlua_class_function(gL.T, "set_map", hlua_set_map);
8489 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008490 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008491 hlua_class_function(gL.T, "log", hlua_log);
8492 hlua_class_function(gL.T, "Debug", hlua_log_debug);
8493 hlua_class_function(gL.T, "Info", hlua_log_info);
8494 hlua_class_function(gL.T, "Warning", hlua_log_warning);
8495 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02008496 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01008497 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008498
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008499 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008500
8501 /*
8502 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008503 * Register class Map
8504 *
8505 */
8506
8507 /* This table entry is the object "Map" base. */
8508 lua_newtable(gL.T);
8509
8510 /* register pattern types. */
8511 for (i=0; i<PAT_MATCH_NUM; i++)
8512 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008513 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008514 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
8515 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008516 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008517
8518 /* register constructor. */
8519 hlua_class_function(gL.T, "new", hlua_map_new);
8520
8521 /* Create and fill the metatable. */
8522 lua_newtable(gL.T);
8523
8524 /* Create and fille the __index entry. */
8525 lua_pushstring(gL.T, "__index");
8526 lua_newtable(gL.T);
8527
8528 /* Register . */
8529 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
8530 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
8531
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008532 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008533
Thierry Fournier45e78d72016-02-19 18:34:46 +01008534 /* Register previous table in the registry with reference and named entry.
8535 * The function hlua_register_metatable() pops the stack, so we
8536 * previously create a copy of the table.
8537 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008538 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008539 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008540
8541 /* Assign the metatable to the mai Map object. */
8542 lua_setmetatable(gL.T, -2);
8543
8544 /* Set a name to the table. */
8545 lua_setglobal(gL.T, "Map");
8546
8547 /*
8548 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008549 * Register class Channel
8550 *
8551 */
8552
8553 /* Create and fill the metatable. */
8554 lua_newtable(gL.T);
8555
8556 /* Create and fille the __index entry. */
8557 lua_pushstring(gL.T, "__index");
8558 lua_newtable(gL.T);
8559
8560 /* Register . */
8561 hlua_class_function(gL.T, "get", hlua_channel_get);
8562 hlua_class_function(gL.T, "dup", hlua_channel_dup);
8563 hlua_class_function(gL.T, "getline", hlua_channel_getline);
8564 hlua_class_function(gL.T, "set", hlua_channel_set);
8565 hlua_class_function(gL.T, "append", hlua_channel_append);
8566 hlua_class_function(gL.T, "send", hlua_channel_send);
8567 hlua_class_function(gL.T, "forward", hlua_channel_forward);
8568 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
8569 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01008570 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008571
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008572 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008573
8574 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008575 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008576
8577 /*
8578 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008579 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008580 *
8581 */
8582
8583 /* Create and fill the metatable. */
8584 lua_newtable(gL.T);
8585
8586 /* Create and fille the __index entry. */
8587 lua_pushstring(gL.T, "__index");
8588 lua_newtable(gL.T);
8589
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008590 /* Browse existing fetches and create the associated
8591 * object method.
8592 */
8593 sf = NULL;
8594 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
8595
8596 /* Dont register the keywork if the arguments check function are
8597 * not safe during the runtime.
8598 */
8599 if ((sf->val_args != NULL) &&
8600 (sf->val_args != val_payload_lv) &&
8601 (sf->val_args != val_hdr))
8602 continue;
8603
8604 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8605 * by an underscore.
8606 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008607 strncpy(trash.area, sf->kw, trash.size);
8608 trash.area[trash.size - 1] = '\0';
8609 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008610 if (*p == '.' || *p == '-' || *p == '+')
8611 *p = '_';
8612
8613 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008614 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01008615 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008616 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008617 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008618 }
8619
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008620 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008621
8622 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008623 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008624
8625 /*
8626 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008627 * Register class Converters
8628 *
8629 */
8630
8631 /* Create and fill the metatable. */
8632 lua_newtable(gL.T);
8633
8634 /* Create and fill the __index entry. */
8635 lua_pushstring(gL.T, "__index");
8636 lua_newtable(gL.T);
8637
8638 /* Browse existing converters and create the associated
8639 * object method.
8640 */
8641 sc = NULL;
8642 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
8643 /* Dont register the keywork if the arguments check function are
8644 * not safe during the runtime.
8645 */
8646 if (sc->val_args != NULL)
8647 continue;
8648
8649 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8650 * by an underscore.
8651 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008652 strncpy(trash.area, sc->kw, trash.size);
8653 trash.area[trash.size - 1] = '\0';
8654 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008655 if (*p == '.' || *p == '-' || *p == '+')
8656 *p = '_';
8657
8658 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008659 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008660 lua_pushlightuserdata(gL.T, sc);
8661 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008662 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008663 }
8664
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008665 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008666
8667 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008668 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008669
8670 /*
8671 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008672 * Register class HTTP
8673 *
8674 */
8675
8676 /* Create and fill the metatable. */
8677 lua_newtable(gL.T);
8678
8679 /* Create and fille the __index entry. */
8680 lua_pushstring(gL.T, "__index");
8681 lua_newtable(gL.T);
8682
8683 /* Register Lua functions. */
8684 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
8685 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
8686 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
8687 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
8688 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
8689 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
8690 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
8691 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
8692 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
8693 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
8694
8695 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
8696 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
8697 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
8698 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
8699 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
8700 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02008701 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008702
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008703 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008704
8705 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008706 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008707
8708 /*
8709 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008710 * Register class AppletTCP
8711 *
8712 */
8713
8714 /* Create and fill the metatable. */
8715 lua_newtable(gL.T);
8716
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008717 /* Create and fille the __index entry. */
8718 lua_pushstring(gL.T, "__index");
8719 lua_newtable(gL.T);
8720
8721 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01008722 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
8723 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
8724 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
8725 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
8726 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008727 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
8728 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
8729 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008730
8731 lua_settable(gL.T, -3);
8732
8733 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008734 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008735
8736 /*
8737 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008738 * Register class AppletHTTP
8739 *
8740 */
8741
8742 /* Create and fill the metatable. */
8743 lua_newtable(gL.T);
8744
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008745 /* Create and fille the __index entry. */
8746 lua_pushstring(gL.T, "__index");
8747 lua_newtable(gL.T);
8748
8749 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01008750 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
8751 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008752 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
8753 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
8754 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008755 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
8756 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
8757 hlua_class_function(gL.T, "send", hlua_applet_http_send);
8758 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
8759 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
8760 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
8761
8762 lua_settable(gL.T, -3);
8763
8764 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008765 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008766
8767 /*
8768 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008769 * Register class TXN
8770 *
8771 */
8772
8773 /* Create and fill the metatable. */
8774 lua_newtable(gL.T);
8775
8776 /* Create and fille the __index entry. */
8777 lua_pushstring(gL.T, "__index");
8778 lua_newtable(gL.T);
8779
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008780 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04008781 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
8782 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
8783 hlua_class_function(gL.T, "set_var", hlua_set_var);
8784 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
8785 hlua_class_function(gL.T, "get_var", hlua_get_var);
8786 hlua_class_function(gL.T, "done", hlua_txn_done);
8787 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
8788 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
8789 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
8790 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
8791 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
8792 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
8793 hlua_class_function(gL.T, "log", hlua_txn_log);
8794 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
8795 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
8796 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
8797 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008798
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008799 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008800
8801 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008802 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008803
8804 /*
8805 *
8806 * Register class Socket
8807 *
8808 */
8809
8810 /* Create and fill the metatable. */
8811 lua_newtable(gL.T);
8812
8813 /* Create and fille the __index entry. */
8814 lua_pushstring(gL.T, "__index");
8815 lua_newtable(gL.T);
8816
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008817#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008818 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008819#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008820 hlua_class_function(gL.T, "connect", hlua_socket_connect);
8821 hlua_class_function(gL.T, "send", hlua_socket_send);
8822 hlua_class_function(gL.T, "receive", hlua_socket_receive);
8823 hlua_class_function(gL.T, "close", hlua_socket_close);
8824 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
8825 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8826 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8827 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8828
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008829 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008830
8831 /* Register the garbage collector entry. */
8832 lua_pushstring(gL.T, "__gc");
8833 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008834 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008835
8836 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008837 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008838
8839 /* Proxy and server configuration initialisation. */
8840 memset(&socket_proxy, 0, sizeof(socket_proxy));
8841 init_new_proxy(&socket_proxy);
8842 socket_proxy.parent = NULL;
8843 socket_proxy.last_change = now.tv_sec;
8844 socket_proxy.id = "LUA-SOCKET";
8845 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8846 socket_proxy.maxconn = 0;
8847 socket_proxy.accept = NULL;
8848 socket_proxy.options2 |= PR_O2_INDEPSTR;
8849 socket_proxy.srv = NULL;
8850 socket_proxy.conn_retries = 0;
8851 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8852
8853 /* Init TCP server: unchanged parameters */
8854 memset(&socket_tcp, 0, sizeof(socket_tcp));
8855 socket_tcp.next = NULL;
8856 socket_tcp.proxy = &socket_proxy;
8857 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8858 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008859 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008860 socket_tcp.priv_conns = NULL;
8861 socket_tcp.idle_conns = NULL;
8862 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008863 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008864 socket_tcp.last_change = 0;
8865 socket_tcp.id = "LUA-TCP-CONN";
8866 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8867 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8868 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
8869
8870 /* XXX: Copy default parameter from default server,
8871 * but the default server is not initialized.
8872 */
8873 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
8874 socket_tcp.minconn = socket_proxy.defsrv.minconn;
8875 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
8876 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
8877 socket_tcp.onerror = socket_proxy.defsrv.onerror;
8878 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8879 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
8880 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8881 socket_tcp.uweight = socket_proxy.defsrv.iweight;
8882 socket_tcp.iweight = socket_proxy.defsrv.iweight;
8883
8884 socket_tcp.check.status = HCHK_STATUS_INI;
8885 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
8886 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
8887 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
8888 socket_tcp.check.server = &socket_tcp;
8889
8890 socket_tcp.agent.status = HCHK_STATUS_INI;
8891 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
8892 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
8893 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
8894 socket_tcp.agent.server = &socket_tcp;
8895
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008896 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008897
8898#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008899 /* Init TCP server: unchanged parameters */
8900 memset(&socket_ssl, 0, sizeof(socket_ssl));
8901 socket_ssl.next = NULL;
8902 socket_ssl.proxy = &socket_proxy;
8903 socket_ssl.obj_type = OBJ_TYPE_SERVER;
8904 LIST_INIT(&socket_ssl.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008905 socket_ssl.pendconns = EB_ROOT;
Willy Tarreaub784b352019-02-07 14:48:24 +01008906 socket_ssl.priv_conns = NULL;
8907 socket_ssl.idle_conns = NULL;
8908 socket_ssl.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008909 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008910 socket_ssl.last_change = 0;
8911 socket_ssl.id = "LUA-SSL-CONN";
8912 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8913 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8914 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8915
8916 /* XXX: Copy default parameter from default server,
8917 * but the default server is not initialized.
8918 */
8919 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8920 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8921 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8922 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8923 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8924 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8925 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8926 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8927 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8928 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8929
8930 socket_ssl.check.status = HCHK_STATUS_INI;
8931 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8932 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8933 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8934 socket_ssl.check.server = &socket_ssl;
8935
8936 socket_ssl.agent.status = HCHK_STATUS_INI;
8937 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8938 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8939 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8940 socket_ssl.agent.server = &socket_ssl;
8941
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008942 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008943 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008944
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008945 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008946 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8947 /*
8948 *
8949 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008950 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008951 * features like client certificates and ssl_verify.
8952 *
8953 */
8954 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8955 if (tmp_error != 0) {
8956 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8957 abort(); /* This must be never arrives because the command line
8958 not editable by the user. */
8959 }
8960 idx += kw->skip;
8961 }
8962 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008963#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008964
8965 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008966}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008967
Willy Tarreau80713382018-11-26 10:19:54 +01008968static void hlua_register_build_options(void)
8969{
Willy Tarreaubb57d942016-12-21 19:04:56 +01008970 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +01008971
Willy Tarreaubb57d942016-12-21 19:04:56 +01008972 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8973 hap_register_build_opts(ptr, 1);
8974}
Willy Tarreau80713382018-11-26 10:19:54 +01008975
8976INITCALL0(STG_REGISTER, hlua_register_build_options);