blob: c2d045ec2e086c02723cec2e890d63ac9dcb6b28 [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. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100157/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200158#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);
Tim Duesterhusf371b832019-09-29 23:03:07 +0200433 /* We don't know the actual size of the underlying allocation, so be conservative. */
434 arg->data.str.size = arg->data.str.data;
435 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100436 break;
437
438 case LUA_TUSERDATA:
439 case LUA_TNIL:
440 case LUA_TTABLE:
441 case LUA_TFUNCTION:
442 case LUA_TTHREAD:
443 case LUA_TLIGHTUSERDATA:
444 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200445 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100446 break;
447 }
448 return 1;
449}
450
451/* the following functions are used to convert a struct sample
452 * in Lua type. This useful to convert the return of the
453 * fetchs or converters.
454 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100455static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100456{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200457 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100458 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100459 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200460 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100461 break;
462
463 case SMP_T_BIN:
464 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200465 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100466 break;
467
468 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200469 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100470 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
471 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
472 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
473 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
474 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
475 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
476 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
477 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
478 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200479 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100480 break;
481 default:
482 lua_pushnil(L);
483 break;
484 }
485 break;
486
487 case SMP_T_IPV4:
488 case SMP_T_IPV6:
489 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200490 if (sample_casts[smp->data.type][SMP_T_STR] &&
491 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200492 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100493 else
494 lua_pushnil(L);
495 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100496 default:
497 lua_pushnil(L);
498 break;
499 }
500 return 1;
501}
502
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100503/* the following functions are used to convert a struct sample
504 * in Lua strings. This is useful to convert the return of the
505 * fetchs or converters.
506 */
507static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
508{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200509 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100510
511 case SMP_T_BIN:
512 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200513 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100514 break;
515
516 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200517 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100518 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
519 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
520 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
521 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
522 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
523 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
524 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
525 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
526 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200527 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100528 break;
529 default:
530 lua_pushstring(L, "");
531 break;
532 }
533 break;
534
535 case SMP_T_SINT:
536 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100537 case SMP_T_IPV4:
538 case SMP_T_IPV6:
539 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200540 if (sample_casts[smp->data.type][SMP_T_STR] &&
541 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200542 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100543 else
544 lua_pushstring(L, "");
545 break;
546 default:
547 lua_pushstring(L, "");
548 break;
549 }
550 return 1;
551}
552
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100553/* the following functions are used to convert an Lua type in a
554 * struct sample. This is useful to provide data from a converter
555 * to the LUA code.
556 */
557static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
558{
559 switch (lua_type(L, ud)) {
560
561 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200562 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200563 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100564 break;
565
566
567 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200568 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200569 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100570 break;
571
572 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200573 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100574 smp->flags |= SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200575 smp->data.u.str.area = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.data);
Tim Duesterhusf371b832019-09-29 23:03:07 +0200576 /* We don't know the actual size of the underlying allocation, so be conservative. */
577 smp->data.u.str.size = smp->data.u.str.data;
578 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100579 break;
580
581 case LUA_TUSERDATA:
582 case LUA_TNIL:
583 case LUA_TTABLE:
584 case LUA_TFUNCTION:
585 case LUA_TTHREAD:
586 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200587 case LUA_TNONE:
588 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200589 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200590 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100591 break;
592 }
593 return 1;
594}
595
596/* This function check the "argp" builded by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800597 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100598 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100599 *
600 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
601 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100602 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100603__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100604 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100605{
606 int min_arg;
607 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100608 struct proxy *px;
609 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100610
611 idx = 0;
612 min_arg = ARGM(mask);
613 mask >>= ARGM_BITS;
614
615 while (1) {
616
617 /* Check oversize. */
618 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100619 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100620 }
621
622 /* Check for mandatory arguments. */
623 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100624 if (idx < min_arg) {
625
626 /* If miss other argument than the first one, we return an error. */
627 if (idx > 0)
628 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
629
630 /* If first argument have a certain type, some default values
631 * may be used. See the function smp_resolve_args().
632 */
633 switch (mask & ARGT_MASK) {
634
635 case ARGT_FE:
636 if (!(p->cap & PR_CAP_FE))
637 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
638 argp[idx].data.prx = p;
639 argp[idx].type = ARGT_FE;
640 argp[idx+1].type = ARGT_STOP;
641 break;
642
643 case ARGT_BE:
644 if (!(p->cap & PR_CAP_BE))
645 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
646 argp[idx].data.prx = p;
647 argp[idx].type = ARGT_BE;
648 argp[idx+1].type = ARGT_STOP;
649 break;
650
651 case ARGT_TAB:
652 argp[idx].data.prx = p;
653 argp[idx].type = ARGT_TAB;
654 argp[idx+1].type = ARGT_STOP;
655 break;
656
657 default:
658 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
659 break;
660 }
661 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100662 return 0;
663 }
664
665 /* Check for exceed the number of requiered argument. */
666 if ((mask & ARGT_MASK) == ARGT_STOP &&
667 argp[idx].type != ARGT_STOP) {
668 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
669 }
670
671 if ((mask & ARGT_MASK) == ARGT_STOP &&
672 argp[idx].type == ARGT_STOP) {
673 return 0;
674 }
675
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100676 /* Convert some argument types. */
677 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100678 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100679 if (argp[idx].type != ARGT_SINT)
680 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
681 argp[idx].type = ARGT_SINT;
682 break;
683
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100684 case ARGT_TIME:
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_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100688 break;
689
690 case ARGT_SIZE:
691 if (argp[idx].type != ARGT_SINT)
692 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200693 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100694 break;
695
696 case ARGT_FE:
697 if (argp[idx].type != ARGT_STR)
698 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200699 memcpy(trash.area, argp[idx].data.str.area,
700 argp[idx].data.str.data);
701 trash.area[argp[idx].data.str.data] = 0;
702 argp[idx].data.prx = proxy_fe_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100703 if (!argp[idx].data.prx)
704 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
705 argp[idx].type = ARGT_FE;
706 break;
707
708 case ARGT_BE:
709 if (argp[idx].type != ARGT_STR)
710 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200711 memcpy(trash.area, argp[idx].data.str.area,
712 argp[idx].data.str.data);
713 trash.area[argp[idx].data.str.data] = 0;
714 argp[idx].data.prx = proxy_be_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100715 if (!argp[idx].data.prx)
716 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
717 argp[idx].type = ARGT_BE;
718 break;
719
720 case ARGT_TAB:
721 if (argp[idx].type != ARGT_STR)
722 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200723 memcpy(trash.area, argp[idx].data.str.area,
724 argp[idx].data.str.data);
725 trash.area[argp[idx].data.str.data] = 0;
Tim Duesterhuse351e762019-09-29 23:03:09 +0200726 argp[idx].data.t = stktable_find_by_name(trash.area);
727 if (!argp[idx].data.t)
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100728 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
729 argp[idx].type = ARGT_TAB;
730 break;
731
732 case ARGT_SRV:
733 if (argp[idx].type != ARGT_STR)
734 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200735 memcpy(trash.area, argp[idx].data.str.area,
736 argp[idx].data.str.data);
737 trash.area[argp[idx].data.str.data] = 0;
738 sname = strrchr(trash.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100739 if (sname) {
740 *sname++ = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200741 pname = trash.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200742 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100743 if (!px)
744 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
745 }
746 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200747 sname = trash.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100748 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100749 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100750 argp[idx].data.srv = findserver(px, sname);
751 if (!argp[idx].data.srv)
752 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
753 argp[idx].type = ARGT_SRV;
754 break;
755
756 case ARGT_IPV4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200757 memcpy(trash.area, argp[idx].data.str.area,
758 argp[idx].data.str.data);
759 trash.area[argp[idx].data.str.data] = 0;
760 if (inet_pton(AF_INET, trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100761 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
762 argp[idx].type = ARGT_IPV4;
763 break;
764
765 case ARGT_MSK4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200766 memcpy(trash.area, argp[idx].data.str.area,
767 argp[idx].data.str.data);
768 trash.area[argp[idx].data.str.data] = 0;
769 if (!str2mask(trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100770 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
771 argp[idx].type = ARGT_MSK4;
772 break;
773
774 case ARGT_IPV6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200775 memcpy(trash.area, argp[idx].data.str.area,
776 argp[idx].data.str.data);
777 trash.area[argp[idx].data.str.data] = 0;
778 if (inet_pton(AF_INET6, trash.area, &argp[idx].data.ipv6))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100779 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
780 argp[idx].type = ARGT_IPV6;
781 break;
782
783 case ARGT_MSK6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200784 memcpy(trash.area, argp[idx].data.str.area,
785 argp[idx].data.str.data);
786 trash.area[argp[idx].data.str.data] = 0;
787 if (!str2mask6(trash.area, &argp[idx].data.ipv6))
Tim Duesterhusb814da62018-01-25 16:24:50 +0100788 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 mask"));
789 argp[idx].type = ARGT_MSK6;
790 break;
791
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100792 case ARGT_MAP:
793 case ARGT_REG:
794 case ARGT_USR:
795 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100796 break;
797 }
798
799 /* Check for type of argument. */
800 if ((mask & ARGT_MASK) != argp[idx].type) {
801 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
802 arg_type_names[(mask & ARGT_MASK)],
803 arg_type_names[argp[idx].type & ARGT_MASK]);
804 WILL_LJMP(luaL_argerror(L, first + idx, msg));
805 }
806
807 /* Next argument. */
808 mask >>= ARGT_BITS;
809 idx++;
810 }
811}
812
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100813/*
814 * The following functions are used to make correspondance between the the
815 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100816 *
817 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100818 * - hlua_sethlua : create the association between hlua context and lua_state.
819 */
820static inline struct hlua *hlua_gethlua(lua_State *L)
821{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100822 struct hlua **hlua = lua_getextraspace(L);
823 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100824}
825static inline void hlua_sethlua(struct hlua *hlua)
826{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100827 struct hlua **hlua_store = lua_getextraspace(hlua->T);
828 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100829}
830
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100831/* This function is used to send logs. It try to send on screen (stderr)
832 * and on the default syslog server.
833 */
834static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
835{
836 struct tm tm;
837 char *p;
838
839 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200840 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100841 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200842 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200843 /* Break the message if exceed the buffer size. */
844 *(p-4) = ' ';
845 *(p-3) = '.';
846 *(p-2) = '.';
847 *(p-1) = '.';
848 break;
849 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100850 if (isprint(*msg))
851 *p = *msg;
852 else
853 *p = '.';
854 }
855 *p = '\0';
856
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200857 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100858 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200859 get_localtime(date.tv_sec, &tm);
860 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100861 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200862 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100863 fflush(stderr);
864 }
865}
866
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100867/* This function just ensure that the yield will be always
868 * returned with a timeout and permit to set some flags
869 */
870__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100871 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100872{
873 struct hlua *hlua = hlua_gethlua(L);
874
875 /* Set the wake timeout. If timeout is required, we set
876 * the expiration time.
877 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200878 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100879
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100880 hlua->flags |= flags;
881
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100882 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +0200883 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100884}
885
Willy Tarreau87b09662015-04-03 00:22:06 +0200886/* This function initialises the Lua environment stored in the stream.
887 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100888 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200889 *
890 * This function is particular. it initialises a new Lua thread. If the
891 * initialisation fails (example: out of memory error), the lua function
892 * throws an error (longjmp).
893 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100894 * In some case (at least one), this function can be called from safe
895 * environement, so we must not initialise it. While the support of
896 * threads appear, the safe environment set a lock to ensure only one
897 * Lua execution at a time. If we initialize safe environment in another
898 * safe environmenet, we have a dead lock.
899 *
900 * set "already_safe" true if the context is initialized form safe
901 * Lua fonction.
902 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800903 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200904 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800905 * MUST NOT manipulate the created thread stack state, because it is not
906 * proctected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100907 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100908int hlua_ctx_init(struct hlua *lua, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100909{
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100910 if (!already_safe) {
911 if (!SET_SAFE_LJMP(gL.T)) {
912 lua->Tref = LUA_REFNIL;
913 return 0;
914 }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200915 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100916 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100917 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100918 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100919 lua->T = lua_newthread(gL.T);
920 if (!lua->T) {
921 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100922 if (!already_safe)
923 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100924 return 0;
925 }
926 hlua_sethlua(lua);
927 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
928 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100929 if (!already_safe)
930 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100931 return 1;
932}
933
Willy Tarreau87b09662015-04-03 00:22:06 +0200934/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100935 * is destroyed. The destroy also the memory context. The struct "lua"
936 * is not freed.
937 */
938void hlua_ctx_destroy(struct hlua *lua)
939{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100940 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100941 return;
942
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100943 if (!lua->T)
944 goto end;
945
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100946 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +0200947 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100948
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200949 if (!SET_SAFE_LJMP(lua->T))
950 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100951 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200952 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200953
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200954 if (!SET_SAFE_LJMP(gL.T))
955 return;
956 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
957 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200958 /* Forces a garbage collecting process. If the Lua program is finished
959 * without error, we run the GC on the thread pointer. Its freed all
960 * the unused memory.
961 * If the thread is finnish with an error or is currently yielded,
962 * it seems that the GC applied on the thread doesn't clean anything,
963 * so e run the GC on the main thread.
964 * NOTE: maybe this action locks all the Lua threads untiml the en of
965 * the garbage collection.
966 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200967 if (lua->flags & HLUA_MUST_GC) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200968 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200969 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200970 lua_gc(gL.T, LUA_GCCOLLECT, 0);
971 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200972 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200973
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200974 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100975
976end:
Willy Tarreaubafbe012017-11-24 17:34:44 +0100977 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100978}
979
980/* This function is used to restore the Lua context when a coroutine
981 * fails. This function copy the common memory between old coroutine
982 * and the new coroutine. The old coroutine is destroyed, and its
983 * replaced by the new coroutine.
984 * If the flag "keep_msg" is set, the last entry of the old is assumed
985 * as string error message and it is copied in the new stack.
986 */
987static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
988{
989 lua_State *T;
990 int new_ref;
991
992 /* Renew the main LUA stack doesn't have sense. */
993 if (lua == &gL)
994 return 0;
995
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100996 /* New Lua coroutine. */
997 T = lua_newthread(gL.T);
998 if (!T)
999 return 0;
1000
1001 /* Copy last error message. */
1002 if (keep_msg)
1003 lua_xmove(lua->T, T, 1);
1004
1005 /* Copy data between the coroutines. */
1006 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1007 lua_xmove(lua->T, T, 1);
1008 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
1009
1010 /* Destroy old data. */
1011 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1012
1013 /* The thread is garbage collected by Lua. */
1014 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
1015
1016 /* Fill the struct with the new coroutine values. */
1017 lua->Mref = new_ref;
1018 lua->T = T;
1019 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
1020
1021 /* Set context. */
1022 hlua_sethlua(lua);
1023
1024 return 1;
1025}
1026
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001027void hlua_hook(lua_State *L, lua_Debug *ar)
1028{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001029 struct hlua *hlua = hlua_gethlua(L);
1030
1031 /* Lua cannot yield when its returning from a function,
1032 * so, we can fix the interrupt hook to 1 instruction,
1033 * expecting that the function is finnished.
1034 */
1035 if (lua_gethookmask(L) & LUA_MASKRET) {
1036 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1037 return;
1038 }
1039
1040 /* restore the interrupt condition. */
1041 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1042
1043 /* If we interrupt the Lua processing in yieldable state, we yield.
1044 * If the state is not yieldable, trying yield causes an error.
1045 */
1046 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001047 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001048
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001049 /* If we cannot yield, update the clock and check the timeout. */
1050 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001051 hlua->run_time += now_ms - hlua->start_time;
1052 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001053 lua_pushfstring(L, "execution timeout");
1054 WILL_LJMP(lua_error(L));
1055 }
1056
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001057 /* Update the start time. */
1058 hlua->start_time = now_ms;
1059
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001060 /* Try to interrupt the process at the end of the current
1061 * unyieldable function.
1062 */
1063 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001064}
1065
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001066/* This function start or resumes the Lua stack execution. If the flag
1067 * "yield_allowed" if no set and the LUA stack execution returns a yield
1068 * The function return an error.
1069 *
1070 * The function can returns 4 values:
1071 * - HLUA_E_OK : The execution is terminated without any errors.
1072 * - HLUA_E_AGAIN : The execution must continue at the next associated
1073 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001074 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001075 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001076 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001077 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001078 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001079 * LUA code.
1080 */
1081static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1082{
Christopher Faulet20699902020-07-28 10:33:25 +02001083#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1084 int nres;
1085#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001086 int ret;
1087 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001088 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001089
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001090 /* Initialise run time counter. */
1091 if (!HLUA_IS_RUNNING(lua))
1092 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001093
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001094 /* Lock the whole Lua execution. This lock must be before the
1095 * label "resume_execution".
1096 */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001097 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001098
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001099resume_execution:
1100
1101 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1102 * instructions. it is used for preventing infinite loops.
1103 */
1104 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1105
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001106 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001107 HLUA_SET_RUN(lua);
1108 HLUA_CLR_CTRLYIELD(lua);
1109 HLUA_CLR_WAKERESWR(lua);
1110 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001111
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001112 /* Update the start time. */
1113 lua->start_time = now_ms;
1114
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001115 /* Call the function. */
Christopher Faulet20699902020-07-28 10:33:25 +02001116#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1117 ret = lua_resume(lua->T, gL.T, lua->nargs, &nres);
1118#else
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001119 ret = lua_resume(lua->T, gL.T, lua->nargs);
Christopher Faulet20699902020-07-28 10:33:25 +02001120#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001121 switch (ret) {
1122
1123 case LUA_OK:
1124 ret = HLUA_E_OK;
1125 break;
1126
1127 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001128 /* Check if the execution timeout is expired. It it is the case, we
1129 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001130 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001131 tv_update_date(0, 1);
1132 lua->run_time += now_ms - lua->start_time;
1133 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001134 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001135 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001136 break;
1137 }
1138 /* Process the forced yield. if the general yield is not allowed or
1139 * if no task were associated this the current Lua execution
1140 * coroutine, we resume the execution. Else we want to return in the
1141 * scheduler and we want to be waked up again, to continue the
1142 * current Lua execution. So we schedule our own task.
1143 */
1144 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001145 if (!yield_allowed || !lua->task)
1146 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001147 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001148 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001149 if (!yield_allowed) {
1150 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001151 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001152 break;
1153 }
1154 ret = HLUA_E_AGAIN;
1155 break;
1156
1157 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001158
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001159 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001160 * because the errors ares the only one mean to return immediately
1161 * from and lua execution.
1162 */
1163 if (lua->flags & HLUA_EXIT) {
1164 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001165 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001166 break;
1167 }
1168
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001169 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001170 if (!lua_checkstack(lua->T, 1)) {
1171 ret = HLUA_E_ERR;
1172 break;
1173 }
1174 msg = lua_tostring(lua->T, -1);
1175 lua_settop(lua->T, 0); /* Empty the stack. */
1176 lua_pop(lua->T, 1);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001177 trace = hlua_traceback(lua->T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001178 if (msg)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001179 lua_pushfstring(lua->T, "runtime error: %s from %s", msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001180 else
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001181 lua_pushfstring(lua->T, "unknown runtime error from %s", trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001182 ret = HLUA_E_ERRMSG;
1183 break;
1184
1185 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001186 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001187 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001188 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001189 break;
1190
1191 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001192 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001193 if (!lua_checkstack(lua->T, 1)) {
1194 ret = HLUA_E_ERR;
1195 break;
1196 }
1197 msg = lua_tostring(lua->T, -1);
1198 lua_settop(lua->T, 0); /* Empty the stack. */
1199 lua_pop(lua->T, 1);
1200 if (msg)
1201 lua_pushfstring(lua->T, "message handler error: %s", msg);
1202 else
1203 lua_pushfstring(lua->T, "message handler error");
1204 ret = HLUA_E_ERRMSG;
1205 break;
1206
1207 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001208 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001209 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001210 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001211 break;
1212 }
1213
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001214 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001215 if (lua->flags & HLUA_MUST_GC &&
1216 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001217 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1218
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001219 switch (ret) {
1220 case HLUA_E_AGAIN:
1221 break;
1222
1223 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001224 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001225 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001226 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001227 break;
1228
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001229 case HLUA_E_ETMOUT:
1230 case HLUA_E_NOMEM:
1231 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001232 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001233 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001234 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001235 hlua_ctx_renew(lua, 0);
1236 break;
1237
1238 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001239 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001240 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001241 break;
1242 }
1243
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001244 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001245 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001246
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001247 return ret;
1248}
1249
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001250/* This function exit the current code. */
1251__LJMP static int hlua_done(lua_State *L)
1252{
1253 struct hlua *hlua = hlua_gethlua(L);
1254
1255 hlua->flags |= HLUA_EXIT;
1256 WILL_LJMP(lua_error(L));
1257
1258 return 0;
1259}
1260
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001261/* This function is an LUA binding. It provides a function
1262 * for deleting ACL from a referenced ACL file.
1263 */
1264__LJMP static int hlua_del_acl(lua_State *L)
1265{
1266 const char *name;
1267 const char *key;
1268 struct pat_ref *ref;
1269
1270 MAY_LJMP(check_args(L, 2, "del_acl"));
1271
1272 name = MAY_LJMP(luaL_checkstring(L, 1));
1273 key = MAY_LJMP(luaL_checkstring(L, 2));
1274
1275 ref = pat_ref_lookup(name);
1276 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001277 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001278
Christopher Faulet9fa1f4e2020-06-03 18:39:16 +02001279 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001280 pat_ref_delete(ref, key);
Christopher Faulet9fa1f4e2020-06-03 18:39:16 +02001281 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001282 return 0;
1283}
1284
1285/* This function is an LUA binding. It provides a function
1286 * for deleting map entry from a referenced map file.
1287 */
1288static int hlua_del_map(lua_State *L)
1289{
1290 const char *name;
1291 const char *key;
1292 struct pat_ref *ref;
1293
1294 MAY_LJMP(check_args(L, 2, "del_map"));
1295
1296 name = MAY_LJMP(luaL_checkstring(L, 1));
1297 key = MAY_LJMP(luaL_checkstring(L, 2));
1298
1299 ref = pat_ref_lookup(name);
1300 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001301 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001302
Christopher Faulet9fa1f4e2020-06-03 18:39:16 +02001303 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001304 pat_ref_delete(ref, key);
Christopher Faulet9fa1f4e2020-06-03 18:39:16 +02001305 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001306 return 0;
1307}
1308
1309/* This function is an LUA binding. It provides a function
1310 * for adding ACL pattern from a referenced ACL file.
1311 */
1312static int hlua_add_acl(lua_State *L)
1313{
1314 const char *name;
1315 const char *key;
1316 struct pat_ref *ref;
1317
1318 MAY_LJMP(check_args(L, 2, "add_acl"));
1319
1320 name = MAY_LJMP(luaL_checkstring(L, 1));
1321 key = MAY_LJMP(luaL_checkstring(L, 2));
1322
1323 ref = pat_ref_lookup(name);
1324 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001325 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001326
Christopher Faulet9fa1f4e2020-06-03 18:39:16 +02001327 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001328 if (pat_ref_find_elt(ref, key) == NULL)
1329 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet9fa1f4e2020-06-03 18:39:16 +02001330 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001331 return 0;
1332}
1333
1334/* This function is an LUA binding. It provides a function
1335 * for setting map pattern and sample from a referenced map
1336 * file.
1337 */
1338static int hlua_set_map(lua_State *L)
1339{
1340 const char *name;
1341 const char *key;
1342 const char *value;
1343 struct pat_ref *ref;
1344
1345 MAY_LJMP(check_args(L, 3, "set_map"));
1346
1347 name = MAY_LJMP(luaL_checkstring(L, 1));
1348 key = MAY_LJMP(luaL_checkstring(L, 2));
1349 value = MAY_LJMP(luaL_checkstring(L, 3));
1350
1351 ref = pat_ref_lookup(name);
1352 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001353 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001354
Christopher Faulet9fa1f4e2020-06-03 18:39:16 +02001355 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001356 if (pat_ref_find_elt(ref, key) != NULL)
1357 pat_ref_set(ref, key, value, NULL);
1358 else
1359 pat_ref_add(ref, key, value, NULL);
Christopher Faulet9fa1f4e2020-06-03 18:39:16 +02001360 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001361 return 0;
1362}
1363
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001364/* A class is a lot of memory that contain data. This data can be a table,
1365 * an integer or user data. This data is associated with a metatable. This
1366 * metatable have an original version registred in the global context with
1367 * the name of the object (_G[<name>] = <metable> ).
1368 *
1369 * A metable is a table that modify the standard behavior of a standard
1370 * access to the associated data. The entries of this new metatable are
1371 * defined as is:
1372 *
1373 * http://lua-users.org/wiki/MetatableEvents
1374 *
1375 * __index
1376 *
1377 * we access an absent field in a table, the result is nil. This is
1378 * true, but it is not the whole truth. Actually, such access triggers
1379 * the interpreter to look for an __index metamethod: If there is no
1380 * such method, as usually happens, then the access results in nil;
1381 * otherwise, the metamethod will provide the result.
1382 *
1383 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1384 * the key does not appear in the table, but the metatable has an __index
1385 * property:
1386 *
1387 * - if the value is a function, the function is called, passing in the
1388 * table and the key; the return value of that function is returned as
1389 * the result.
1390 *
1391 * - if the value is another table, the value of the key in that table is
1392 * asked for and returned (and if it doesn't exist in that table, but that
1393 * table's metatable has an __index property, then it continues on up)
1394 *
1395 * - Use "rawget(myTable,key)" to skip this metamethod.
1396 *
1397 * http://www.lua.org/pil/13.4.1.html
1398 *
1399 * __newindex
1400 *
1401 * Like __index, but control property assignment.
1402 *
1403 * __mode - Control weak references. A string value with one or both
1404 * of the characters 'k' and 'v' which specifies that the the
1405 * keys and/or values in the table are weak references.
1406 *
1407 * __call - Treat a table like a function. When a table is followed by
1408 * parenthesis such as "myTable( 'foo' )" and the metatable has
1409 * a __call key pointing to a function, that function is invoked
1410 * (passing any specified arguments) and the return value is
1411 * returned.
1412 *
1413 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1414 * called, if the metatable for myTable has a __metatable
1415 * key, the value of that key is returned instead of the
1416 * actual metatable.
1417 *
1418 * __tostring - Control string representation. When the builtin
1419 * "tostring( myTable )" function is called, if the metatable
1420 * for myTable has a __tostring property set to a function,
1421 * that function is invoked (passing myTable to it) and the
1422 * return value is used as the string representation.
1423 *
1424 * __len - Control table length. When the table length is requested using
1425 * the length operator ( '#' ), if the metatable for myTable has
1426 * a __len key pointing to a function, that function is invoked
1427 * (passing myTable to it) and the return value used as the value
1428 * of "#myTable".
1429 *
1430 * __gc - Userdata finalizer code. When userdata is set to be garbage
1431 * collected, if the metatable has a __gc field pointing to a
1432 * function, that function is first invoked, passing the userdata
1433 * to it. The __gc metamethod is not called for tables.
1434 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1435 *
1436 * Special metamethods for redefining standard operators:
1437 * http://www.lua.org/pil/13.1.html
1438 *
1439 * __add "+"
1440 * __sub "-"
1441 * __mul "*"
1442 * __div "/"
1443 * __unm "!"
1444 * __pow "^"
1445 * __concat ".."
1446 *
1447 * Special methods for redfining standar relations
1448 * http://www.lua.org/pil/13.2.html
1449 *
1450 * __eq "=="
1451 * __lt "<"
1452 * __le "<="
1453 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001454
1455/*
1456 *
1457 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001458 * Class Map
1459 *
1460 *
1461 */
1462
1463/* Returns a struct hlua_map if the stack entry "ud" is
1464 * a class session, otherwise it throws an error.
1465 */
1466__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1467{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001468 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001469}
1470
1471/* This function is the map constructor. It don't need
1472 * the class Map object. It creates and return a new Map
1473 * object. It must be called only during "body" or "init"
1474 * context because it process some filesystem accesses.
1475 */
1476__LJMP static int hlua_map_new(struct lua_State *L)
1477{
1478 const char *fn;
1479 int match = PAT_MATCH_STR;
1480 struct sample_conv conv;
1481 const char *file = "";
1482 int line = 0;
1483 lua_Debug ar;
1484 char *err = NULL;
1485 struct arg args[2];
1486
1487 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1488 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1489
1490 fn = MAY_LJMP(luaL_checkstring(L, 1));
1491
1492 if (lua_gettop(L) >= 2) {
1493 match = MAY_LJMP(luaL_checkinteger(L, 2));
1494 if (match < 0 || match >= PAT_MATCH_NUM)
1495 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1496 }
1497
1498 /* Get Lua filename and line number. */
1499 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1500 lua_getinfo(L, "Sl", &ar); /* get info about it */
1501 if (ar.currentline > 0) { /* is there info? */
1502 file = ar.short_src;
1503 line = ar.currentline;
1504 }
1505 }
1506
1507 /* fill fake sample_conv struct. */
1508 conv.kw = ""; /* unused. */
1509 conv.process = NULL; /* unused. */
1510 conv.arg_mask = 0; /* unused. */
1511 conv.val_args = NULL; /* unused. */
1512 conv.out_type = SMP_T_STR;
1513 conv.private = (void *)(long)match;
1514 switch (match) {
1515 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1516 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1517 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1518 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1519 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1520 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1521 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001522 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001523 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1524 default:
1525 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1526 }
1527
1528 /* fill fake args. */
1529 args[0].type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001530 args[0].data.str.area = (char *)fn;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001531 args[1].type = ARGT_STOP;
1532
1533 /* load the map. */
1534 if (!sample_load_map(args, &conv, file, line, &err)) {
1535 /* error case: we cant use luaL_error because we must
1536 * free the err variable.
1537 */
1538 luaL_where(L, 1);
1539 lua_pushfstring(L, "'new': %s.", err);
1540 lua_concat(L, 2);
1541 free(err);
1542 WILL_LJMP(lua_error(L));
1543 }
1544
1545 /* create the lua object. */
1546 lua_newtable(L);
1547 lua_pushlightuserdata(L, args[0].data.map);
1548 lua_rawseti(L, -2, 0);
1549
1550 /* Pop a class Map metatable and affect it to the userdata. */
1551 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1552 lua_setmetatable(L, -2);
1553
1554
1555 return 1;
1556}
1557
1558__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1559{
1560 struct map_descriptor *desc;
1561 struct pattern *pat;
1562 struct sample smp;
1563
1564 MAY_LJMP(check_args(L, 2, "lookup"));
1565 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001566 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001567 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001568 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001569 }
1570 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001571 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001572 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001573 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 +02001574 }
1575
1576 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001577 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001578 if (str)
1579 lua_pushstring(L, "");
1580 else
1581 lua_pushnil(L);
1582 return 1;
1583 }
1584
1585 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001586 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001587 return 1;
1588}
1589
1590__LJMP static int hlua_map_lookup(struct lua_State *L)
1591{
1592 return _hlua_map_lookup(L, 0);
1593}
1594
1595__LJMP static int hlua_map_slookup(struct lua_State *L)
1596{
1597 return _hlua_map_lookup(L, 1);
1598}
1599
1600/*
1601 *
1602 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001603 * Class Socket
1604 *
1605 *
1606 */
1607
1608__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1609{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001610 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001611}
1612
1613/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001614 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001615 * received.
1616 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001617static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001618{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001619 struct stream_interface *si = appctx->owner;
Olivier Houchard9aaf7782017-09-13 18:30:23 +02001620 struct connection *c = cs_conn(objt_cs(si_opposite(si)->end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001621
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001622 if (appctx->ctx.hlua_cosocket.die) {
1623 si_shutw(si);
1624 si_shutr(si);
1625 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001626 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1627 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001628 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1629 }
1630
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001631 /* If the connection object is not available, close all the
1632 * streams and wakeup everything waiting for.
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001633 */
1634 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001635 si_shutw(si);
1636 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001637 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001638 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1639 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001640 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001641 }
1642
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001643 /* If we cant write, wakeup the pending write signals. */
1644 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001645 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001646
1647 /* If we cant read, wakeup the pending read signals. */
1648 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001649 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001650
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001651 /* if the connection is not estabkished, inform the stream that we want
1652 * to be notified whenever the connection completes.
1653 */
1654 if (!(c->flags & CO_FL_CONNECTED)) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01001655 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01001656 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01001657 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001658 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001659 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001660
1661 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001662 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001663
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001664 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001665 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001666 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001667
1668 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001669 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001670 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001671
1672 /* Some data were injected in the buffer, notify the stream
1673 * interface.
1674 */
1675 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001676 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001677
1678 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001679 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001680 */
1681 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01001682 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001683}
1684
Willy Tarreau87b09662015-04-03 00:22:06 +02001685/* This function is called when the "struct stream" is destroyed.
1686 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001687 * Wake all the pending signals.
1688 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001689static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001690{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001691 struct xref *peer;
1692
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001693 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001694 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1695 if (peer)
1696 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001697
1698 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001699 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1700 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001701}
1702
1703/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001704 * uses this object. If the stream does not exists, just quit.
1705 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001706 * pending signal can rest in the read and write lists. destroy
1707 * it.
1708 */
1709__LJMP static int hlua_socket_gc(lua_State *L)
1710{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001711 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001712 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001713 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001714
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001715 MAY_LJMP(check_args(L, 1, "__gc"));
1716
1717 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001718 peer = xref_get_peer_and_lock(&socket->xref);
1719 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001720 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001721 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001722
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001723 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001724 appctx->ctx.hlua_cosocket.die = 1;
1725 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001726
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001727 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001728 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001729 return 0;
1730}
1731
1732/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001733 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001734 */
sada05ed3302018-05-11 11:48:18 -07001735__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001736{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001737 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001738 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001739 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001740
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001741 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001742
1743 /* Check if we run on the same thread than the xreator thread.
1744 * We cannot access to the socket if the thread is different.
1745 */
1746 if (socket->tid != tid)
1747 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1748
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001749 peer = xref_get_peer_and_lock(&socket->xref);
1750 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001751 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001752 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001753
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001754 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001755 appctx->ctx.hlua_cosocket.die = 1;
1756 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001757
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001758 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001759 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001760 return 0;
1761}
1762
sada05ed3302018-05-11 11:48:18 -07001763/* The close function calls close_helper.
1764 */
1765__LJMP static int hlua_socket_close(lua_State *L)
1766{
1767 MAY_LJMP(check_args(L, 1, "close"));
1768 return hlua_socket_close_helper(L);
1769}
1770
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001771/* This Lua function assumes that the stack contain three parameters.
1772 * 1 - USERDATA containing a struct socket
1773 * 2 - INTEGER with values of the macro defined below
1774 * If the integer is -1, we must read at most one line.
1775 * If the integer is -2, we ust read all the data until the
1776 * end of the stream.
1777 * If the integer is positive value, we must read a number of
1778 * bytes corresponding to this value.
1779 */
1780#define HLSR_READ_LINE (-1)
1781#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001782__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001783{
1784 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1785 int wanted = lua_tointeger(L, 2);
1786 struct hlua *hlua = hlua_gethlua(L);
1787 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001788 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001789 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02001790 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001791 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02001792 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001793 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001794 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001795 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001796 struct stream_interface *si;
1797 struct stream *s;
1798 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001799 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001800
1801 /* Check if this lua stack is schedulable. */
1802 if (!hlua || !hlua->task)
1803 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1804 "'frontend', 'backend' or 'task'"));
1805
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001806 /* Check if we run on the same thread than the xreator thread.
1807 * We cannot access to the socket if the thread is different.
1808 */
1809 if (socket->tid != tid)
1810 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1811
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001812 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001813 peer = xref_get_peer_and_lock(&socket->xref);
1814 if (!peer)
1815 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001816 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1817 si = appctx->owner;
1818 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001819
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001820 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001821 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001822 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001823 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001824 if (nblk < 0) /* Connection close. */
1825 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001826 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001827 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001828
1829 /* remove final \r\n. */
1830 if (nblk == 1) {
1831 if (blk1[len1-1] == '\n') {
1832 len1--;
1833 skip_at_end++;
1834 if (blk1[len1-1] == '\r') {
1835 len1--;
1836 skip_at_end++;
1837 }
1838 }
1839 }
1840 else {
1841 if (blk2[len2-1] == '\n') {
1842 len2--;
1843 skip_at_end++;
1844 if (blk2[len2-1] == '\r') {
1845 len2--;
1846 skip_at_end++;
1847 }
1848 }
1849 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001850 }
1851
1852 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001853 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001854 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001855 if (nblk < 0) /* Connection close. */
1856 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001857 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001858 goto connection_empty;
1859 }
1860
1861 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001862 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001863 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001864 if (nblk < 0) /* Connection close. */
1865 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001866 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001867 goto connection_empty;
1868
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001869 missing_bytes = wanted - socket->b.n;
1870 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001871 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001872 len1 = missing_bytes;
1873 } if (nblk == 2 && len1 + len2 > missing_bytes)
1874 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001875 }
1876
1877 len = len1;
1878
1879 luaL_addlstring(&socket->b, blk1, len1);
1880 if (nblk == 2) {
1881 len += len2;
1882 luaL_addlstring(&socket->b, blk2, len2);
1883 }
1884
1885 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001886 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001887
1888 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02001889 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001890
1891 /* If the pattern reclaim to read all the data
1892 * in the connection, got out.
1893 */
1894 if (wanted == HLSR_READ_ALL)
1895 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001896 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001897 goto connection_empty;
1898
1899 /* Return result. */
1900 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001901 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001902 return 1;
1903
1904connection_closed:
1905
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001906 xref_unlock(&socket->xref, peer);
1907
1908no_peer:
1909
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001910 /* If the buffer containds data. */
1911 if (socket->b.n > 0) {
1912 luaL_pushresult(&socket->b);
1913 return 1;
1914 }
1915 lua_pushnil(L);
1916 lua_pushstring(L, "connection closed.");
1917 return 2;
1918
1919connection_empty:
1920
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001921 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1922 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001923 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001924 }
1925 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02001926 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001927 return 0;
1928}
1929
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001930/* This Lua function gets two parameters. The first one can be string
1931 * or a number. If the string is "*l", the user requires one line. If
1932 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001933 * If the value is a number, the user require a number of bytes equal
1934 * to the value. The default value is "*l" (a line).
1935 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001936 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001937 * integer takes this values:
1938 * -1 : read a line
1939 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001940 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001941 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001942 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001943 * concatenated with the read data.
1944 */
1945__LJMP static int hlua_socket_receive(struct lua_State *L)
1946{
1947 int wanted = HLSR_READ_LINE;
1948 const char *pattern;
1949 int type;
1950 char *error;
1951 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001952 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001953
1954 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1955 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1956
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001957 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001958
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001959 /* Check if we run on the same thread than the xreator thread.
1960 * We cannot access to the socket if the thread is different.
1961 */
1962 if (socket->tid != tid)
1963 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1964
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001965 /* check for pattern. */
1966 if (lua_gettop(L) >= 2) {
1967 type = lua_type(L, 2);
1968 if (type == LUA_TSTRING) {
1969 pattern = lua_tostring(L, 2);
1970 if (strcmp(pattern, "*a") == 0)
1971 wanted = HLSR_READ_ALL;
1972 else if (strcmp(pattern, "*l") == 0)
1973 wanted = HLSR_READ_LINE;
1974 else {
1975 wanted = strtoll(pattern, &error, 10);
1976 if (*error != '\0')
1977 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1978 }
1979 }
1980 else if (type == LUA_TNUMBER) {
1981 wanted = lua_tointeger(L, 2);
1982 if (wanted < 0)
1983 WILL_LJMP(luaL_error(L, "Unsupported size."));
1984 }
1985 }
1986
1987 /* Set pattern. */
1988 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01001989
1990 /* Check if we would replace the top by itself. */
1991 if (lua_gettop(L) != 2)
1992 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001993
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001994 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001995 luaL_buffinit(L, &socket->b);
1996
1997 /* Check prefix. */
1998 if (lua_gettop(L) >= 3) {
1999 if (lua_type(L, 3) != LUA_TSTRING)
2000 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2001 pattern = lua_tolstring(L, 3, &len);
2002 luaL_addlstring(&socket->b, pattern, len);
2003 }
2004
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002005 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002006}
2007
2008/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002009 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002010 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002011static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002012{
2013 struct hlua_socket *socket;
2014 struct hlua *hlua = hlua_gethlua(L);
2015 struct appctx *appctx;
2016 size_t buf_len;
2017 const char *buf;
2018 int len;
2019 int send_len;
2020 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002021 struct xref *peer;
2022 struct stream_interface *si;
2023 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002024
2025 /* Check if this lua stack is schedulable. */
2026 if (!hlua || !hlua->task)
2027 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2028 "'frontend', 'backend' or 'task'"));
2029
2030 /* Get object */
2031 socket = MAY_LJMP(hlua_checksocket(L, 1));
2032 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002033 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002034
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002035 /* Check if we run on the same thread than the xreator thread.
2036 * We cannot access to the socket if the thread is different.
2037 */
2038 if (socket->tid != tid)
2039 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2040
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002041 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002042 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002043 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002044 lua_pushinteger(L, -1);
2045 return 1;
2046 }
2047 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2048 si = appctx->owner;
2049 s = si_strm(si);
2050
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002051 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002052 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002053 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002054 lua_pushinteger(L, -1);
2055 return 1;
2056 }
2057
2058 /* Update the input buffer data. */
2059 buf += sent;
2060 send_len = buf_len - sent;
2061
2062 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002063 if (sent >= buf_len) {
2064 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002065 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002066 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002067
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002068 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002069 * the request buffer if its not required.
2070 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002071 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002072 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002073 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002074 }
2075
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002076 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002077 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002078 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002079 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002080 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002081
2082 /* send data */
2083 if (len < send_len)
2084 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002085 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002086
2087 /* "Not enough space" (-1), "Buffer too little to contain
2088 * the data" (-2) are not expected because the available length
2089 * is tested.
2090 * Other unknown error are also not expected.
2091 */
2092 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002093 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002094 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002095
sada05ed3302018-05-11 11:48:18 -07002096 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002097 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002098 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002099 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002100 return 1;
2101 }
2102
2103 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002104 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002105
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002106 s->req.rex = TICK_ETERNITY;
2107 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002108
2109 /* Update length sent. */
2110 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002111 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002112
2113 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002114 if (sent + len >= buf_len) {
2115 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002116 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002117 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002118
2119hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002120 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2121 xref_unlock(&socket->xref, peer);
2122 WILL_LJMP(luaL_error(L, "out of memory"));
2123 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002124 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002125 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002126 return 0;
2127}
2128
2129/* This function initiate the send of data. It just check the input
2130 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002131 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002132 * "hlua_socket_write_yield" that can yield.
2133 *
2134 * The Lua function gets between 3 and 4 parameters. The first one is
2135 * the associated object. The second is a string buffer. The third is
2136 * a facultative integer that represents where is the buffer position
2137 * of the start of the data that can send. The first byte is the
2138 * position "1". The default value is "1". The fourth argument is a
2139 * facultative integer that represents where is the buffer position
2140 * of the end of the data that can send. The default is the last byte.
2141 */
2142static int hlua_socket_send(struct lua_State *L)
2143{
2144 int i;
2145 int j;
2146 const char *buf;
2147 size_t buf_len;
2148
2149 /* Check number of arguments. */
2150 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2151 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2152
2153 /* Get the string. */
2154 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2155
2156 /* Get and check j. */
2157 if (lua_gettop(L) == 4) {
2158 j = MAY_LJMP(luaL_checkinteger(L, 4));
2159 if (j < 0)
2160 j = buf_len + j + 1;
2161 if (j > buf_len)
2162 j = buf_len + 1;
2163 lua_pop(L, 1);
2164 }
2165 else
2166 j = buf_len;
2167
2168 /* Get and check i. */
2169 if (lua_gettop(L) == 3) {
2170 i = MAY_LJMP(luaL_checkinteger(L, 3));
2171 if (i < 0)
2172 i = buf_len + i + 1;
2173 if (i > buf_len)
2174 i = buf_len + 1;
2175 lua_pop(L, 1);
2176 } else
2177 i = 1;
2178
2179 /* Check bth i and j. */
2180 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002181 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002182 return 1;
2183 }
2184 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002185 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186 return 1;
2187 }
2188 if (i == 0)
2189 i = 1;
2190 if (j == 0)
2191 j = 1;
2192
2193 /* Pop the string. */
2194 lua_pop(L, 1);
2195
2196 /* Update the buffer length. */
2197 buf += i - 1;
2198 buf_len = j - i + 1;
2199 lua_pushlstring(L, buf, buf_len);
2200
2201 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002202 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002203
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002204 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002205}
2206
Willy Tarreau22b0a682015-06-17 19:43:49 +02002207#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002208__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2209{
2210 static char buffer[SOCKET_INFO_MAX_LEN];
2211 int ret;
2212 int len;
2213 char *p;
2214
2215 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2216 if (ret <= 0) {
2217 lua_pushnil(L);
2218 return 1;
2219 }
2220
2221 if (ret == AF_UNIX) {
2222 lua_pushstring(L, buffer+1);
2223 return 1;
2224 }
2225 else if (ret == AF_INET6) {
2226 buffer[0] = '[';
2227 len = strlen(buffer);
2228 buffer[len] = ']';
2229 len++;
2230 buffer[len] = ':';
2231 len++;
2232 p = buffer;
2233 }
2234 else if (ret == AF_INET) {
2235 p = buffer + 1;
2236 len = strlen(p);
2237 p[len] = ':';
2238 len++;
2239 }
2240 else {
2241 lua_pushnil(L);
2242 return 1;
2243 }
2244
2245 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2246 lua_pushnil(L);
2247 return 1;
2248 }
2249
2250 lua_pushstring(L, p);
2251 return 1;
2252}
2253
2254/* Returns information about the peer of the connection. */
2255__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2256{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002257 struct hlua_socket *socket;
2258 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002259 struct xref *peer;
2260 struct appctx *appctx;
2261 struct stream_interface *si;
2262 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002263 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002264
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002265 MAY_LJMP(check_args(L, 1, "getpeername"));
2266
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002267 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002268
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002269 /* Check if we run on the same thread than the xreator thread.
2270 * We cannot access to the socket if the thread is different.
2271 */
2272 if (socket->tid != tid)
2273 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2274
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002275 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002276 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002277 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002278 lua_pushnil(L);
2279 return 1;
2280 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002281 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2282 si = appctx->owner;
2283 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002284
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002285 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002286 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002287 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002288 lua_pushnil(L);
2289 return 1;
2290 }
2291
Willy Tarreaua71f6422016-11-16 17:00:14 +01002292 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002293 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002294 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002295 lua_pushnil(L);
2296 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002297 }
2298
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002299 ret = MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2300 xref_unlock(&socket->xref, peer);
2301 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002302}
2303
2304/* Returns information about my connection side. */
2305static int hlua_socket_getsockname(struct lua_State *L)
2306{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002307 struct hlua_socket *socket;
2308 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002309 struct appctx *appctx;
2310 struct xref *peer;
2311 struct stream_interface *si;
2312 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002313 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002314
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002315 MAY_LJMP(check_args(L, 1, "getsockname"));
2316
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002317 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002318
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002319 /* Check if we run on the same thread than the xreator thread.
2320 * We cannot access to the socket if the thread is different.
2321 */
2322 if (socket->tid != tid)
2323 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2324
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002325 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002326 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002327 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002328 lua_pushnil(L);
2329 return 1;
2330 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002331 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2332 si = appctx->owner;
2333 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002334
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002335 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002336 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002337 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002338 lua_pushnil(L);
2339 return 1;
2340 }
2341
Willy Tarreaua71f6422016-11-16 17:00:14 +01002342 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002343 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002344 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002345 lua_pushnil(L);
2346 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002347 }
2348
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002349 ret = hlua_socket_info(L, &conn->addr.from);
2350 xref_unlock(&socket->xref, peer);
2351 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002352}
2353
2354/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002355static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002356 .obj_type = OBJ_TYPE_APPLET,
2357 .name = "<LUA_TCP>",
2358 .fct = hlua_socket_handler,
2359 .release = hlua_socket_release,
2360};
2361
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002362__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002363{
2364 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2365 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002366 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002367 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002368 struct stream_interface *si;
2369 struct stream *s;
2370
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002371 /* Check if we run on the same thread than the xreator thread.
2372 * We cannot access to the socket if the thread is different.
2373 */
2374 if (socket->tid != tid)
2375 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2376
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002377 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002378 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002379 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002380 lua_pushnil(L);
2381 lua_pushstring(L, "Can't connect");
2382 return 2;
2383 }
2384 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2385 si = appctx->owner;
2386 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002387
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002388 /* Check if we run on the same thread than the xreator thread.
2389 * We cannot access to the socket if the thread is different.
2390 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002391 if (socket->tid != tid) {
2392 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002393 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002394 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002395
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002396 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002397 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002398 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002399 lua_pushnil(L);
2400 lua_pushstring(L, "Can't connect");
2401 return 2;
2402 }
2403
Willy Tarreaue09101e2018-10-16 17:37:12 +02002404 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002405
2406 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002407 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002408 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002409 lua_pushinteger(L, 1);
2410 return 1;
2411 }
2412
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002413 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2414 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002415 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002416 }
2417 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002418 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002419 return 0;
2420}
2421
2422/* This function fail or initite the connection. */
2423__LJMP static int hlua_socket_connect(struct lua_State *L)
2424{
2425 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002426 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002427 const char *ip;
2428 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002429 struct hlua *hlua;
2430 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002431 int low, high;
2432 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002433 struct xref *peer;
2434 struct stream_interface *si;
2435 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002436
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002437 if (lua_gettop(L) < 2)
2438 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002439
2440 /* Get args. */
2441 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002442
2443 /* Check if we run on the same thread than the xreator thread.
2444 * We cannot access to the socket if the thread is different.
2445 */
2446 if (socket->tid != tid)
2447 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2448
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002449 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002450 if (lua_gettop(L) >= 3) {
2451 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002452 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002453
Tim Duesterhus6edab862018-01-06 19:04:45 +01002454 /* Force the ip to end with a colon, to support IPv6 addresses
2455 * that are not enclosed within square brackets.
2456 */
2457 if (port > 0) {
2458 luaL_buffinit(L, &b);
2459 luaL_addstring(&b, ip);
2460 luaL_addchar(&b, ':');
2461 luaL_pushresult(&b);
2462 ip = lua_tolstring(L, lua_gettop(L), NULL);
2463 }
2464 }
2465
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002466 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002467 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002468 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002469 lua_pushnil(L);
2470 return 1;
2471 }
2472 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2473 si = appctx->owner;
2474 s = si_strm(si);
2475
2476 /* Initialise connection. */
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002477 conn = cs_conn(si_alloc_cs(&s->si[1], NULL));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002478 if (!conn) {
2479 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002480 WILL_LJMP(luaL_error(L, "connect: internal error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002481 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002482
Willy Tarreau3adac082015-09-26 17:51:09 +02002483 /* needed for the connection not to be closed */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002484 conn->target = s->target;
Willy Tarreau3adac082015-09-26 17:51:09 +02002485
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002486 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002487 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002488 if (!addr) {
2489 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002490 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002491 }
2492 if (low != high) {
2493 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002494 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002495 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002496 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002497
2498 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002499 if (low == 0) {
2500 if (conn->addr.to.ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002501 if (port == -1) {
2502 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002503 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002504 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002505 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2506 } else if (conn->addr.to.ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002507 if (port == -1) {
2508 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002509 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002510 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002511 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2512 }
2513 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002514
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002515 hlua = hlua_gethlua(L);
Willy Tarreaue09101e2018-10-16 17:37:12 +02002516 appctx = __objt_appctx(s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002517
2518 /* inform the stream that we want to be notified whenever the
2519 * connection completes.
2520 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002521 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002522 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002523 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002524
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002525 hlua->flags |= HLUA_MUST_GC;
2526
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002527 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2528 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002529 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002530 }
2531 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002532
2533 task_wakeup(s->task, TASK_WOKEN_INIT);
2534 /* Return yield waiting for connection. */
2535
Willy Tarreau9635e032018-10-16 17:52:55 +02002536 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002537
2538 return 0;
2539}
2540
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002541#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002542__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2543{
2544 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002545 struct xref *peer;
2546 struct appctx *appctx;
2547 struct stream_interface *si;
2548 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002549
2550 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2551 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002552
2553 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002554 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002555 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002556 lua_pushnil(L);
2557 return 1;
2558 }
2559 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2560 si = appctx->owner;
2561 s = si_strm(si);
2562
2563 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002564 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002565 return MAY_LJMP(hlua_socket_connect(L));
2566}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002567#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002568
2569__LJMP static int hlua_socket_setoption(struct lua_State *L)
2570{
2571 return 0;
2572}
2573
2574__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2575{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002576 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002577 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002578 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002579 struct xref *peer;
2580 struct appctx *appctx;
2581 struct stream_interface *si;
2582 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002583
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002584 MAY_LJMP(check_args(L, 2, "settimeout"));
2585
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002586 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002587
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002588 /* convert the timeout to millis */
2589 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002590
Thierry Fournier17a921b2018-03-08 09:59:02 +01002591 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002592 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002593 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2594
Mark Lakes56cc1252018-03-27 09:48:06 +02002595 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002596 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002597
2598 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002599 if (tmout == 0)
2600 tmout++; /* very small timeouts are adjusted to a minium of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002601
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002602 /* Check if we run on the same thread than the xreator thread.
2603 * We cannot access to the socket if the thread is different.
2604 */
2605 if (socket->tid != tid)
2606 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2607
Mark Lakes56cc1252018-03-27 09:48:06 +02002608 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002609 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002610 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002611 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2612 WILL_LJMP(lua_error(L));
2613 return 0;
2614 }
2615 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2616 si = appctx->owner;
2617 s = si_strm(si);
2618
Cyril Bonté7bb63452018-08-17 23:51:02 +02002619 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002620 s->req.rto = tmout;
2621 s->req.wto = tmout;
2622 s->res.rto = tmout;
2623 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002624 s->req.rex = tick_add_ifset(now_ms, tmout);
2625 s->req.wex = tick_add_ifset(now_ms, tmout);
2626 s->res.rex = tick_add_ifset(now_ms, tmout);
2627 s->res.wex = tick_add_ifset(now_ms, tmout);
2628
2629 s->task->expire = tick_add_ifset(now_ms, tmout);
2630 task_queue(s->task);
2631
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002632 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002633
Thierry Fourniere9636f12018-03-08 09:54:32 +01002634 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002635 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002636}
2637
2638__LJMP static int hlua_socket_new(lua_State *L)
2639{
2640 struct hlua_socket *socket;
2641 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002642 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002643 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002644
2645 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002646 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002647 hlua_pusherror(L, "socket: full stack");
2648 goto out_fail_conf;
2649 }
2650
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002651 /* Create the object: obj[0] = userdata. */
2652 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002653 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002654 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002655 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002656 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002657
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002658 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002659 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002660 hlua_pusherror(L, "socket: uninitialized pools.");
2661 goto out_fail_conf;
2662 }
2663
Willy Tarreau87b09662015-04-03 00:22:06 +02002664 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002665 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2666 lua_setmetatable(L, -2);
2667
Willy Tarreaud420a972015-04-06 00:39:18 +02002668 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002669 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002670 if (!appctx) {
2671 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002672 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002673 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002674
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002675 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002676 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002677 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2678 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002679
Willy Tarreaud420a972015-04-06 00:39:18 +02002680 /* Now create a session, task and stream for this applet */
2681 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2682 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002683 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002684 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002685 }
2686
Willy Tarreau87787ac2017-08-28 16:22:54 +02002687 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002688 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002689 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002690 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002691 }
2692
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002693 /* Initialise cross reference between stream and Lua socket object. */
2694 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002695
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002696 /* Configure "right" stream interface. this "si" is used to connect
2697 * and retrieve data from the server. The connection is initialized
2698 * with the "struct server".
2699 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002700 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002701
2702 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002703 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2704 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002705
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002706 return 1;
2707
Willy Tarreaud420a972015-04-06 00:39:18 +02002708 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002709 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002710 out_fail_sess:
2711 appctx_free(appctx);
2712 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002713 WILL_LJMP(lua_error(L));
2714 return 0;
2715}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002716
2717/*
2718 *
2719 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002720 * Class Channel
2721 *
2722 *
2723 */
2724
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002725/* This function is called before the Lua execution. It stores
2726 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002727 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002728static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002729{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002730 c->mode = stream->be->mode;
2731 switch (c->mode) {
2732 case PR_MODE_HTTP:
2733 c->data.http.dir = opt & SMP_OPT_DIR;
2734 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2735 c->data.http.state = stream->txn->req.msg_state;
2736 else
2737 c->data.http.state = stream->txn->rsp.msg_state;
2738 break;
2739 default:
2740 break;
2741 }
2742}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002743
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002744/* This function is called after the Lua execution. it
2745 * returns true if the parser state is consistent, otherwise,
2746 * it return false.
2747 *
2748 * In HTTP mode, the parser state must be in the same state
2749 * or greater when we exit the function. Even if we do a
2750 * control yield. This prevent to break the HTTP message
2751 * from the Lua code.
2752 */
2753static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2754{
2755 if (c->mode != stream->be->mode)
2756 return 0;
2757
2758 switch (c->mode) {
2759 case PR_MODE_HTTP:
2760 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002761 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002762 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2763 return stream->txn->req.msg_state >= c->data.http.state;
2764 else
2765 return stream->txn->rsp.msg_state >= c->data.http.state;
2766 default:
2767 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002768 }
2769 return 1;
2770}
2771
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002772/* Returns the struct hlua_channel join to the class channel in the
2773 * stack entry "ud" or throws an argument error.
2774 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002775__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002776{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002777 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002778}
2779
Willy Tarreau47860ed2015-03-10 14:07:50 +01002780/* Pushes the channel onto the top of the stack. If the stask does not have a
2781 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002782 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002783static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002784{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002785 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002786 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002787 return 0;
2788
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002789 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002790 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002791 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002792
2793 /* Pop a class sesison metatable and affect it to the userdata. */
2794 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2795 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002796 return 1;
2797}
2798
2799/* Duplicate all the data present in the input channel and put it
2800 * in a string LUA variables. Returns -1 and push a nil value in
2801 * the stack if the channel is closed and all the data are consumed,
2802 * returns 0 if no data are available, otherwise it returns the length
2803 * of the builded string.
2804 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002805static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002806{
2807 char *blk1;
2808 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002809 size_t len1;
2810 size_t len2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002811 int ret;
2812 luaL_Buffer b;
2813
Willy Tarreau06d80a92017-10-19 14:32:15 +02002814 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002815 if (unlikely(ret == 0))
2816 return 0;
2817
2818 if (unlikely(ret < 0)) {
2819 lua_pushnil(L);
2820 return -1;
2821 }
2822
2823 luaL_buffinit(L, &b);
2824 luaL_addlstring(&b, blk1, len1);
2825 if (unlikely(ret == 2))
2826 luaL_addlstring(&b, blk2, len2);
2827 luaL_pushresult(&b);
2828
2829 if (unlikely(ret == 2))
2830 return len1 + len2;
2831 return len1;
2832}
2833
2834/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2835 * a yield. This function keep the data in the buffer.
2836 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002837__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002838{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002839 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002840
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002841 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2842
Christopher Faulet3f829a42018-12-13 21:56:45 +01002843 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2844 WILL_LJMP(lua_error(L));
2845
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002846 if (_hlua_channel_dup(chn, L) == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002847 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002848 return 1;
2849}
2850
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002851/* Check arguments for the function "hlua_channel_dup_yield". */
2852__LJMP static int hlua_channel_dup(lua_State *L)
2853{
2854 MAY_LJMP(check_args(L, 1, "dup"));
2855 MAY_LJMP(hlua_checkchannel(L, 1));
2856 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2857}
2858
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002859/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2860 * a yield. This function consumes the data in the buffer. It returns
2861 * a string containing the data or a nil pointer if no data are available
2862 * and the channel is closed.
2863 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002864__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002865{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002866 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002867 int ret;
2868
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002869 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002870
Christopher Faulet3f829a42018-12-13 21:56:45 +01002871 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2872 WILL_LJMP(lua_error(L));
2873
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002874 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002875 if (unlikely(ret == 0))
Willy Tarreau9635e032018-10-16 17:52:55 +02002876 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002877
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002878 if (unlikely(ret == -1))
2879 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002880
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002881 b_sub(&chn->buf, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002882 return 1;
2883}
2884
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002885/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002886__LJMP static int hlua_channel_get(lua_State *L)
2887{
2888 MAY_LJMP(check_args(L, 1, "get"));
2889 MAY_LJMP(hlua_checkchannel(L, 1));
2890 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2891}
2892
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002893/* This functions consumes and returns one line. If the channel is closed,
2894 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002895 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002896 * value.
2897 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002898__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002899{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002900 char *blk1;
2901 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002902 size_t len1;
2903 size_t len2;
2904 size_t len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002905 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002906 int ret;
2907 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002908
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002909 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2910
Christopher Faulet3f829a42018-12-13 21:56:45 +01002911 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2912 WILL_LJMP(lua_error(L));
2913
Willy Tarreau06d80a92017-10-19 14:32:15 +02002914 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002915 if (ret == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002916 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002917
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002918 if (ret == -1) {
2919 lua_pushnil(L);
2920 return 1;
2921 }
2922
2923 luaL_buffinit(L, &b);
2924 luaL_addlstring(&b, blk1, len1);
2925 len = len1;
2926 if (unlikely(ret == 2)) {
2927 luaL_addlstring(&b, blk2, len2);
2928 len += len2;
2929 }
2930 luaL_pushresult(&b);
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002931 b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn) + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002932 return 1;
2933}
2934
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002935/* Check arguments for the function "hlua_channel_getline_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002936__LJMP static int hlua_channel_getline(lua_State *L)
2937{
2938 MAY_LJMP(check_args(L, 1, "getline"));
2939 MAY_LJMP(hlua_checkchannel(L, 1));
2940 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2941}
2942
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002943/* This function takes a string as input, and append it at the
2944 * input side of channel. If the data is too big, but a space
2945 * is probably available after sending some data, the function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002946 * yields. If the data is bigger than the buffer, or if the
2947 * channel is closed, it returns -1. Otherwise, it returns the
2948 * amount of data written.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002949 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002950__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002951{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002952 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002953 size_t len;
2954 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2955 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2956 int ret;
2957 int max;
2958
Christopher Faulet3f829a42018-12-13 21:56:45 +01002959 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2960 WILL_LJMP(lua_error(L));
2961
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002962 /* Check if the buffer is available because HAProxy doesn't allocate
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002963 * the request buffer if its not required.
2964 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002965 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01002966 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02002967 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002968 }
2969
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002970 max = channel_recv_limit(chn) - b_data(&chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002971 if (max > len - l)
2972 max = len - l;
2973
Willy Tarreau06d80a92017-10-19 14:32:15 +02002974 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002975 if (ret == -2 || ret == -3) {
2976 lua_pushinteger(L, -1);
2977 return 1;
2978 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002979 if (ret == -1) {
2980 chn->flags |= CF_WAKE_WRITE;
Willy Tarreau9635e032018-10-16 17:52:55 +02002981 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002982 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002983 l += ret;
2984 lua_pop(L, 1);
2985 lua_pushinteger(L, l);
2986
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002987 max = channel_recv_limit(chn) - b_data(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02002988 if (max == 0 && co_data(chn) == 0) {
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002989 /* There are no space available, and the output buffer is empty.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002990 * in this case, we cannot add more data, so we cannot yield,
2991 * we return the amount of copyied data.
2992 */
2993 return 1;
2994 }
2995 if (l < len)
Willy Tarreau9635e032018-10-16 17:52:55 +02002996 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002997 return 1;
2998}
2999
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003000/* Just a wrapper of "hlua_channel_append_yield". It returns the length
3001 * of the written string, or -1 if the channel is closed or if the
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003002 * buffer size is too little for the data.
3003 */
3004__LJMP static int hlua_channel_append(lua_State *L)
3005{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003006 size_t len;
3007
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003008 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003009 MAY_LJMP(hlua_checkchannel(L, 1));
3010 MAY_LJMP(luaL_checklstring(L, 2, &len));
3011 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003012 lua_pushinteger(L, 0);
3013
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003014 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003015}
3016
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003017/* Just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003018 * his process by cleaning the buffer. The result is a replacement
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003019 * of the current data. It returns the length of the written string,
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003020 * or -1 if the channel is closed or if the buffer size is too
3021 * little for the data.
3022 */
3023__LJMP static int hlua_channel_set(lua_State *L)
3024{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003025 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003026
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003027 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003028 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003029 lua_pushinteger(L, 0);
3030
Christopher Faulet3f829a42018-12-13 21:56:45 +01003031 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
3032 WILL_LJMP(lua_error(L));
3033
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003034 b_set_data(&chn->buf, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003035
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003036 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003037}
3038
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003039/* Append data in the output side of the buffer. This data is immediately
3040 * sent. The function returns the amount of data written. If the buffer
3041 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003042 * if the channel is closed.
3043 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003044__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003045{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003046 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003047 size_t len;
3048 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3049 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3050 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003051 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003052
Christopher Faulet3f829a42018-12-13 21:56:45 +01003053 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
3054 WILL_LJMP(lua_error(L));
3055
Willy Tarreau47860ed2015-03-10 14:07:50 +01003056 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003057 lua_pushinteger(L, -1);
3058 return 1;
3059 }
3060
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003061 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003062 * the request buffer if its not required.
3063 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003064 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01003065 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02003066 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003067 }
3068
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003069 /* The written data will be immediately sent, so we can check
3070 * the available space without taking in account the reserve.
3071 * The reserve is guaranteed for the processing of incoming
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003072 * data, because the buffer will be flushed.
3073 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003074 max = b_room(&chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003075
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003076 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003077 * in this case, we cannot add more data, so we cannot yield,
3078 * we return the amount of copyied data.
3079 */
Willy Tarreaua79021a2018-06-15 18:07:57 +02003080 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003081 return 1;
3082
3083 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003084 if (max > len - l)
3085 max = len - l;
3086
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003087 /* The buffer available size may be not contiguous. This test
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003088 * detects a non contiguous buffer and realign it.
3089 */
Willy Tarreau3f679992018-06-15 15:06:42 +02003090 if (ci_space_for_replace(chn) < max)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003091 channel_slow_realign(chn, trash.area);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003092
3093 /* Copy input data in the buffer. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003094 max = b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn), str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003095
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003096 /* buffer replace considers that the input part is filled.
3097 * so, I must forward these new data in the output part.
3098 */
Willy Tarreaubcbd3932018-06-06 07:13:22 +02003099 c_adv(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003100
3101 l += max;
3102 lua_pop(L, 1);
3103 lua_pushinteger(L, l);
3104
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003105 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003106 * in this case, we cannot add more data, so we cannot yield,
3107 * we return the amount of copyied data.
3108 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003109 max = b_room(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003110 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003111 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003112
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003113 if (l < len) {
3114 /* If we are waiting for space in the response buffer, we
3115 * must set the flag WAKERESWR. This flag required the task
3116 * wake up if any activity is detected on the response buffer.
3117 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003118 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003119 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003120 else
3121 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003122 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003123 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003124
3125 return 1;
3126}
3127
3128/* Just a wraper of "_hlua_channel_send". This wrapper permits
3129 * yield the LUA process, and resume it without checking the
3130 * input arguments.
3131 */
3132__LJMP static int hlua_channel_send(lua_State *L)
3133{
3134 MAY_LJMP(check_args(L, 2, "send"));
3135 lua_pushinteger(L, 0);
3136
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003137 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003138}
3139
3140/* This function forward and amount of butes. The data pass from
3141 * the input side of the buffer to the output side, and can be
3142 * forwarded. This function never fails.
3143 *
3144 * The Lua function takes an amount of bytes to be forwarded in
3145 * imput. It returns the number of bytes forwarded.
3146 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003147__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003148{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003149 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003150 int len;
3151 int l;
3152 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003153 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003154
3155 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003156
3157 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
3158 WILL_LJMP(lua_error(L));
3159
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003160 len = MAY_LJMP(luaL_checkinteger(L, 2));
3161 l = MAY_LJMP(luaL_checkinteger(L, -1));
3162
3163 max = len - l;
Willy Tarreaua79021a2018-06-15 18:07:57 +02003164 if (max > ci_data(chn))
3165 max = ci_data(chn);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003166 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003167 l += max;
3168
3169 lua_pop(L, 1);
3170 lua_pushinteger(L, l);
3171
3172 /* Check if it miss bytes to forward. */
3173 if (l < len) {
3174 /* The the input channel or the output channel are closed, we
3175 * must return the amount of data forwarded.
3176 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003177 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003178 return 1;
3179
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003180 /* If we are waiting for space data in the response buffer, we
3181 * must set the flag WAKERESWR. This flag required the task
3182 * wake up if any activity is detected on the response buffer.
3183 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003184 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003185 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003186 else
3187 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003188
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003189 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003190 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003191 }
3192
3193 return 1;
3194}
3195
3196/* Just check the input and prepare the stack for the previous
3197 * function "hlua_channel_forward_yield"
3198 */
3199__LJMP static int hlua_channel_forward(lua_State *L)
3200{
3201 MAY_LJMP(check_args(L, 2, "forward"));
3202 MAY_LJMP(hlua_checkchannel(L, 1));
3203 MAY_LJMP(luaL_checkinteger(L, 2));
3204
3205 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003206 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003207}
3208
3209/* Just returns the number of bytes available in the input
3210 * side of the buffer. This function never fails.
3211 */
3212__LJMP static int hlua_channel_get_in_len(lua_State *L)
3213{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003214 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003215
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003216 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003217 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003218 if (IS_HTX_STRM(chn_strm(chn))) {
3219 struct htx *htx = htxbuf(&chn->buf);
3220 lua_pushinteger(L, htx->data - co_data(chn));
3221 }
3222 else
3223 lua_pushinteger(L, ci_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003224 return 1;
3225}
3226
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003227/* Returns true if the channel is full. */
3228__LJMP static int hlua_channel_is_full(lua_State *L)
3229{
3230 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003231
3232 MAY_LJMP(check_args(L, 1, "is_full"));
3233 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0136ebb2020-02-26 11:59:19 +01003234 /* ignore the reserve, we are not on a producer side (ie in an
3235 * applet).
3236 */
3237 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003238 return 1;
3239}
3240
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003241/* Just returns the number of bytes available in the output
3242 * side of the buffer. This function never fails.
3243 */
3244__LJMP static int hlua_channel_get_out_len(lua_State *L)
3245{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003246 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003247
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003248 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003249 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003250 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003251 return 1;
3252}
3253
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003254/*
3255 *
3256 *
3257 * Class Fetches
3258 *
3259 *
3260 */
3261
3262/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003263 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003264 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003265__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003266{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003267 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003268}
3269
3270/* This function creates and push in the stack a fetch object according
3271 * with a current TXN.
3272 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003273static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003274{
Willy Tarreau7073c472015-04-06 11:15:40 +02003275 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003276
3277 /* Check stack size. */
3278 if (!lua_checkstack(L, 3))
3279 return 0;
3280
3281 /* Create the object: obj[0] = userdata.
3282 * Note that the base of the Fetches object is the
3283 * transaction object.
3284 */
3285 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003286 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003287 lua_rawseti(L, -2, 0);
3288
Willy Tarreau7073c472015-04-06 11:15:40 +02003289 hsmp->s = txn->s;
3290 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003291 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003292 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003293
3294 /* Pop a class sesison metatable and affect it to the userdata. */
3295 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3296 lua_setmetatable(L, -2);
3297
3298 return 1;
3299}
3300
3301/* This function is an LUA binding. It is called with each sample-fetch.
3302 * It uses closure argument to store the associated sample-fetch. It
3303 * returns only one argument or throws an error. An error is thrown
3304 * only if an error is encountered during the argument parsing. If
3305 * the "sample-fetch" function fails, nil is returned.
3306 */
3307__LJMP static int hlua_run_sample_fetch(lua_State *L)
3308{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003309 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003310 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003311 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003312 int i;
3313 struct sample smp;
3314
3315 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003316 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003317
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003318 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003319 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003320
Thierry FOURNIERca988662015-12-20 18:43:03 +01003321 /* Check execution authorization. */
3322 if (f->use & SMP_USE_HTTP_ANY &&
3323 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3324 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3325 "is not available in Lua services", f->kw);
3326 WILL_LJMP(lua_error(L));
3327 }
3328
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003329 /* Get extra arguments. */
3330 for (i = 0; i < lua_gettop(L) - 1; i++) {
3331 if (i >= ARGM_NBARGS)
3332 break;
3333 hlua_lua2arg(L, i + 2, &args[i]);
3334 }
3335 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003336 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003337
3338 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003339 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003340
3341 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003342 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003343 lua_pushfstring(L, "error in arguments");
3344 WILL_LJMP(lua_error(L));
3345 }
3346
3347 /* Initialise the sample. */
3348 memset(&smp, 0, sizeof(smp));
3349
3350 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003351 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003352 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003353 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003354 lua_pushstring(L, "");
3355 else
3356 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003357 return 1;
3358 }
3359
3360 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003361 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003362 hlua_smp2lua_str(L, &smp);
3363 else
3364 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003365 return 1;
3366}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003367
3368/*
3369 *
3370 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003371 * Class Converters
3372 *
3373 *
3374 */
3375
3376/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003377 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003378 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003379__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003380{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003381 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003382}
3383
3384/* This function creates and push in the stack a Converters object
3385 * according with a current TXN.
3386 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003387static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003388{
Willy Tarreau7073c472015-04-06 11:15:40 +02003389 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003390
3391 /* Check stack size. */
3392 if (!lua_checkstack(L, 3))
3393 return 0;
3394
3395 /* Create the object: obj[0] = userdata.
3396 * Note that the base of the Converters object is the
3397 * same than the TXN object.
3398 */
3399 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003400 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003401 lua_rawseti(L, -2, 0);
3402
Willy Tarreau7073c472015-04-06 11:15:40 +02003403 hsmp->s = txn->s;
3404 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003405 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003406 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003407
Willy Tarreau87b09662015-04-03 00:22:06 +02003408 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003409 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3410 lua_setmetatable(L, -2);
3411
3412 return 1;
3413}
3414
3415/* This function is an LUA binding. It is called with each converter.
3416 * It uses closure argument to store the associated converter. It
3417 * returns only one argument or throws an error. An error is thrown
3418 * only if an error is encountered during the argument parsing. If
3419 * the converter function function fails, nil is returned.
3420 */
3421__LJMP static int hlua_run_sample_conv(lua_State *L)
3422{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003423 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003424 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003425 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003426 int i;
3427 struct sample smp;
3428
3429 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003430 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003431
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003432 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003433 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003434
3435 /* Get extra arguments. */
3436 for (i = 0; i < lua_gettop(L) - 2; i++) {
3437 if (i >= ARGM_NBARGS)
3438 break;
3439 hlua_lua2arg(L, i + 3, &args[i]);
3440 }
3441 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003442 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003443
3444 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003445 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003446
3447 /* Run the special args checker. */
3448 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3449 hlua_pusherror(L, "error in arguments");
3450 WILL_LJMP(lua_error(L));
3451 }
3452
3453 /* Initialise the sample. */
3454 if (!hlua_lua2smp(L, 2, &smp)) {
3455 hlua_pusherror(L, "error in the input argument");
3456 WILL_LJMP(lua_error(L));
3457 }
3458
Willy Tarreau1777ea62016-03-10 16:15:46 +01003459 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3460
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003461 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003462 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003463 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003464 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003465 WILL_LJMP(lua_error(L));
3466 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003467 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3468 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003469 hlua_pusherror(L, "error during the input argument casting");
3470 WILL_LJMP(lua_error(L));
3471 }
3472
3473 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003474 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003475 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003476 lua_pushstring(L, "");
3477 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003478 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003479 return 1;
3480 }
3481
3482 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003483 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003484 hlua_smp2lua_str(L, &smp);
3485 else
3486 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003487 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003488}
3489
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003490/*
3491 *
3492 *
3493 * Class AppletTCP
3494 *
3495 *
3496 */
3497
3498/* Returns a struct hlua_txn if the stack entry "ud" is
3499 * a class stream, otherwise it throws an error.
3500 */
3501__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3502{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003503 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003504}
3505
3506/* This function creates and push in the stack an Applet object
3507 * according with a current TXN.
3508 */
3509static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3510{
3511 struct hlua_appctx *appctx;
3512 struct stream_interface *si = ctx->owner;
3513 struct stream *s = si_strm(si);
3514 struct proxy *p = s->be;
3515
3516 /* Check stack size. */
3517 if (!lua_checkstack(L, 3))
3518 return 0;
3519
3520 /* Create the object: obj[0] = userdata.
3521 * Note that the base of the Converters object is the
3522 * same than the TXN object.
3523 */
3524 lua_newtable(L);
3525 appctx = lua_newuserdata(L, sizeof(*appctx));
3526 lua_rawseti(L, -2, 0);
3527 appctx->appctx = ctx;
3528 appctx->htxn.s = s;
3529 appctx->htxn.p = p;
3530
3531 /* Create the "f" field that contains a list of fetches. */
3532 lua_pushstring(L, "f");
3533 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3534 return 0;
3535 lua_settable(L, -3);
3536
3537 /* Create the "sf" field that contains a list of stringsafe fetches. */
3538 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003539 if (!hlua_fetches_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 /* Create the "c" field that contains a list of converters. */
3544 lua_pushstring(L, "c");
3545 if (!hlua_converters_new(L, &appctx->htxn, 0))
3546 return 0;
3547 lua_settable(L, -3);
3548
3549 /* Create the "sc" field that contains a list of stringsafe converters. */
3550 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003551 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003552 return 0;
3553 lua_settable(L, -3);
3554
3555 /* Pop a class stream metatable and affect it to the table. */
3556 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3557 lua_setmetatable(L, -2);
3558
3559 return 1;
3560}
3561
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003562__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3563{
3564 struct hlua_appctx *appctx;
3565 struct stream *s;
3566 const char *name;
3567 size_t len;
3568 struct sample smp;
3569
3570 MAY_LJMP(check_args(L, 3, "set_var"));
3571
3572 /* It is useles to retrieve the stream, but this function
3573 * runs only in a stream context.
3574 */
3575 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3576 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3577 s = appctx->htxn.s;
3578
3579 /* Converts the third argument in a sample. */
3580 hlua_lua2smp(L, 3, &smp);
3581
3582 /* Store the sample in a variable. */
3583 smp_set_owner(&smp, s->be, s->sess, s, 0);
3584 vars_set_by_name(name, len, &smp);
3585 return 0;
3586}
3587
3588__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3589{
3590 struct hlua_appctx *appctx;
3591 struct stream *s;
3592 const char *name;
3593 size_t len;
3594 struct sample smp;
3595
3596 MAY_LJMP(check_args(L, 2, "unset_var"));
3597
3598 /* It is useles to retrieve the stream, but this function
3599 * runs only in a stream context.
3600 */
3601 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3602 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3603 s = appctx->htxn.s;
3604
3605 /* Unset the variable. */
3606 smp_set_owner(&smp, s->be, s->sess, s, 0);
3607 vars_unset_by_name(name, len, &smp);
3608 return 0;
3609}
3610
3611__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3612{
3613 struct hlua_appctx *appctx;
3614 struct stream *s;
3615 const char *name;
3616 size_t len;
3617 struct sample smp;
3618
3619 MAY_LJMP(check_args(L, 2, "get_var"));
3620
3621 /* It is useles to retrieve the stream, but this function
3622 * runs only in a stream context.
3623 */
3624 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3625 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3626 s = appctx->htxn.s;
3627
3628 smp_set_owner(&smp, s->be, s->sess, s, 0);
3629 if (!vars_get_by_name(name, len, &smp)) {
3630 lua_pushnil(L);
3631 return 1;
3632 }
3633
3634 return hlua_smp2lua(L, &smp);
3635}
3636
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003637__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3638{
3639 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3640 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003641 struct hlua *hlua;
3642
3643 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003644 if (!s->hlua)
3645 return 0;
3646 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003647
3648 MAY_LJMP(check_args(L, 2, "set_priv"));
3649
3650 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003651 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003652
3653 /* Get and store new value. */
3654 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3655 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3656
3657 return 0;
3658}
3659
3660__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3661{
3662 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3663 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003664 struct hlua *hlua;
3665
3666 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003667 if (!s->hlua) {
3668 lua_pushnil(L);
3669 return 1;
3670 }
3671 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003672
3673 /* Push configuration index in the stack. */
3674 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3675
3676 return 1;
3677}
3678
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003679/* If expected data not yet available, it returns a yield. This function
3680 * consumes the data in the buffer. It returns a string containing the
3681 * data. This string can be empty.
3682 */
3683__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3684{
3685 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3686 struct stream_interface *si = appctx->appctx->owner;
3687 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003688 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003689 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003690 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003691 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003692
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003693 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003694 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003695
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003696 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003697 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003698 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003699 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003700 }
3701
3702 /* End of data: commit the total strings and return. */
3703 if (ret < 0) {
3704 luaL_pushresult(&appctx->b);
3705 return 1;
3706 }
3707
3708 /* Ensure that the block 2 length is usable. */
3709 if (ret == 1)
3710 len2 = 0;
3711
3712 /* dont check the max length read and dont check. */
3713 luaL_addlstring(&appctx->b, blk1, len1);
3714 luaL_addlstring(&appctx->b, blk2, len2);
3715
3716 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003717 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003718 luaL_pushresult(&appctx->b);
3719 return 1;
3720}
3721
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003722/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003723__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3724{
3725 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3726
3727 /* Initialise the string catenation. */
3728 luaL_buffinit(L, &appctx->b);
3729
3730 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3731}
3732
3733/* If expected data not yet available, it returns a yield. This function
3734 * consumes the data in the buffer. It returns a string containing the
3735 * data. This string can be empty.
3736 */
3737__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3738{
3739 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3740 struct stream_interface *si = appctx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003741 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003742 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003743 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003744 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003745 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003746 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003747
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003748 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003749 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003750
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003751 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003752 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003753 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003754 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003755 }
3756
3757 /* End of data: commit the total strings and return. */
3758 if (ret < 0) {
3759 luaL_pushresult(&appctx->b);
3760 return 1;
3761 }
3762
3763 /* Ensure that the block 2 length is usable. */
3764 if (ret == 1)
3765 len2 = 0;
3766
3767 if (len == -1) {
3768
3769 /* If len == -1, catenate all the data avalaile and
3770 * yield because we want to get all the data until
3771 * the end of data stream.
3772 */
3773 luaL_addlstring(&appctx->b, blk1, len1);
3774 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003775 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003776 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003777 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003778
3779 } else {
3780
3781 /* Copy the fisrt block caping to the length required. */
3782 if (len1 > len)
3783 len1 = len;
3784 luaL_addlstring(&appctx->b, blk1, len1);
3785 len -= len1;
3786
3787 /* Copy the second block. */
3788 if (len2 > len)
3789 len2 = len;
3790 luaL_addlstring(&appctx->b, blk2, len2);
3791 len -= len2;
3792
3793 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003794 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003795
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003796 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003797 if (len > 0) {
3798 lua_pushinteger(L, len);
3799 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003800 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003801 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003802 }
3803
3804 /* return the result. */
3805 luaL_pushresult(&appctx->b);
3806 return 1;
3807 }
3808
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003809 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003810 hlua_pusherror(L, "Lua: internal error");
3811 WILL_LJMP(lua_error(L));
3812 return 0;
3813}
3814
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003815/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003816__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3817{
3818 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3819 int len = -1;
3820
3821 if (lua_gettop(L) > 2)
3822 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3823 if (lua_gettop(L) >= 2) {
3824 len = MAY_LJMP(luaL_checkinteger(L, 2));
3825 lua_pop(L, 1);
3826 }
3827
3828 /* Confirm or set the required length */
3829 lua_pushinteger(L, len);
3830
3831 /* Initialise the string catenation. */
3832 luaL_buffinit(L, &appctx->b);
3833
3834 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3835}
3836
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003837/* Append data in the output side of the buffer. This data is immediately
3838 * sent. The function returns the amount of data written. If the buffer
3839 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003840 * if the channel is closed.
3841 */
3842__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3843{
3844 size_t len;
3845 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3846 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3847 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3848 struct stream_interface *si = appctx->appctx->owner;
3849 struct channel *chn = si_ic(si);
3850 int max;
3851
3852 /* Get the max amount of data which can write as input in the channel. */
3853 max = channel_recv_max(chn);
3854 if (max > (len - l))
3855 max = len - l;
3856
3857 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003858 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003859
3860 /* update counters. */
3861 l += max;
3862 lua_pop(L, 1);
3863 lua_pushinteger(L, l);
3864
3865 /* If some data is not send, declares the situation to the
3866 * applet, and returns a yield.
3867 */
3868 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01003869 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003870 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003871 }
3872
3873 return 1;
3874}
3875
3876/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3877 * yield the LUA process, and resume it without checking the
3878 * input arguments.
3879 */
3880__LJMP static int hlua_applet_tcp_send(lua_State *L)
3881{
3882 MAY_LJMP(check_args(L, 2, "send"));
3883 lua_pushinteger(L, 0);
3884
3885 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3886}
3887
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003888/*
3889 *
3890 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003891 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003892 *
3893 *
3894 */
3895
3896/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003897 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003898 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003899__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003900{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003901 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003902}
3903
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003904/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003905 * according with a current TXN.
3906 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003907static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003908{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003909 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003910 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003911 struct stream_interface *si = ctx->owner;
3912 struct stream *s = si_strm(si);
3913 struct proxy *px = s->be;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003914
3915 /* Check stack size. */
3916 if (!lua_checkstack(L, 3))
3917 return 0;
3918
3919 /* Create the object: obj[0] = userdata.
3920 * Note that the base of the Converters object is the
3921 * same than the TXN object.
3922 */
3923 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003924 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003925 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003926 appctx->appctx = ctx;
3927 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003928 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003929 appctx->htxn.s = s;
3930 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003931
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003932 /* Create the "f" field that contains a list of fetches. */
3933 lua_pushstring(L, "f");
3934 if (!hlua_fetches_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 "sf" field that contains a list of stringsafe fetches. */
3939 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003940 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003941 return 0;
3942 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003943
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003944 /* Create the "c" field that contains a list of converters. */
3945 lua_pushstring(L, "c");
3946 if (!hlua_converters_new(L, &appctx->htxn, 0))
3947 return 0;
3948 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003949
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003950 /* Create the "sc" field that contains a list of stringsafe converters. */
3951 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003952 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003953 return 0;
3954 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003955
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003956 if (IS_HTX_STRM(s)) {
3957 /* HTX version */
3958 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet29f17582019-05-23 11:03:26 +02003959 struct htx_blk *blk;
3960 struct htx_sl *sl;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003961 struct ist path;
3962 unsigned long long len = 0;
3963 int32_t pos;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003964
Christopher Faulet29f17582019-05-23 11:03:26 +02003965 blk = htx_get_first_blk(htx);
Christopher Faulet43a686d2019-11-18 15:50:25 +01003966 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Faulet29f17582019-05-23 11:03:26 +02003967 sl = htx_get_blk_ptr(htx, blk);
3968
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003969 /* Stores the request method. */
3970 lua_pushstring(L, "method");
3971 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
3972 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003973
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003974 /* Stores the http version. */
3975 lua_pushstring(L, "version");
3976 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
3977 lua_settable(L, -3);
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003978
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003979 /* creates an array of headers. hlua_http_get_headers() crates and push
3980 * the array on the top of the stack.
3981 */
3982 lua_pushstring(L, "headers");
3983 htxn.s = s;
3984 htxn.p = px;
3985 htxn.dir = SMP_OPT_DIR_REQ;
3986 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3987 return 0;
3988 lua_settable(L, -3);
3989
3990 path = http_get_path(htx_sl_req_uri(sl));
3991 if (path.ptr) {
3992 char *p, *q, *end;
3993
3994 p = path.ptr;
3995 end = path.ptr + path.len;
3996 q = p;
3997 while (q < end && *q != '?')
3998 q++;
3999
4000 /* Stores the request path. */
4001 lua_pushstring(L, "path");
4002 lua_pushlstring(L, p, q - p);
4003 lua_settable(L, -3);
4004
4005 /* Stores the query string. */
4006 lua_pushstring(L, "qs");
4007 if (*q == '?')
4008 q++;
4009 lua_pushlstring(L, q, end - q);
4010 lua_settable(L, -3);
4011 }
4012
Christopher Fauleta3f15502019-05-13 15:27:23 +02004013 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004014 struct htx_blk *blk = htx_get_blk(htx, pos);
4015 enum htx_blk_type type = htx_get_blk_type(blk);
4016
Christopher Faulet54b5e212019-06-04 10:08:28 +02004017 if (type == HTX_BLK_EOM || type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004018 break;
4019 if (type == HTX_BLK_DATA)
4020 len += htx_get_blksz(blk);
4021 }
4022 if (htx->extra != ULLONG_MAX)
4023 len += htx->extra;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004024
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004025 /* Stores the request path. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004026 lua_pushstring(L, "length");
4027 lua_pushinteger(L, len);
4028 lua_settable(L, -3);
4029 }
4030 else {
4031 /* Legacy HTTP version */
4032 struct http_txn *txn = s->txn;
4033 const char *path;
4034 const char *end;
4035 const char *p;
4036
4037 /* Stores the request method. */
4038 lua_pushstring(L, "method");
4039 lua_pushlstring(L, ci_head(txn->req.chn), txn->req.sl.rq.m_l);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004040 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004041
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004042 /* Stores the http version. */
4043 lua_pushstring(L, "version");
4044 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 +01004045 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004046
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004047 /* creates an array of headers. hlua_http_get_headers() crates and push
4048 * the array on the top of the stack.
4049 */
4050 lua_pushstring(L, "headers");
4051 htxn.s = s;
4052 htxn.p = px;
4053 htxn.dir = SMP_OPT_DIR_REQ;
4054 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
4055 return 0;
4056 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004057
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004058 /* Get path and qs */
4059 path = http_txn_get_path(txn);
4060 if (path) {
4061 end = ci_head(txn->req.chn) + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
4062 p = path;
4063 while (p < end && *p != '?')
4064 p++;
4065
4066 /* Stores the request path. */
4067 lua_pushstring(L, "path");
4068 lua_pushlstring(L, path, p - path);
4069 lua_settable(L, -3);
4070
4071 /* Stores the query string. */
4072 lua_pushstring(L, "qs");
4073 if (*p == '?')
4074 p++;
4075 lua_pushlstring(L, p, end - p);
4076 lua_settable(L, -3);
4077 }
4078
4079 /* Stores the request path. */
4080 lua_pushstring(L, "length");
4081 lua_pushinteger(L, txn->req.body_len);
4082 lua_settable(L, -3);
4083 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004084
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004085 /* Create an empty array of HTTP request headers. */
4086 lua_pushstring(L, "response");
4087 lua_newtable(L);
4088 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004089
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004090 /* Pop a class stream metatable and affect it to the table. */
4091 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4092 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004093
4094 return 1;
4095}
4096
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004097__LJMP static int hlua_applet_http_set_var(lua_State *L)
4098{
4099 struct hlua_appctx *appctx;
4100 struct stream *s;
4101 const char *name;
4102 size_t len;
4103 struct sample smp;
4104
4105 MAY_LJMP(check_args(L, 3, "set_var"));
4106
4107 /* It is useles to retrieve the stream, but this function
4108 * runs only in a stream context.
4109 */
4110 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4111 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4112 s = appctx->htxn.s;
4113
4114 /* Converts the third argument in a sample. */
4115 hlua_lua2smp(L, 3, &smp);
4116
4117 /* Store the sample in a variable. */
4118 smp_set_owner(&smp, s->be, s->sess, s, 0);
4119 vars_set_by_name(name, len, &smp);
4120 return 0;
4121}
4122
4123__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4124{
4125 struct hlua_appctx *appctx;
4126 struct stream *s;
4127 const char *name;
4128 size_t len;
4129 struct sample smp;
4130
4131 MAY_LJMP(check_args(L, 2, "unset_var"));
4132
4133 /* It is useles to retrieve the stream, but this function
4134 * runs only in a stream context.
4135 */
4136 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4137 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4138 s = appctx->htxn.s;
4139
4140 /* Unset the variable. */
4141 smp_set_owner(&smp, s->be, s->sess, s, 0);
4142 vars_unset_by_name(name, len, &smp);
4143 return 0;
4144}
4145
4146__LJMP static int hlua_applet_http_get_var(lua_State *L)
4147{
4148 struct hlua_appctx *appctx;
4149 struct stream *s;
4150 const char *name;
4151 size_t len;
4152 struct sample smp;
4153
4154 MAY_LJMP(check_args(L, 2, "get_var"));
4155
4156 /* It is useles to retrieve the stream, but this function
4157 * runs only in a stream context.
4158 */
4159 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4160 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4161 s = appctx->htxn.s;
4162
4163 smp_set_owner(&smp, s->be, s->sess, s, 0);
4164 if (!vars_get_by_name(name, len, &smp)) {
4165 lua_pushnil(L);
4166 return 1;
4167 }
4168
4169 return hlua_smp2lua(L, &smp);
4170}
4171
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004172__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4173{
4174 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4175 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004176 struct hlua *hlua;
4177
4178 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004179 if (!s->hlua)
4180 return 0;
4181 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004182
4183 MAY_LJMP(check_args(L, 2, "set_priv"));
4184
4185 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004186 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004187
4188 /* Get and store new value. */
4189 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4190 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4191
4192 return 0;
4193}
4194
4195__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4196{
4197 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4198 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004199 struct hlua *hlua;
4200
4201 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004202 if (!s->hlua) {
4203 lua_pushnil(L);
4204 return 1;
4205 }
4206 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004207
4208 /* Push configuration index in the stack. */
4209 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4210
4211 return 1;
4212}
4213
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004214/* If expected data not yet available, it returns a yield. This function
4215 * consumes the data in the buffer. It returns a string containing the
4216 * data. This string can be empty.
4217 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004218__LJMP static int hlua_applet_htx_getline_yield(lua_State *L, int status, lua_KContext ctx)
4219{
4220 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4221 struct stream_interface *si = appctx->appctx->owner;
4222 struct channel *req = si_oc(si);
4223 struct htx *htx;
4224 struct htx_blk *blk;
4225 size_t count;
4226 int stop = 0;
4227
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004228 htx = htx_from_buf(&req->buf);
4229 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004230 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004231
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004232 while (count && !stop && blk) {
4233 enum htx_blk_type type = htx_get_blk_type(blk);
4234 uint32_t sz = htx_get_blksz(blk);
4235 struct ist v;
4236 uint32_t vlen;
4237 char *nl;
4238
Christopher Faulete461e342018-12-18 16:43:35 +01004239 if (type == HTX_BLK_EOM) {
4240 stop = 1;
4241 break;
4242 }
4243
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004244 vlen = sz;
4245 if (vlen > count) {
4246 if (type != HTX_BLK_DATA)
4247 break;
4248 vlen = count;
4249 }
4250
4251 switch (type) {
4252 case HTX_BLK_UNUSED:
4253 break;
4254
4255 case HTX_BLK_DATA:
4256 v = htx_get_blk_value(htx, blk);
4257 v.len = vlen;
4258 nl = istchr(v, '\n');
4259 if (nl != NULL) {
4260 stop = 1;
4261 vlen = nl - v.ptr + 1;
4262 }
4263 luaL_addlstring(&appctx->b, v.ptr, vlen);
4264 break;
4265
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004266 case HTX_BLK_TLR:
4267 case HTX_BLK_EOM:
4268 stop = 1;
4269 break;
4270
4271 default:
4272 break;
4273 }
4274
4275 co_set_data(req, co_data(req) - vlen);
4276 count -= vlen;
4277 if (sz == vlen)
4278 blk = htx_remove_blk(htx, blk);
4279 else {
4280 htx_cut_data_blk(htx, blk, vlen);
4281 break;
4282 }
4283 }
4284
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004285 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004286 if (!stop) {
4287 si_cant_get(si);
4288 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_getline_yield, TICK_ETERNITY, 0));
4289 }
4290
4291 /* return the result. */
4292 luaL_pushresult(&appctx->b);
4293 return 1;
4294}
4295
4296
4297/* If expected data not yet available, it returns a yield. This function
4298 * consumes the data in the buffer. It returns a string containing the
4299 * data. This string can be empty.
4300 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004301__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004302{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004303 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4304 struct stream_interface *si = appctx->appctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004305 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004306 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004307 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004308 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004309 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004310
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004311 /* Check for the end of the data. */
4312 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4313 luaL_pushresult(&appctx->b);
4314 return 1;
4315 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004316
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004317 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004318 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004319
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004320 /* Data not yet available. return yield. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004321 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004322 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004323 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004324 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004325
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004326 /* End of data: commit the total strings and return. */
4327 if (ret < 0) {
4328 luaL_pushresult(&appctx->b);
4329 return 1;
4330 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004331
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004332 /* Ensure that the block 2 length is usable. */
4333 if (ret == 1)
4334 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004335
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004336 /* Copy the fisrt block caping to the length required. */
4337 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4338 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4339 luaL_addlstring(&appctx->b, blk1, len1);
4340 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004341
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004342 /* Copy the second block. */
4343 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4344 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4345 luaL_addlstring(&appctx->b, blk2, len2);
4346 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004347
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004348 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004349 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004350 luaL_pushresult(&appctx->b);
4351 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004352}
4353
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004354/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004355__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004356{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004357 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004358
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004359 /* Initialise the string catenation. */
4360 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004361
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004362 if (IS_HTX_STRM(si_strm(appctx->appctx->owner)))
4363 return MAY_LJMP(hlua_applet_htx_getline_yield(L, 0, 0));
4364 else
4365 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004366}
4367
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004368/* If expected data not yet available, it returns a yield. This function
4369 * consumes the data in the buffer. It returns a string containing the
4370 * data. This string can be empty.
4371 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004372__LJMP static int hlua_applet_htx_recv_yield(lua_State *L, int status, lua_KContext ctx)
4373{
4374 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4375 struct stream_interface *si = appctx->appctx->owner;
4376 struct channel *req = si_oc(si);
4377 struct htx *htx;
4378 struct htx_blk *blk;
4379 size_t count;
4380 int len;
4381
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004382 htx = htx_from_buf(&req->buf);
4383 len = MAY_LJMP(luaL_checkinteger(L, 2));
4384 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02004385 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004386 while (count && len && blk) {
4387 enum htx_blk_type type = htx_get_blk_type(blk);
4388 uint32_t sz = htx_get_blksz(blk);
4389 struct ist v;
4390 uint32_t vlen;
4391
Christopher Faulete461e342018-12-18 16:43:35 +01004392 if (type == HTX_BLK_EOM) {
4393 len = 0;
4394 break;
4395 }
4396
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004397 vlen = sz;
4398 if (len > 0 && vlen > len)
4399 vlen = len;
4400 if (vlen > count) {
4401 if (type != HTX_BLK_DATA)
4402 break;
4403 vlen = count;
4404 }
4405
4406 switch (type) {
4407 case HTX_BLK_UNUSED:
4408 break;
4409
4410 case HTX_BLK_DATA:
4411 v = htx_get_blk_value(htx, blk);
4412 luaL_addlstring(&appctx->b, v.ptr, vlen);
4413 break;
4414
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004415 case HTX_BLK_TLR:
4416 case HTX_BLK_EOM:
4417 len = 0;
4418 break;
4419
4420 default:
4421 break;
4422 }
4423
4424 co_set_data(req, co_data(req) - vlen);
4425 count -= vlen;
4426 if (len > 0)
4427 len -= vlen;
4428 if (sz == vlen)
4429 blk = htx_remove_blk(htx, blk);
4430 else {
4431 htx_cut_data_blk(htx, blk, vlen);
4432 break;
4433 }
4434 }
4435
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004436 htx_to_buf(htx, &req->buf);
4437
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004438 /* If we are no other data available, yield waiting for new data. */
4439 if (len) {
4440 if (len > 0) {
4441 lua_pushinteger(L, len);
4442 lua_replace(L, 2);
4443 }
4444 si_cant_get(si);
4445 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_recv_yield, TICK_ETERNITY, 0));
4446 }
4447
4448 /* return the result. */
4449 luaL_pushresult(&appctx->b);
4450 return 1;
4451}
4452
4453/* If expected data not yet available, it returns a yield. This function
4454 * consumes the data in the buffer. It returns a string containing the
4455 * data. This string can be empty.
4456 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004457__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004458{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004459 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4460 struct stream_interface *si = appctx->appctx->owner;
4461 int len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004462 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004463 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004464 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004465 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004466 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004467
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004468 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004469 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004470
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004471 /* Data not yet available. return yield. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004472 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004473 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004474 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004475 }
4476
4477 /* End of data: commit the total strings and return. */
4478 if (ret < 0) {
4479 luaL_pushresult(&appctx->b);
4480 return 1;
4481 }
4482
4483 /* Ensure that the block 2 length is usable. */
4484 if (ret == 1)
4485 len2 = 0;
4486
4487 /* Copy the fisrt block caping to the length required. */
4488 if (len1 > len)
4489 len1 = len;
4490 luaL_addlstring(&appctx->b, blk1, len1);
4491 len -= len1;
4492
4493 /* Copy the second block. */
4494 if (len2 > len)
4495 len2 = len;
4496 luaL_addlstring(&appctx->b, blk2, len2);
4497 len -= len2;
4498
4499 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004500 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004501 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4502 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4503
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004504 /* If we are no other data available, yield waiting for new data. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004505 if (len > 0) {
4506 lua_pushinteger(L, len);
4507 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004508 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004509 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004510 }
4511
4512 /* return the result. */
4513 luaL_pushresult(&appctx->b);
4514 return 1;
4515}
4516
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004517/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004518__LJMP static int hlua_applet_http_recv(lua_State *L)
4519{
4520 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4521 int len = -1;
4522
4523 /* Check arguments. */
4524 if (lua_gettop(L) > 2)
4525 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4526 if (lua_gettop(L) >= 2) {
4527 len = MAY_LJMP(luaL_checkinteger(L, 2));
4528 lua_pop(L, 1);
4529 }
4530
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004531 if (IS_HTX_STRM(si_strm(appctx->appctx->owner))) {
4532 /* HTX version */
4533 lua_pushinteger(L, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004534
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004535 /* Initialise the string catenation. */
4536 luaL_buffinit(L, &appctx->b);
4537
4538 return MAY_LJMP(hlua_applet_htx_recv_yield(L, 0, 0));
4539 }
4540 else {
4541 /* Legacy HTTP version */
4542 /* Check the required length */
4543 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4544 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4545 lua_pushinteger(L, len);
4546
4547 /* Initialise the string catenation. */
4548 luaL_buffinit(L, &appctx->b);
4549
4550 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4551 }
4552}
4553
4554/* Append data in the output side of the buffer. This data is immediately
4555 * sent. The function returns the amount of data written. If the buffer
4556 * cannot contain the data, the function yields. The function returns -1
4557 * if the channel is closed.
4558 */
4559__LJMP static int hlua_applet_htx_send_yield(lua_State *L, int status, lua_KContext ctx)
4560{
4561 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4562 struct stream_interface *si = appctx->appctx->owner;
4563 struct channel *res = si_ic(si);
4564 struct htx *htx = htx_from_buf(&res->buf);
4565 const char *data;
4566 size_t len;
4567 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4568 int max;
4569
Christopher Faulet4e963012019-07-03 11:39:30 +02004570 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004571 if (!max)
4572 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004573
4574 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
4575
4576 /* Get the max amount of data which can write as input in the channel. */
4577 if (max > (len - l))
4578 max = len - l;
4579
4580 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02004581 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004582 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004583
4584 /* update counters. */
4585 l += max;
4586 lua_pop(L, 1);
4587 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004588
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004589 /* If some data is not send, declares the situation to the
4590 * applet, and returns a yield.
4591 */
4592 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004593 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004594 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004595 si_rx_room_blk(si);
4596 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_send_yield, TICK_ETERNITY, 0));
4597 }
4598
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004599 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004600 return 1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004601}
4602
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004603/* Append data in the output side of the buffer. This data is immediately
4604 * sent. The function returns the amount of data written. If the buffer
4605 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004606 * if the channel is closed.
4607 */
4608__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4609{
4610 size_t len;
4611 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4612 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4613 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4614 struct stream_interface *si = appctx->appctx->owner;
4615 struct channel *chn = si_ic(si);
4616 int max;
4617
4618 /* Get the max amount of data which can write as input in the channel. */
4619 max = channel_recv_max(chn);
4620 if (max > (len - l))
4621 max = len - l;
4622
4623 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004624 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004625
4626 /* update counters. */
4627 l += max;
4628 lua_pop(L, 1);
4629 lua_pushinteger(L, l);
4630
4631 /* If some data is not send, declares the situation to the
4632 * applet, and returns a yield.
4633 */
4634 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004635 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004636 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004637 }
4638
4639 return 1;
4640}
4641
4642/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4643 * yield the LUA process, and resume it without checking the
4644 * input arguments.
4645 */
4646__LJMP static int hlua_applet_http_send(lua_State *L)
4647{
4648 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004649
4650 /* We want to send some data. Headers must be sent. */
4651 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4652 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4653 WILL_LJMP(lua_error(L));
4654 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004655
4656 if (IS_HTX_STRM(si_strm(appctx->appctx->owner))) {
4657 /* HTX version */
4658 /* This interger is used for followinf the amount of data sent. */
4659 lua_pushinteger(L, 0);
4660
4661 return MAY_LJMP(hlua_applet_htx_send_yield(L, 0, 0));
4662 }
4663 else {
4664 /* Legacy HTTP version */
4665 size_t len;
4666 char hex[10];
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004667
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004668 MAY_LJMP(luaL_checklstring(L, 2, &len));
4669
4670 /* If transfer encoding chunked is selected, we surround the data
4671 * by chunk data.
4672 */
4673 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4674 snprintf(hex, 9, "%x", (unsigned int)len);
4675 lua_pushfstring(L, "%s\r\n", hex);
4676 lua_insert(L, 2); /* swap the last 2 entries. */
4677 lua_pushstring(L, "\r\n");
4678 lua_concat(L, 3);
4679 }
4680
4681 /* This interger is used for followinf the amount of data sent. */
4682 lua_pushinteger(L, 0);
4683
4684 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4685 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004686}
4687
4688__LJMP static int hlua_applet_http_addheader(lua_State *L)
4689{
4690 const char *name;
4691 int ret;
4692
4693 MAY_LJMP(hlua_checkapplet_http(L, 1));
4694 name = MAY_LJMP(luaL_checkstring(L, 2));
4695 MAY_LJMP(luaL_checkstring(L, 3));
4696
4697 /* Push in the stack the "response" entry. */
4698 ret = lua_getfield(L, 1, "response");
4699 if (ret != LUA_TTABLE) {
4700 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4701 "is expected as an array. %s found", lua_typename(L, ret));
4702 WILL_LJMP(lua_error(L));
4703 }
4704
4705 /* check if the header is already registered if it is not
4706 * the case, register it.
4707 */
4708 ret = lua_getfield(L, -1, name);
4709 if (ret == LUA_TNIL) {
4710
4711 /* Entry not found. */
4712 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4713
4714 /* Insert the new header name in the array in the top of the stack.
4715 * It left the new array in the top of the stack.
4716 */
4717 lua_newtable(L);
4718 lua_pushvalue(L, 2);
4719 lua_pushvalue(L, -2);
4720 lua_settable(L, -4);
4721
4722 } else if (ret != LUA_TTABLE) {
4723
4724 /* corruption error. */
4725 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4726 "is expected as an array. %s found", name, lua_typename(L, ret));
4727 WILL_LJMP(lua_error(L));
4728 }
4729
4730 /* Now the top od thestack is an array of values. We push
4731 * the header value as new entry.
4732 */
4733 lua_pushvalue(L, 3);
4734 ret = lua_rawlen(L, -2);
4735 lua_rawseti(L, -2, ret + 1);
4736 lua_pushboolean(L, 1);
4737 return 1;
4738}
4739
4740__LJMP static int hlua_applet_http_status(lua_State *L)
4741{
4742 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4743 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004744 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004745
4746 if (status < 100 || status > 599) {
4747 lua_pushboolean(L, 0);
4748 return 1;
4749 }
4750
4751 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004752 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004753 lua_pushboolean(L, 1);
4754 return 1;
4755}
4756
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004757
4758__LJMP static int hlua_applet_htx_send_response(lua_State *L)
4759{
4760 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4761 struct stream_interface *si = appctx->appctx->owner;
4762 struct channel *res = si_ic(si);
4763 struct htx *htx;
4764 struct htx_sl *sl;
4765 struct h1m h1m;
4766 const char *status, *reason;
4767 const char *name, *value;
4768 size_t nlen, vlen;
4769 unsigned int flags;
4770
4771 /* Send the message at once. */
4772 htx = htx_from_buf(&res->buf);
4773 h1m_init_res(&h1m);
4774
4775 /* Use the same http version than the request. */
4776 status = ultoa_r(appctx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
4777 reason = appctx->appctx->ctx.hlua_apphttp.reason;
4778 if (reason == NULL)
4779 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
4780 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
4781 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
4782 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
4783 }
4784 else {
4785 flags = HTX_SL_F_IS_RESP;
4786 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
4787 }
4788 if (!sl) {
4789 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
4790 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4791 WILL_LJMP(lua_error(L));
4792 }
4793 sl->info.res.status = appctx->appctx->ctx.hlua_apphttp.status;
4794
4795 /* Get the array associated to the field "response" in the object AppletHTTP. */
4796 lua_pushvalue(L, 0);
4797 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4798 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4799 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4800 WILL_LJMP(lua_error(L));
4801 }
4802
4803 /* Browse the list of headers. */
4804 lua_pushnil(L);
4805 while(lua_next(L, -2) != 0) {
4806 /* We expect a string as -2. */
4807 if (lua_type(L, -2) != LUA_TSTRING) {
4808 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4809 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4810 lua_typename(L, lua_type(L, -2)));
4811 WILL_LJMP(lua_error(L));
4812 }
4813 name = lua_tolstring(L, -2, &nlen);
4814
4815 /* We expect an array as -1. */
4816 if (lua_type(L, -1) != LUA_TTABLE) {
4817 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4818 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4819 name,
4820 lua_typename(L, lua_type(L, -1)));
4821 WILL_LJMP(lua_error(L));
4822 }
4823
4824 /* Browse the table who is on the top of the stack. */
4825 lua_pushnil(L);
4826 while(lua_next(L, -2) != 0) {
4827 int id;
4828
4829 /* We expect a number as -2. */
4830 if (lua_type(L, -2) != LUA_TNUMBER) {
4831 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4832 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4833 name,
4834 lua_typename(L, lua_type(L, -2)));
4835 WILL_LJMP(lua_error(L));
4836 }
4837 id = lua_tointeger(L, -2);
4838
4839 /* We expect a string as -2. */
4840 if (lua_type(L, -1) != LUA_TSTRING) {
4841 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4842 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4843 name, id,
4844 lua_typename(L, lua_type(L, -1)));
4845 WILL_LJMP(lua_error(L));
4846 }
4847 value = lua_tolstring(L, -1, &vlen);
4848
4849 /* Simple Protocol checks. */
4850 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
4851 h1_parse_xfer_enc_header(&h1m, ist2(name, nlen));
4852 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
4853 struct ist v = ist2(value, vlen);
4854 int ret;
4855
4856 ret = h1_parse_cont_len_header(&h1m, &v);
4857 if (ret < 0) {
4858 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
4859 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4860 name);
4861 WILL_LJMP(lua_error(L));
4862 }
4863 else if (ret == 0)
4864 goto next; /* Skip it */
4865 }
4866
4867 /* Add a new header */
4868 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
4869 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
4870 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4871 name);
4872 WILL_LJMP(lua_error(L));
4873 }
4874 next:
4875 /* Remove the array from the stack, and get next element with a remaining string. */
4876 lua_pop(L, 1);
4877 }
4878
4879 /* Remove the array from the stack, and get next element with a remaining string. */
4880 lua_pop(L, 1);
4881 }
4882
4883 if (h1m.flags & H1_MF_CHNK)
4884 h1m.flags &= ~H1_MF_CLEN;
4885 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
4886 h1m.flags |= H1_MF_XFER_LEN;
4887
4888 /* Uset HTX start-line flags */
4889 if (h1m.flags & H1_MF_XFER_ENC)
4890 flags |= HTX_SL_F_XFER_ENC;
4891 if (h1m.flags & H1_MF_XFER_LEN) {
4892 flags |= HTX_SL_F_XFER_LEN;
4893 if (h1m.flags & H1_MF_CHNK)
4894 flags |= HTX_SL_F_CHNK;
4895 else if (h1m.flags & H1_MF_CLEN)
4896 flags |= HTX_SL_F_CLEN;
4897 if (h1m.body_len == 0)
4898 flags |= HTX_SL_F_BODYLESS;
4899 }
4900 sl->flags |= flags;
4901
4902 /* If we dont have a content-length set, and the HTTP version is 1.1
4903 * and the status code implies the presence of a message body, we must
4904 * announce a transfer encoding chunked. This is required by haproxy
4905 * for the keepalive compliance. If the applet annouces a transfer-encoding
4906 * chunked itslef, don't do anything.
4907 */
4908 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
4909 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4910 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4911 appctx->appctx->ctx.hlua_apphttp.status != 304) {
4912 /* Add a new header */
4913 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
4914 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
4915 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
4916 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4917 WILL_LJMP(lua_error(L));
4918 }
4919 }
4920
4921 /* Finalize headers. */
4922 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
4923 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
4924 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4925 WILL_LJMP(lua_error(L));
4926 }
4927
4928 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
4929 b_reset(&res->buf);
4930 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4931 WILL_LJMP(lua_error(L));
4932 }
4933
4934 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004935 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004936
4937 /* Headers sent, set the flag. */
4938 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4939 return 0;
4940
4941}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004942/* We will build the status line and the headers of the HTTP response.
4943 * We will try send at once if its not possible, we give back the hand
4944 * waiting for more room.
4945 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004946__LJMP static int hlua_applet_htx_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4947{
4948 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4949 struct stream_interface *si = appctx->appctx->owner;
4950 struct channel *res = si_ic(si);
4951
4952 if (co_data(res)) {
4953 si_rx_room_blk(si);
4954 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_start_response_yield, TICK_ETERNITY, 0));
4955 }
4956 return MAY_LJMP(hlua_applet_htx_send_response(L));
4957}
4958
4959
4960__LJMP static int hlua_applet_htx_start_response(lua_State *L)
4961{
4962 return MAY_LJMP(hlua_applet_htx_start_response_yield(L, 0, 0));
4963}
4964
4965/* We will build the status line and the headers of the HTTP response.
4966 * We will try send at once if its not possible, we give back the hand
4967 * waiting for more room.
4968 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004969__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4970{
4971 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4972 struct stream_interface *si = appctx->appctx->owner;
4973 struct channel *chn = si_ic(si);
4974 int ret;
4975 size_t len;
4976 const char *msg;
4977
4978 /* Get the message as the first argument on the stack. */
4979 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4980
4981 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004982 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004983
4984 /* if ret == -2 or -3 the channel closed or the message si too
4985 * big for the buffers.
4986 */
4987 if (ret == -2 || ret == -3) {
4988 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4989 WILL_LJMP(lua_error(L));
4990 }
4991
4992 /* If ret is -1, we dont have room in the buffer, so we yield. */
4993 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004994 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004995 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004996 }
4997
4998 /* Headers sent, set the flag. */
4999 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
5000 return 0;
5001}
5002
5003__LJMP static int hlua_applet_http_start_response(lua_State *L)
5004{
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005005 struct buffer *tmp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005006 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005007 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02005008 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005009 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02005010 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005011 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005012 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005013 int hdr_chunked = 0;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005014 const char *reason;
5015
5016 if (IS_HTX_STRM(si_strm(appctx->appctx->owner)))
5017 return MAY_LJMP(hlua_applet_htx_start_response(L));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005018
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005019 reason = appctx->appctx->ctx.hlua_apphttp.reason;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005020 if (reason == NULL)
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02005021 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005022
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005023 tmp = get_trash_chunk();
5024
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005025 /* Use the same http version than the request. */
5026 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01005027 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005028 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005029 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005030
5031 /* Get the array associated to the field "response" in the object AppletHTTP. */
5032 lua_pushvalue(L, 0);
5033 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5034 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
5035 appctx->appctx->rule->arg.hlua_rule->fcn.name);
5036 WILL_LJMP(lua_error(L));
5037 }
5038
5039 /* Browse the list of headers. */
5040 lua_pushnil(L);
5041 while(lua_next(L, -2) != 0) {
5042
5043 /* We expect a string as -2. */
5044 if (lua_type(L, -2) != LUA_TSTRING) {
5045 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
5046 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5047 lua_typename(L, lua_type(L, -2)));
5048 WILL_LJMP(lua_error(L));
5049 }
Willy Tarreaua3294632017-08-23 11:24:47 +02005050 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005051
5052 /* We expect an array as -1. */
5053 if (lua_type(L, -1) != LUA_TTABLE) {
5054 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
5055 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5056 name,
5057 lua_typename(L, lua_type(L, -1)));
5058 WILL_LJMP(lua_error(L));
5059 }
5060
5061 /* Browse the table who is on the top of the stack. */
5062 lua_pushnil(L);
5063 while(lua_next(L, -2) != 0) {
5064
5065 /* We expect a number as -2. */
5066 if (lua_type(L, -2) != LUA_TNUMBER) {
5067 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
5068 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5069 name,
5070 lua_typename(L, lua_type(L, -2)));
5071 WILL_LJMP(lua_error(L));
5072 }
5073 id = lua_tointeger(L, -2);
5074
5075 /* We expect a string as -2. */
5076 if (lua_type(L, -1) != LUA_TSTRING) {
5077 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
5078 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5079 name, id,
5080 lua_typename(L, lua_type(L, -1)));
5081 WILL_LJMP(lua_error(L));
5082 }
Willy Tarreaua3294632017-08-23 11:24:47 +02005083 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005084
5085 /* Catenate a new header. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005086 if (tmp->data + name_len + 2 + value_len + 2 < tmp->size) {
5087 memcpy(tmp->area + tmp->data, name, name_len);
5088 tmp->data += name_len;
5089 tmp->area[tmp->data++] = ':';
5090 tmp->area[tmp->data++] = ' ';
Willy Tarreaua3294632017-08-23 11:24:47 +02005091
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005092 memcpy(tmp->area + tmp->data, value,
5093 value_len);
5094 tmp->data += value_len;
5095 tmp->area[tmp->data++] = '\r';
5096 tmp->area[tmp->data++] = '\n';
Willy Tarreaua3294632017-08-23 11:24:47 +02005097 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005098
5099 /* Protocol checks. */
5100
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005101 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005102 * is done without control. If it contains a bad value,
5103 * the content-length remains negative so that we can
5104 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005105 */
Willy Tarreaua3294632017-08-23 11:24:47 +02005106 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005107 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005108
5109 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02005110 if (name_len == 17 && value_len == 7 &&
5111 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005112 strcasecmp("chunked", value) == 0)
5113 hdr_chunked = 1;
5114
5115 /* Remove the array from the stack, and get next element with a remaining string. */
5116 lua_pop(L, 1);
5117 }
5118
5119 /* Remove the array from the stack, and get next element with a remaining string. */
5120 lua_pop(L, 1);
5121 }
5122
Willy Tarreau06c75fe2017-08-23 09:10:38 +02005123 /* If we dont have a content-length set, and the HTTP version is 1.1
5124 * and the status code implies the presence of a message body, we must
5125 * announce a transfer encoding chunked. This is required by haproxy
5126 * for the keepalive compliance. If the applet annouces a transfer-encoding
5127 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005128 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005129 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02005130 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
5131 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
5132 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
5133 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005134 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
5135 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
5136 }
5137
5138 /* Finalize headers. */
5139 chunk_appendf(tmp, "\r\n");
5140
5141 /* Remove the last entry and the array of headers */
5142 lua_pop(L, 2);
5143
5144 /* Push the headers block. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005145 lua_pushlstring(L, tmp->area, tmp->data);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005146
5147 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
5148}
5149
5150/*
5151 *
5152 *
5153 * Class HTTP
5154 *
5155 *
5156 */
5157
5158/* Returns a struct hlua_txn if the stack entry "ud" is
5159 * a class stream, otherwise it throws an error.
5160 */
5161__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
5162{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005163 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005164}
5165
5166/* This function creates and push in the stack a HTTP object
5167 * according with a current TXN.
5168 */
5169static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5170{
5171 struct hlua_txn *htxn;
5172
5173 /* Check stack size. */
5174 if (!lua_checkstack(L, 3))
5175 return 0;
5176
5177 /* Create the object: obj[0] = userdata.
5178 * Note that the base of the Converters object is the
5179 * same than the TXN object.
5180 */
5181 lua_newtable(L);
5182 htxn = lua_newuserdata(L, sizeof(*htxn));
5183 lua_rawseti(L, -2, 0);
5184
5185 htxn->s = txn->s;
5186 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005187 htxn->dir = txn->dir;
5188 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005189
5190 /* Pop a class stream metatable and affect it to the table. */
5191 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5192 lua_setmetatable(L, -2);
5193
5194 return 1;
5195}
5196
5197/* This function creates ans returns an array of HTTP headers.
5198 * This function does not fails. It is used as wrapper with the
5199 * 2 following functions.
5200 */
5201__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5202{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005203 /* Create the table. */
5204 lua_newtable(L);
5205
5206 if (!htxn->s->txn)
5207 return 1;
5208
Christopher Faulet724a12c2018-12-13 22:12:15 +01005209 if (IS_HTX_STRM(htxn->s)) {
5210 /* HTX version */
5211 struct htx *htx = htxbuf(&msg->chn->buf);
5212 int32_t pos;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005213
Christopher Fauleta3f15502019-05-13 15:27:23 +02005214 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet724a12c2018-12-13 22:12:15 +01005215 struct htx_blk *blk = htx_get_blk(htx, pos);
5216 enum htx_blk_type type = htx_get_blk_type(blk);
5217 struct ist n, v;
5218 int len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005219
Christopher Faulet724a12c2018-12-13 22:12:15 +01005220 if (type == HTX_BLK_HDR) {
5221 n = htx_get_blk_name(htx,blk);
5222 v = htx_get_blk_value(htx, blk);
5223 }
5224 else if (type == HTX_BLK_EOH)
5225 break;
5226 else
5227 continue;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005228
Christopher Faulet724a12c2018-12-13 22:12:15 +01005229 /* Check for existing entry:
5230 * assume that the table is on the top of the stack, and
5231 * push the key in the stack, the function lua_gettable()
5232 * perform the lookup.
5233 */
5234 lua_pushlstring(L, n.ptr, n.len);
5235 lua_gettable(L, -2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005236
Christopher Faulet724a12c2018-12-13 22:12:15 +01005237 switch (lua_type(L, -1)) {
5238 case LUA_TNIL:
5239 /* Table not found, create it. */
5240 lua_pop(L, 1); /* remove the nil value. */
5241 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5242 lua_newtable(L); /* create and push empty table. */
5243 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5244 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5245 lua_rawset(L, -3); /* index new table with header name (pop the values). */
5246 break;
5247
5248 case LUA_TTABLE:
5249 /* Entry found: push the value in the table. */
5250 len = lua_rawlen(L, -1);
5251 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5252 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5253 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5254 break;
5255
5256 default:
5257 /* Other cases are errors. */
5258 hlua_pusherror(L, "internal error during the parsing of headers.");
5259 WILL_LJMP(lua_error(L));
5260 }
5261 }
5262 }
5263 else {
5264 /* Legacy HTTP version */
5265 const char *cur_ptr, *cur_next, *p;
5266 int old_idx, cur_idx;
5267 struct hdr_idx_elem *cur_hdr;
5268 const char *hn, *hv;
5269 int hnl, hvl;
5270 const char *in;
5271 char *out;
5272 int len;
5273
5274 /* Build array of headers. */
5275 old_idx = 0;
5276 cur_next = ci_head(msg->chn) + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
5277
5278 while (1) {
5279 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
5280 if (!cur_idx)
5281 break;
5282 old_idx = cur_idx;
5283
5284 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
5285 cur_ptr = cur_next;
5286 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
5287
5288 /* Now we have one full header at cur_ptr of len cur_hdr->len,
5289 * and the next header starts at cur_next. We'll check
5290 * this header in the list as well as against the default
5291 * rule.
5292 */
5293
5294 /* look for ': *'. */
5295 hn = cur_ptr;
5296 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
5297 if (p >= cur_ptr+cur_hdr->len)
5298 continue;
5299 hnl = p - hn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005300 p++;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005301 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
5302 p++;
5303 if (p >= cur_ptr+cur_hdr->len)
5304 continue;
5305 hv = p;
5306 hvl = cur_ptr+cur_hdr->len-p;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005307
Christopher Faulet724a12c2018-12-13 22:12:15 +01005308 /* Lowercase the key. Don't check the size of trash, it have
5309 * the size of one buffer and the input data contains in one
5310 * buffer.
5311 */
5312 out = trash.area;
5313 for (in=hn; in<hn+hnl; in++, out++)
5314 *out = tolower(*in);
5315 *out = '\0';
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005316
Christopher Faulet724a12c2018-12-13 22:12:15 +01005317 /* Check for existing entry:
5318 * assume that the table is on the top of the stack, and
5319 * push the key in the stack, the function lua_gettable()
5320 * perform the lookup.
5321 */
5322 lua_pushlstring(L, trash.area, hnl);
5323 lua_gettable(L, -2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005324
Christopher Faulet724a12c2018-12-13 22:12:15 +01005325 switch (lua_type(L, -1)) {
5326 case LUA_TNIL:
5327 /* Table not found, create it. */
5328 lua_pop(L, 1); /* remove the nil value. */
5329 lua_pushlstring(L, trash.area, hnl); /* push the header name as key. */
5330 lua_newtable(L); /* create and push empty table. */
5331 lua_pushlstring(L, hv, hvl); /* push header value. */
5332 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5333 lua_rawset(L, -3); /* index new table with header name (pop the values). */
5334 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005335
Christopher Faulet724a12c2018-12-13 22:12:15 +01005336 case LUA_TTABLE:
5337 /* Entry found: push the value in the table. */
5338 len = lua_rawlen(L, -1);
5339 lua_pushlstring(L, hv, hvl); /* push header value. */
5340 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5341 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5342 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005343
Christopher Faulet724a12c2018-12-13 22:12:15 +01005344 default:
5345 /* Other cases are errors. */
5346 hlua_pusherror(L, "internal error during the parsing of headers.");
5347 WILL_LJMP(lua_error(L));
5348 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005349 }
5350 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005351 return 1;
5352}
5353
5354__LJMP static int hlua_http_req_get_headers(lua_State *L)
5355{
5356 struct hlua_txn *htxn;
5357
5358 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5359 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5360
Christopher Faulet2351ca22019-07-26 16:31:34 +02005361 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005362 WILL_LJMP(lua_error(L));
5363
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005364 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
5365}
5366
5367__LJMP static int hlua_http_res_get_headers(lua_State *L)
5368{
5369 struct hlua_txn *htxn;
5370
5371 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5372 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5373
Christopher Faulet2351ca22019-07-26 16:31:34 +02005374 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005375 WILL_LJMP(lua_error(L));
5376
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005377 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
5378}
5379
5380/* This function replace full header, or just a value in
5381 * the request or in the response. It is a wrapper fir the
5382 * 4 following functions.
5383 */
5384__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
5385 struct http_msg *msg, int action)
5386{
5387 size_t name_len;
5388 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5389 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5390 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Dragan Dosen26743032019-04-30 15:54:36 +02005391 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005392
Dragan Dosen26743032019-04-30 15:54:36 +02005393 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005394 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5395
Christopher Faulet5a8549e2019-06-17 13:36:06 +02005396 if (IS_HTX_STRM(htxn->s)) {
5397 struct htx *htx = htxbuf(&msg->chn->buf);
5398
5399 htx_transform_header_str(htxn->s, msg->chn, htx, ist2(name, name_len), value, re, action);
5400 }
5401 else
5402 http_transform_header_str(htxn->s, msg, name, name_len, value, re, action);
Dragan Dosen26743032019-04-30 15:54:36 +02005403 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005404 return 0;
5405}
5406
5407__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5408{
5409 struct hlua_txn *htxn;
5410
5411 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5412 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5413
Christopher Faulet2351ca22019-07-26 16:31:34 +02005414 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005415 WILL_LJMP(lua_error(L));
5416
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005417 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
5418}
5419
5420__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5421{
5422 struct hlua_txn *htxn;
5423
5424 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5425 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5426
Christopher Faulet2351ca22019-07-26 16:31:34 +02005427 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005428 WILL_LJMP(lua_error(L));
5429
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005430 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
5431}
5432
5433__LJMP static int hlua_http_req_rep_val(lua_State *L)
5434{
5435 struct hlua_txn *htxn;
5436
5437 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5438 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5439
Christopher Faulet2351ca22019-07-26 16:31:34 +02005440 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005441 WILL_LJMP(lua_error(L));
5442
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005443 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
5444}
5445
5446__LJMP static int hlua_http_res_rep_val(lua_State *L)
5447{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005448 struct hlua_txn *htxn;
5449
5450 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5451 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5452
Christopher Faulet2351ca22019-07-26 16:31:34 +02005453 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005454 WILL_LJMP(lua_error(L));
5455
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02005456 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005457}
5458
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005459/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005460 * It is a wrapper for the 2 following functions.
5461 */
5462__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5463{
5464 size_t len;
5465 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005466
Christopher Faulet724a12c2018-12-13 22:12:15 +01005467 if (IS_HTX_STRM(htxn->s)) {
5468 /* HTX version */
5469 struct htx *htx = htxbuf(&msg->chn->buf);
5470 struct http_hdr_ctx ctx;
5471
5472 ctx.blk = NULL;
5473 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5474 http_remove_header(htx, &ctx);
5475 }
5476 else {
5477 /* Legacy HTTP version */
5478 struct hdr_ctx ctx;
5479 struct http_txn *txn = htxn->s->txn;
5480
5481 ctx.idx = 0;
5482 while (http_find_header2(name, len, ci_head(msg->chn), &txn->hdr_idx, &ctx))
5483 http_remove_header2(msg, &txn->hdr_idx, &ctx);
5484 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005485 return 0;
5486}
5487
5488__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5489{
5490 struct hlua_txn *htxn;
5491
5492 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5493 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5494
Christopher Faulet2351ca22019-07-26 16:31:34 +02005495 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005496 WILL_LJMP(lua_error(L));
5497
Willy Tarreaueee5b512015-04-03 23:46:31 +02005498 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005499}
5500
5501__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5502{
5503 struct hlua_txn *htxn;
5504
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005505 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005506 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5507
Christopher Faulet2351ca22019-07-26 16:31:34 +02005508 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005509 WILL_LJMP(lua_error(L));
5510
Willy Tarreaueee5b512015-04-03 23:46:31 +02005511 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005512}
5513
5514/* This function adds an header. It is a wrapper used by
5515 * the 2 following functions.
5516 */
5517__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5518{
5519 size_t name_len;
5520 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5521 size_t value_len;
5522 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
5523 char *p;
5524
Christopher Faulet724a12c2018-12-13 22:12:15 +01005525 if (IS_HTX_STRM(htxn->s)) {
5526 /* HTX version */
5527 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005528
Christopher Faulet724a12c2018-12-13 22:12:15 +01005529 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5530 ist2(value, value_len)));
5531 }
5532 else {
5533 /* Legacy HTTP version */
5534 /* Check length. */
5535 trash.data = value_len + name_len + 2;
5536 if (trash.data > trash.size)
5537 return 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005538
Christopher Faulet724a12c2018-12-13 22:12:15 +01005539 /* Creates the header string. */
5540 p = trash.area;
5541 memcpy(p, name, name_len);
5542 p += name_len;
5543 *p = ':';
5544 p++;
5545 *p = ' ';
5546 p++;
5547 memcpy(p, value, value_len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005548
Christopher Faulet724a12c2018-12-13 22:12:15 +01005549 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
5550 trash.area, trash.data) != 0);
5551 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005552 return 0;
5553}
5554
5555__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5556{
5557 struct hlua_txn *htxn;
5558
5559 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5560 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5561
Christopher Faulet2351ca22019-07-26 16:31:34 +02005562 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005563 WILL_LJMP(lua_error(L));
5564
Willy Tarreaueee5b512015-04-03 23:46:31 +02005565 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005566}
5567
5568__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5569{
5570 struct hlua_txn *htxn;
5571
5572 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5573 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5574
Christopher Faulet2351ca22019-07-26 16:31:34 +02005575 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005576 WILL_LJMP(lua_error(L));
5577
Willy Tarreaueee5b512015-04-03 23:46:31 +02005578 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005579}
5580
5581static int hlua_http_req_set_hdr(lua_State *L)
5582{
5583 struct hlua_txn *htxn;
5584
5585 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5586 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5587
Christopher Faulet2351ca22019-07-26 16:31:34 +02005588 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005589 WILL_LJMP(lua_error(L));
5590
Willy Tarreaueee5b512015-04-03 23:46:31 +02005591 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
5592 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005593}
5594
5595static int hlua_http_res_set_hdr(lua_State *L)
5596{
5597 struct hlua_txn *htxn;
5598
5599 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5600 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5601
Christopher Faulet2351ca22019-07-26 16:31:34 +02005602 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005603 WILL_LJMP(lua_error(L));
5604
Willy Tarreaueee5b512015-04-03 23:46:31 +02005605 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
5606 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005607}
5608
5609/* This function set the method. */
5610static int hlua_http_req_set_meth(lua_State *L)
5611{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005612 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005613 size_t name_len;
5614 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005615
Christopher Faulet2351ca22019-07-26 16:31:34 +02005616 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005617 WILL_LJMP(lua_error(L));
5618
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005619 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005620 return 1;
5621}
5622
5623/* This function set the method. */
5624static int hlua_http_req_set_path(lua_State *L)
5625{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005626 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005627 size_t name_len;
5628 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005629
Christopher Faulet2351ca22019-07-26 16:31:34 +02005630 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005631 WILL_LJMP(lua_error(L));
5632
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005633 lua_pushboolean(L, http_replace_req_line(1, 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 query-string. */
5638static int hlua_http_req_set_query(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 FOURNIER08504f42015-03-16 14:17:08 +01005643
Christopher Faulet2351ca22019-07-26 16:31:34 +02005644 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005645 WILL_LJMP(lua_error(L));
5646
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005647 /* Check length. */
5648 if (name_len > trash.size - 1) {
5649 lua_pushboolean(L, 0);
5650 return 1;
5651 }
5652
5653 /* Add the mark question as prefix. */
5654 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005655 trash.area[trash.data++] = '?';
5656 memcpy(trash.area + trash.data, name, name_len);
5657 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005658
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005659 lua_pushboolean(L,
5660 http_replace_req_line(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005661 return 1;
5662}
5663
5664/* This function set the uri. */
5665static int hlua_http_req_set_uri(lua_State *L)
5666{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005667 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005668 size_t name_len;
5669 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005670
Christopher Faulet2351ca22019-07-26 16:31:34 +02005671 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005672 WILL_LJMP(lua_error(L));
5673
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005674 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005675 return 1;
5676}
5677
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005678/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005679static int hlua_http_res_set_status(lua_State *L)
5680{
5681 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5682 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005683 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005684
Christopher Faulet2351ca22019-07-26 16:31:34 +02005685 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005686 WILL_LJMP(lua_error(L));
5687
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005688 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005689 return 0;
5690}
5691
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005692/*
5693 *
5694 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005695 * Class TXN
5696 *
5697 *
5698 */
5699
5700/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005701 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005702 */
5703__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5704{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005705 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005706}
5707
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005708__LJMP static int hlua_set_var(lua_State *L)
5709{
5710 struct hlua_txn *htxn;
5711 const char *name;
5712 size_t len;
5713 struct sample smp;
5714
5715 MAY_LJMP(check_args(L, 3, "set_var"));
5716
5717 /* It is useles to retrieve the stream, but this function
5718 * runs only in a stream context.
5719 */
5720 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5721 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5722
5723 /* Converts the third argument in a sample. */
5724 hlua_lua2smp(L, 3, &smp);
5725
5726 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005727 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005728 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005729 return 0;
5730}
5731
Christopher Faulet85d79c92016-11-09 16:54:56 +01005732__LJMP static int hlua_unset_var(lua_State *L)
5733{
5734 struct hlua_txn *htxn;
5735 const char *name;
5736 size_t len;
5737 struct sample smp;
5738
5739 MAY_LJMP(check_args(L, 2, "unset_var"));
5740
5741 /* It is useles to retrieve the stream, but this function
5742 * runs only in a stream context.
5743 */
5744 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5745 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5746
5747 /* Unset the variable. */
5748 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5749 vars_unset_by_name(name, len, &smp);
5750 return 0;
5751}
5752
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005753__LJMP static int hlua_get_var(lua_State *L)
5754{
5755 struct hlua_txn *htxn;
5756 const char *name;
5757 size_t len;
5758 struct sample smp;
5759
5760 MAY_LJMP(check_args(L, 2, "get_var"));
5761
5762 /* It is useles to retrieve the stream, but this function
5763 * runs only in a stream context.
5764 */
5765 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5766 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5767
Willy Tarreau7560dd42016-03-10 16:28:58 +01005768 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005769 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005770 lua_pushnil(L);
5771 return 1;
5772 }
5773
5774 return hlua_smp2lua(L, &smp);
5775}
5776
Willy Tarreau59551662015-03-10 14:23:13 +01005777__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005778{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005779 struct hlua *hlua;
5780
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005781 MAY_LJMP(check_args(L, 2, "set_priv"));
5782
Willy Tarreau87b09662015-04-03 00:22:06 +02005783 /* It is useles to retrieve the stream, but this function
5784 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005785 */
5786 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005787 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005788
5789 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005790 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005791
5792 /* Get and store new value. */
5793 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5794 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5795
5796 return 0;
5797}
5798
Willy Tarreau59551662015-03-10 14:23:13 +01005799__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005800{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005801 struct hlua *hlua;
5802
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005803 MAY_LJMP(check_args(L, 1, "get_priv"));
5804
Willy Tarreau87b09662015-04-03 00:22:06 +02005805 /* It is useles to retrieve the stream, but this function
5806 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005807 */
5808 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005809 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005810
5811 /* Push configuration index in the stack. */
5812 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5813
5814 return 1;
5815}
5816
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005817/* Create stack entry containing a class TXN. This function
5818 * return 0 if the stack does not contains free slots,
5819 * otherwise it returns 1.
5820 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005821static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005822{
Willy Tarreaude491382015-04-06 11:04:28 +02005823 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005824
5825 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005826 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005827 return 0;
5828
5829 /* NOTE: The allocation never fails. The failure
5830 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005831 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005832 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005833 /* Create the object: obj[0] = userdata. */
5834 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005835 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005836 lua_rawseti(L, -2, 0);
5837
Willy Tarreaude491382015-04-06 11:04:28 +02005838 htxn->s = s;
5839 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005840 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005841 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005842
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005843 /* Create the "f" field that contains a list of fetches. */
5844 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005845 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005846 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005847 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005848
5849 /* Create the "sf" field that contains a list of stringsafe fetches. */
5850 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005851 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005852 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005853 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005854
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005855 /* Create the "c" field that contains a list of converters. */
5856 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005857 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005858 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005859 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005860
5861 /* Create the "sc" field that contains a list of stringsafe converters. */
5862 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005863 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005864 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005865 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005866
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005867 /* Create the "req" field that contains the request channel object. */
5868 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005869 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005870 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005871 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005872
5873 /* Create the "res" field that contains the response channel object. */
5874 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005875 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005876 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005877 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005878
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005879 /* Creates the HTTP object is the current proxy allows http. */
5880 lua_pushstring(L, "http");
5881 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005882 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005883 return 0;
5884 }
5885 else
5886 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005887 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005888
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005889 /* Pop a class sesison metatable and affect it to the userdata. */
5890 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5891 lua_setmetatable(L, -2);
5892
5893 return 1;
5894}
5895
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005896__LJMP static int hlua_txn_deflog(lua_State *L)
5897{
5898 const char *msg;
5899 struct hlua_txn *htxn;
5900
5901 MAY_LJMP(check_args(L, 2, "deflog"));
5902 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5903 msg = MAY_LJMP(luaL_checkstring(L, 2));
5904
5905 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5906 return 0;
5907}
5908
5909__LJMP static int hlua_txn_log(lua_State *L)
5910{
5911 int level;
5912 const char *msg;
5913 struct hlua_txn *htxn;
5914
5915 MAY_LJMP(check_args(L, 3, "log"));
5916 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5917 level = MAY_LJMP(luaL_checkinteger(L, 2));
5918 msg = MAY_LJMP(luaL_checkstring(L, 3));
5919
5920 if (level < 0 || level >= NB_LOG_LEVELS)
5921 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5922
5923 hlua_sendlog(htxn->s->be, level, msg);
5924 return 0;
5925}
5926
5927__LJMP static int hlua_txn_log_debug(lua_State *L)
5928{
5929 const char *msg;
5930 struct hlua_txn *htxn;
5931
5932 MAY_LJMP(check_args(L, 2, "Debug"));
5933 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5934 msg = MAY_LJMP(luaL_checkstring(L, 2));
5935 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5936 return 0;
5937}
5938
5939__LJMP static int hlua_txn_log_info(lua_State *L)
5940{
5941 const char *msg;
5942 struct hlua_txn *htxn;
5943
5944 MAY_LJMP(check_args(L, 2, "Info"));
5945 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5946 msg = MAY_LJMP(luaL_checkstring(L, 2));
5947 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5948 return 0;
5949}
5950
5951__LJMP static int hlua_txn_log_warning(lua_State *L)
5952{
5953 const char *msg;
5954 struct hlua_txn *htxn;
5955
5956 MAY_LJMP(check_args(L, 2, "Warning"));
5957 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5958 msg = MAY_LJMP(luaL_checkstring(L, 2));
5959 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5960 return 0;
5961}
5962
5963__LJMP static int hlua_txn_log_alert(lua_State *L)
5964{
5965 const char *msg;
5966 struct hlua_txn *htxn;
5967
5968 MAY_LJMP(check_args(L, 2, "Alert"));
5969 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5970 msg = MAY_LJMP(luaL_checkstring(L, 2));
5971 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5972 return 0;
5973}
5974
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005975__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5976{
5977 struct hlua_txn *htxn;
5978 int ll;
5979
5980 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5981 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5982 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5983
5984 if (ll < 0 || ll > 7)
5985 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5986
5987 htxn->s->logs.level = ll;
5988 return 0;
5989}
5990
5991__LJMP static int hlua_txn_set_tos(lua_State *L)
5992{
5993 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005994 int tos;
5995
5996 MAY_LJMP(check_args(L, 2, "set_tos"));
5997 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5998 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5999
Willy Tarreau1a18b542018-12-11 16:37:42 +01006000 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006001 return 0;
6002}
6003
6004__LJMP static int hlua_txn_set_mark(lua_State *L)
6005{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006006 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006007 int mark;
6008
6009 MAY_LJMP(check_args(L, 2, "set_mark"));
6010 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6011 mark = MAY_LJMP(luaL_checkinteger(L, 2));
6012
Lukas Tribusb59291a2019-08-11 18:03:45 +02006013 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006014 return 0;
6015}
6016
Patrick Hemmer268a7072018-05-11 12:52:31 -04006017__LJMP static int hlua_txn_set_priority_class(lua_State *L)
6018{
6019 struct hlua_txn *htxn;
6020
6021 MAY_LJMP(check_args(L, 2, "set_priority_class"));
6022 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6023 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
6024 return 0;
6025}
6026
6027__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
6028{
6029 struct hlua_txn *htxn;
6030
6031 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
6032 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6033 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
6034 return 0;
6035}
6036
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006037/* This function is an Lua binding that send pending data
6038 * to the client, and close the stream interface.
6039 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006040__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006041{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006042 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006043 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01006044 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006045
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006046 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006047 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006048 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006049
Thierry FOURNIERab00df62016-07-14 11:42:37 +02006050 /* If the flags NOTERM is set, we cannot terminate the http
6051 * session, so we just end the execution of the current
6052 * lua code.
6053 */
6054 if (htxn->flags & HLUA_TXN_NOTERM) {
6055 WILL_LJMP(hlua_done(L));
6056 return 0;
6057 }
6058
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006059 ic = &htxn->s->req;
6060 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01006061
Christopher Faulet72c69272019-07-26 16:40:24 +02006062 if (IS_HTX_STRM(htxn->s)) {
6063 htxn->s->txn->status = 0;
6064 http_reply_and_close(htxn->s, 0, NULL);
6065 ic->analysers &= AN_REQ_FLT_END;
6066 oc->analysers &= AN_RES_FLT_END;
6067 }
Christopher Fauletb58fb792019-07-16 10:52:40 +02006068 else {
6069 if (htxn->s->txn) {
6070 /* HTTP mode, let's stay in sync with the stream */
6071 b_del(&ic->buf, htxn->s->txn->req.sov);
6072 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
6073 htxn->s->txn->req.sov = 0;
6074
6075 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
6076 oc->analysers = AN_RES_HTTP_XFER_BODY;
6077 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
6078 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
Willy Tarreau630ef452015-08-28 10:06:15 +02006079
Willy Tarreau630ef452015-08-28 10:06:15 +02006080 /* Note that if we want to support keep-alive, we need
6081 * to bypass the close/shutr_now calls below, but that
6082 * may only be done if the HTTP request was already
6083 * processed and the connection header is known (ie
6084 * not during TCP rules).
6085 */
Christopher Fauletb58fb792019-07-16 10:52:40 +02006086 }
Willy Tarreau630ef452015-08-28 10:06:15 +02006087
Christopher Fauletb58fb792019-07-16 10:52:40 +02006088 channel_auto_read(ic);
6089 channel_abort(ic);
6090 channel_auto_close(ic);
6091 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02006092
Christopher Fauletb58fb792019-07-16 10:52:40 +02006093 oc->wex = tick_add_ifset(now_ms, oc->wto);
6094 channel_auto_read(oc);
6095 channel_auto_close(oc);
6096 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006097
Christopher Fauletb58fb792019-07-16 10:52:40 +02006098 ic->analysers = 0;
6099 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006100
Christopher Faulet72c69272019-07-26 16:40:24 +02006101 if (!(htxn->s->flags & SF_ERR_MASK)) // this is not really an error but it is
6102 htxn->s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
6103
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006104 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006105 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006106 return 0;
6107}
6108
6109__LJMP static int hlua_log(lua_State *L)
6110{
6111 int level;
6112 const char *msg;
6113
6114 MAY_LJMP(check_args(L, 2, "log"));
6115 level = MAY_LJMP(luaL_checkinteger(L, 1));
6116 msg = MAY_LJMP(luaL_checkstring(L, 2));
6117
6118 if (level < 0 || level >= NB_LOG_LEVELS)
6119 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
6120
6121 hlua_sendlog(NULL, level, msg);
6122 return 0;
6123}
6124
6125__LJMP static int hlua_log_debug(lua_State *L)
6126{
6127 const char *msg;
6128
6129 MAY_LJMP(check_args(L, 1, "debug"));
6130 msg = MAY_LJMP(luaL_checkstring(L, 1));
6131 hlua_sendlog(NULL, LOG_DEBUG, msg);
6132 return 0;
6133}
6134
6135__LJMP static int hlua_log_info(lua_State *L)
6136{
6137 const char *msg;
6138
6139 MAY_LJMP(check_args(L, 1, "info"));
6140 msg = MAY_LJMP(luaL_checkstring(L, 1));
6141 hlua_sendlog(NULL, LOG_INFO, msg);
6142 return 0;
6143}
6144
6145__LJMP static int hlua_log_warning(lua_State *L)
6146{
6147 const char *msg;
6148
6149 MAY_LJMP(check_args(L, 1, "warning"));
6150 msg = MAY_LJMP(luaL_checkstring(L, 1));
6151 hlua_sendlog(NULL, LOG_WARNING, msg);
6152 return 0;
6153}
6154
6155__LJMP static int hlua_log_alert(lua_State *L)
6156{
6157 const char *msg;
6158
6159 MAY_LJMP(check_args(L, 1, "alert"));
6160 msg = MAY_LJMP(luaL_checkstring(L, 1));
6161 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006162 return 0;
6163}
6164
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006165__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006166{
6167 int wakeup_ms = lua_tointeger(L, -1);
6168 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02006169 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006170 return 0;
6171}
6172
6173__LJMP static int hlua_sleep(lua_State *L)
6174{
6175 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006176 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006177
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006178 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006179
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006180 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006181 wakeup_ms = tick_add(now_ms, delay);
6182 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006183
Willy Tarreau9635e032018-10-16 17:52:55 +02006184 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006185 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006186}
6187
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006188__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006189{
6190 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006191 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006192
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006193 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006194
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006195 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006196 wakeup_ms = tick_add(now_ms, delay);
6197 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006198
Willy Tarreau9635e032018-10-16 17:52:55 +02006199 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006200 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006201}
6202
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006203/* This functionis an LUA binding. it permits to give back
6204 * the hand at the HAProxy scheduler. It is used when the
6205 * LUA processing consumes a lot of time.
6206 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006207__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006208{
6209 return 0;
6210}
6211
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006212__LJMP static int hlua_yield(lua_State *L)
6213{
Willy Tarreau9635e032018-10-16 17:52:55 +02006214 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006215 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006216}
6217
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006218/* This function change the nice of the currently executed
6219 * task. It is used set low or high priority at the current
6220 * task.
6221 */
Willy Tarreau59551662015-03-10 14:23:13 +01006222__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006223{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006224 struct hlua *hlua;
6225 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006226
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006227 MAY_LJMP(check_args(L, 1, "set_nice"));
6228 hlua = hlua_gethlua(L);
6229 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006230
6231 /* If he task is not set, I'm in a start mode. */
6232 if (!hlua || !hlua->task)
6233 return 0;
6234
6235 if (nice < -1024)
6236 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006237 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006238 nice = 1024;
6239
6240 hlua->task->nice = nice;
6241 return 0;
6242}
6243
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006244/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006245 * HAProxy task subsystem when the task is awaked. The LUA runtime can
6246 * return an E_AGAIN signal, the emmiter of this signal must set a
6247 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006248 *
6249 * Task wrapper are longjmp safe because the only one Lua code
6250 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006251 */
Willy Tarreau83a5ff42019-08-21 14:14:50 +02006252struct task *hlua_process_task(struct task *task, void *context, unsigned short state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006253{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006254 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006255 enum hlua_exec status;
6256
Christopher Faulet5bc99722018-04-25 10:34:45 +02006257 if (task->thread_mask == MAX_THREADS_MASK)
6258 task_set_affinity(task, tid_bit);
6259
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006260 /* If it is the first call to the task, we must initialize the
6261 * execution timeouts.
6262 */
6263 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006264 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006265
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006266 /* Execute the Lua code. */
6267 status = hlua_ctx_resume(hlua, 1);
6268
6269 switch (status) {
6270 /* finished or yield */
6271 case HLUA_E_OK:
6272 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006273 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02006274 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006275 break;
6276
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006277 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01006278 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02006279 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006280 break;
6281
6282 /* finished with error. */
6283 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006284 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006285 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006286 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006287 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006288 break;
6289
6290 case HLUA_E_ERR:
6291 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006292 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006293 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006294 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006295 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006296 break;
6297 }
Emeric Brun253e53e2017-10-17 18:58:40 +02006298 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006299}
6300
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006301/* This function is an LUA binding that register LUA function to be
6302 * executed after the HAProxy configuration parsing and before the
6303 * HAProxy scheduler starts. This function expect only one LUA
6304 * argument that is a function. This function returns nothing, but
6305 * throws if an error is encountered.
6306 */
6307__LJMP static int hlua_register_init(lua_State *L)
6308{
6309 struct hlua_init_function *init;
6310 int ref;
6311
6312 MAY_LJMP(check_args(L, 1, "register_init"));
6313
6314 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6315
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006316 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006317 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006318 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006319
6320 init->function_ref = ref;
6321 LIST_ADDQ(&hlua_init_functions, &init->l);
6322 return 0;
6323}
6324
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006325/* This functio is an LUA binding. It permits to register a task
6326 * executed in parallel of the main HAroxy activity. The task is
6327 * created and it is set in the HAProxy scheduler. It can be called
6328 * from the "init" section, "post init" or during the runtime.
6329 *
6330 * Lua prototype:
6331 *
6332 * <none> core.register_task(<function>)
6333 */
6334static int hlua_register_task(lua_State *L)
6335{
6336 struct hlua *hlua;
6337 struct task *task;
6338 int ref;
6339
6340 MAY_LJMP(check_args(L, 1, "register_task"));
6341
6342 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6343
Willy Tarreaubafbe012017-11-24 17:34:44 +01006344 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006345 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006346 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006347
Emeric Brunc60def82017-09-27 14:59:38 +02006348 task = task_new(MAX_THREADS_MASK);
Willy Tarreaue09101e2018-10-16 17:37:12 +02006349 if (!task)
6350 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
6351
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006352 task->context = hlua;
6353 task->process = hlua_process_task;
6354
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006355 if (!hlua_ctx_init(hlua, task, 1))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006356 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006357
6358 /* Restore the function in the stack. */
6359 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
6360 hlua->nargs = 0;
6361
6362 /* Schedule task. */
6363 task_schedule(task, now_ms);
6364
6365 return 0;
6366}
6367
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006368/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
6369 * doesn't allow "yield" functions because the HAProxy engine cannot
6370 * resume converters.
6371 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006372static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006373{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006374 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006375 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006376 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006377
Willy Tarreaube508f12016-03-10 11:47:01 +01006378 if (!stream)
6379 return 0;
6380
Willy Tarreau87b09662015-04-03 00:22:06 +02006381 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006382 * Lua context can be not initialized. This behavior
6383 * permits to save performances because a systematic
6384 * Lua initialization cause 5% performances loss.
6385 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006386 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006387 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006388 if (!stream->hlua) {
6389 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6390 return 0;
6391 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006392 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006393 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6394 return 0;
6395 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006396 }
6397
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006398 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006399 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006400
6401 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006402 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6403 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6404 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006405 else
6406 error = "critical error";
6407 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006408 return 0;
6409 }
6410
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006411 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006412 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006413 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006414 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006415 return 0;
6416 }
6417
6418 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006419 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006420
6421 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006422 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006423 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006424 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006425 return 0;
6426 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006427 hlua_smp2lua(stream->hlua->T, smp);
6428 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006429
6430 /* push keywords in the stack. */
6431 if (arg_p) {
6432 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006433 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006434 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006435 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006436 return 0;
6437 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006438 hlua_arg2lua(stream->hlua->T, arg_p);
6439 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006440 }
6441 }
6442
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006443 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006444 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006445
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006446 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006447 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006448 }
6449
6450 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006451 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006452 /* finished. */
6453 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006454 /* If the stack is empty, the function fails. */
6455 if (lua_gettop(stream->hlua->T) <= 0)
6456 return 0;
6457
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006458 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006459 hlua_lua2smp(stream->hlua->T, -1, smp);
6460 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006461 return 1;
6462
6463 /* yield. */
6464 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006465 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006466 return 0;
6467
6468 /* finished with error. */
6469 case HLUA_E_ERRMSG:
6470 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006471 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006472 fcn->name, lua_tostring(stream->hlua->T, -1));
6473 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006474 return 0;
6475
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006476 case HLUA_E_ETMOUT:
6477 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
6478 return 0;
6479
6480 case HLUA_E_NOMEM:
6481 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
6482 return 0;
6483
6484 case HLUA_E_YIELD:
6485 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
6486 return 0;
6487
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006488 case HLUA_E_ERR:
6489 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006490 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006491
6492 default:
6493 return 0;
6494 }
6495}
6496
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006497/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
6498 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01006499 * resume sample-fetches. This function will be called by the sample
6500 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006501 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02006502static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
6503 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006504{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006505 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006506 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006507 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006508 const struct buffer msg = { };
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006509 unsigned int hflags = HLUA_TXN_NOTERM;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006510
Willy Tarreaube508f12016-03-10 11:47:01 +01006511 if (!stream)
6512 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01006513
Willy Tarreau87b09662015-04-03 00:22:06 +02006514 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006515 * Lua context can be not initialized. This behavior
6516 * permits to save performances because a systematic
6517 * Lua initialization cause 5% performances loss.
6518 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006519 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006520 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006521 if (!stream->hlua) {
6522 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6523 return 0;
6524 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006525 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006526 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6527 return 0;
6528 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006529 }
6530
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006531 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006532
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006533 if (stream->be->mode == PR_MODE_HTTP) {
6534 if ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ)
6535 hflags |= ((stream->txn->req.msg_state < HTTP_MSG_BODY) ? 0 : HLUA_TXN_HTTP_RDY);
6536 else
6537 hflags |= ((stream->txn->rsp.msg_state < HTTP_MSG_BODY) ? 0 : HLUA_TXN_HTTP_RDY);
6538 }
6539
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006540 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006541 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006542
6543 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006544 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6545 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6546 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006547 else
6548 error = "critical error";
6549 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006550 return 0;
6551 }
6552
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006553 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006554 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006555 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006556 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006557 return 0;
6558 }
6559
6560 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006561 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006562
6563 /* push arguments in the stack. */
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006564 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006565 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006566 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006567 return 0;
6568 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006569 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006570
6571 /* push keywords in the stack. */
6572 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
6573 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006574 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006575 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006576 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006577 return 0;
6578 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006579 hlua_arg2lua(stream->hlua->T, arg_p);
6580 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006581 }
6582
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006583 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006584 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006585
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006586 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006587 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006588 }
6589
6590 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006591 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006592 /* finished. */
6593 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006594 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006595 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006596 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006597 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006598 /* If the stack is empty, the function fails. */
6599 if (lua_gettop(stream->hlua->T) <= 0)
6600 return 0;
6601
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006602 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006603 hlua_lua2smp(stream->hlua->T, -1, smp);
6604 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006605
6606 /* Set the end of execution flag. */
6607 smp->flags &= ~SMP_F_MAY_CHANGE;
6608 return 1;
6609
6610 /* yield. */
6611 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006612 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006613 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006614 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006615 return 0;
6616
6617 /* finished with error. */
6618 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006619 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006620 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006621 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006622 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006623 fcn->name, lua_tostring(stream->hlua->T, -1));
6624 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006625 return 0;
6626
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006627 case HLUA_E_ETMOUT:
6628 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006629 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006630 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
6631 return 0;
6632
6633 case HLUA_E_NOMEM:
6634 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006635 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006636 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
6637 return 0;
6638
6639 case HLUA_E_YIELD:
6640 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006641 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006642 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
6643 return 0;
6644
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006645 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006646 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006647 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006648 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006649 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006650
6651 default:
6652 return 0;
6653 }
6654}
6655
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006656/* This function is an LUA binding used for registering
6657 * "sample-conv" functions. It expects a converter name used
6658 * in the haproxy configuration file, and an LUA function.
6659 */
6660__LJMP static int hlua_register_converters(lua_State *L)
6661{
6662 struct sample_conv_kw_list *sck;
6663 const char *name;
6664 int ref;
6665 int len;
6666 struct hlua_function *fcn;
6667
6668 MAY_LJMP(check_args(L, 2, "register_converters"));
6669
6670 /* First argument : converter name. */
6671 name = MAY_LJMP(luaL_checkstring(L, 1));
6672
6673 /* Second argument : lua function. */
6674 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6675
6676 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006677 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006678 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006679 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006680 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006681 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006682 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006683
6684 /* Fill fcn. */
6685 fcn->name = strdup(name);
6686 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006687 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006688 fcn->function_ref = ref;
6689
6690 /* List head */
6691 sck->list.n = sck->list.p = NULL;
6692
6693 /* converter keyword. */
6694 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006695 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006696 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006697 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006698
6699 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6700 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006701 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 +01006702 sck->kw[0].val_args = NULL;
6703 sck->kw[0].in_type = SMP_T_STR;
6704 sck->kw[0].out_type = SMP_T_STR;
6705 sck->kw[0].private = fcn;
6706
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006707 /* Register this new converter */
6708 sample_register_convs(sck);
6709
6710 return 0;
6711}
6712
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006713/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006714 * "sample-fetch" functions. It expects a converter name used
6715 * in the haproxy configuration file, and an LUA function.
6716 */
6717__LJMP static int hlua_register_fetches(lua_State *L)
6718{
6719 const char *name;
6720 int ref;
6721 int len;
6722 struct sample_fetch_kw_list *sfk;
6723 struct hlua_function *fcn;
6724
6725 MAY_LJMP(check_args(L, 2, "register_fetches"));
6726
6727 /* First argument : sample-fetch name. */
6728 name = MAY_LJMP(luaL_checkstring(L, 1));
6729
6730 /* Second argument : lua function. */
6731 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6732
6733 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006734 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006735 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006736 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006737 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006738 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006739 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006740
6741 /* Fill fcn. */
6742 fcn->name = strdup(name);
6743 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006744 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006745 fcn->function_ref = ref;
6746
6747 /* List head */
6748 sfk->list.n = sfk->list.p = NULL;
6749
6750 /* sample-fetch keyword. */
6751 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006752 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006753 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006754 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006755
6756 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6757 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006758 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 +01006759 sfk->kw[0].val_args = NULL;
6760 sfk->kw[0].out_type = SMP_T_STR;
6761 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6762 sfk->kw[0].val = 0;
6763 sfk->kw[0].private = fcn;
6764
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006765 /* Register this new fetch. */
6766 sample_register_fetches(sfk);
6767
6768 return 0;
6769}
6770
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006771/* This function is a wrapper to execute each LUA function declared
6772 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006773 * return ACT_RET_CONT if the processing is finished (with or without
6774 * error) and return ACT_RET_YIELD if the function must be called again
6775 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006776 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006777static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006778 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006779{
6780 char **arg;
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006781 unsigned int hflags = 0;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006782 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006783 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006784 const struct buffer msg = { };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006785
6786 switch (rule->from) {
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006787 case ACT_F_TCP_REQ_CNT: ; dir = SMP_OPT_DIR_REQ; break;
6788 case ACT_F_TCP_RES_CNT: ; dir = SMP_OPT_DIR_RES; break;
6789 case ACT_F_HTTP_REQ: hflags = HLUA_TXN_HTTP_RDY ; dir = SMP_OPT_DIR_REQ; break;
6790 case ACT_F_HTTP_RES: hflags = HLUA_TXN_HTTP_RDY ; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006791 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006792 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006793 return ACT_RET_CONT;
6794 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006795
Willy Tarreau87b09662015-04-03 00:22:06 +02006796 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006797 * Lua context can be not initialized. This behavior
6798 * permits to save performances because a systematic
6799 * Lua initialization cause 5% performances loss.
6800 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006801 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006802 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006803 if (!s->hlua) {
6804 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6805 rule->arg.hlua_rule->fcn.name);
6806 return ACT_RET_CONT;
6807 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006808 if (!hlua_ctx_init(s->hlua, s->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006809 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6810 rule->arg.hlua_rule->fcn.name);
6811 return ACT_RET_CONT;
6812 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006813 }
6814
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006815 consistency_set(s, dir, &s->hlua->cons);
6816
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006817 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006818 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006819
6820 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006821 if (!SET_SAFE_LJMP(s->hlua->T)) {
6822 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6823 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006824 else
6825 error = "critical error";
6826 SEND_ERR(px, "Lua function '%s': %s.\n",
6827 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006828 return ACT_RET_CONT;
6829 }
6830
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006831 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006832 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006833 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006834 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006835 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006836 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006837 }
6838
6839 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006840 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006841
Willy Tarreau87b09662015-04-03 00:22:06 +02006842 /* Create and and push object stream in the stack. */
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006843 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006844 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006845 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006846 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006847 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006848 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006849 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006850
6851 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006852 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006853 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006854 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006855 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006856 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006857 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006858 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006859 lua_pushstring(s->hlua->T, *arg);
6860 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006861 }
6862
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006863 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006864 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006865
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006866 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006867 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006868 }
6869
Christopher Faulet719ddc82020-06-02 18:46:07 +02006870 /* Always reset the analyse expiration timeout for the corresponding
6871 * channel in case the lua script yield, to be sure to not keep an
6872 * expired timeout.
6873 */
6874 if (dir == SMP_OPT_DIR_REQ)
6875 s->req.analyse_exp = TICK_ETERNITY;
6876 else
6877 s->res.analyse_exp = TICK_ETERNITY;
6878
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006879 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006880 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006881 /* finished. */
6882 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006883 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006884 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006885 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006886 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006887 if (s->hlua->flags & HLUA_STOP)
Christopher Faulet4629d082019-07-04 11:27:15 +02006888 return ACT_RET_DONE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006889 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006890
6891 /* yield. */
6892 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006893 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006894 if (s->hlua->wake_time != TICK_ETERNITY) {
Christopher Fauletea0b0e22019-08-14 23:19:45 +02006895 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006896 s->req.analyse_exp = s->hlua->wake_time;
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006897 else
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006898 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006899 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006900 /* Some actions can be wake up when a "write" event
6901 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006902 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006903 */
Christopher Fauletb22f6502019-07-26 14:54:52 +02006904 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006905 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006906 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006907 s->req.flags |= CF_WAKE_WRITE;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006908 /* We can quit the function without consistency check
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006909 * because HAProxy is not able to manipulate data, it
6910 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006911 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006912
6913 /* finished with error. */
6914 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006915 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006916 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006917 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006918 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006919 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006920 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006921 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6922 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006923 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006924
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006925 case HLUA_E_ETMOUT:
6926 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006927 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006928 return ACT_RET_ERR;
6929 }
6930 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
6931 return 0;
6932
6933 case HLUA_E_NOMEM:
6934 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006935 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006936 return ACT_RET_ERR;
6937 }
6938 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
6939 return 0;
6940
6941 case HLUA_E_YIELD:
6942 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006943 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006944 return ACT_RET_ERR;
6945 }
6946 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6947 rule->arg.hlua_rule->fcn.name);
6948 return 0;
6949
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006950 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006951 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006952 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006953 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006954 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006955 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006956 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006957 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006958
6959 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006960 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006961 }
6962}
6963
Olivier Houchard9f6af332018-05-25 14:04:04 +02006964struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006965{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006966 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006967
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006968 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006969 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006970 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006971}
6972
6973static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6974{
6975 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006976 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006977 struct task *task;
6978 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006979 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006980
Willy Tarreaubafbe012017-11-24 17:34:44 +01006981 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006982 if (!hlua) {
6983 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6984 ctx->rule->arg.hlua_rule->fcn.name);
6985 return 0;
6986 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006987 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006988 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006989 ctx->ctx.hlua_apptcp.flags = 0;
6990
6991 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006992 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006993 if (!task) {
6994 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6995 ctx->rule->arg.hlua_rule->fcn.name);
6996 return 0;
6997 }
6998 task->nice = 0;
6999 task->context = ctx;
7000 task->process = hlua_applet_wakeup;
7001 ctx->ctx.hlua_apptcp.task = task;
7002
7003 /* In the execution wrappers linked with a stream, the
7004 * Lua context can be not initialized. This behavior
7005 * permits to save performances because a systematic
7006 * Lua initialization cause 5% performances loss.
7007 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007008 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007009 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
7010 ctx->rule->arg.hlua_rule->fcn.name);
7011 return 0;
7012 }
7013
7014 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007015 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007016
7017 /* The following Lua calls can fail. */
7018 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007019 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7020 error = lua_tostring(hlua->T, -1);
7021 else
7022 error = "critical error";
7023 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
7024 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007025 return 0;
7026 }
7027
7028 /* Check stack available size. */
7029 if (!lua_checkstack(hlua->T, 1)) {
7030 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7031 ctx->rule->arg.hlua_rule->fcn.name);
7032 RESET_SAFE_LJMP(hlua->T);
7033 return 0;
7034 }
7035
7036 /* Restore the function in the stack. */
7037 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7038
7039 /* Create and and push object stream in the stack. */
7040 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
7041 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7042 ctx->rule->arg.hlua_rule->fcn.name);
7043 RESET_SAFE_LJMP(hlua->T);
7044 return 0;
7045 }
7046 hlua->nargs = 1;
7047
7048 /* push keywords in the stack. */
7049 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7050 if (!lua_checkstack(hlua->T, 1)) {
7051 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7052 ctx->rule->arg.hlua_rule->fcn.name);
7053 RESET_SAFE_LJMP(hlua->T);
7054 return 0;
7055 }
7056 lua_pushstring(hlua->T, *arg);
7057 hlua->nargs++;
7058 }
7059
7060 RESET_SAFE_LJMP(hlua->T);
7061
7062 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007063 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01007064 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007065
7066 return 1;
7067}
7068
Willy Tarreau83a5ff42019-08-21 14:14:50 +02007069void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007070{
7071 struct stream_interface *si = ctx->owner;
7072 struct stream *strm = si_strm(si);
7073 struct channel *res = si_ic(si);
7074 struct act_rule *rule = ctx->rule;
7075 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007076 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007077
7078 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02007079 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
7080 /* eat the whole request */
7081 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007082 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02007083 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007084
7085 /* If the stream is disconnect or closed, ldo nothing. */
7086 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7087 return;
7088
7089 /* Execute the function. */
7090 switch (hlua_ctx_resume(hlua, 1)) {
7091 /* finished. */
7092 case HLUA_E_OK:
7093 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7094
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007095 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02007096 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007097 res->flags |= CF_READ_NULL;
7098 si_shutr(si);
7099 return;
7100
7101 /* yield. */
7102 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007103 if (hlua->wake_time != TICK_ETERNITY)
7104 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007105 return;
7106
7107 /* finished with error. */
7108 case HLUA_E_ERRMSG:
7109 /* Display log. */
7110 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
7111 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7112 lua_pop(hlua->T, 1);
7113 goto error;
7114
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007115 case HLUA_E_ETMOUT:
7116 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
7117 rule->arg.hlua_rule->fcn.name);
7118 goto error;
7119
7120 case HLUA_E_NOMEM:
7121 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
7122 rule->arg.hlua_rule->fcn.name);
7123 goto error;
7124
7125 case HLUA_E_YIELD: /* unexpected */
7126 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
7127 rule->arg.hlua_rule->fcn.name);
7128 goto error;
7129
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007130 case HLUA_E_ERR:
7131 /* Display log. */
7132 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
7133 rule->arg.hlua_rule->fcn.name);
7134 goto error;
7135
7136 default:
7137 goto error;
7138 }
7139
7140error:
7141
7142 /* For all other cases, just close the stream. */
7143 si_shutw(si);
7144 si_shutr(si);
7145 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7146}
7147
7148static void hlua_applet_tcp_release(struct appctx *ctx)
7149{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007150 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007151 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007152 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007153 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007154}
7155
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007156/* The function returns 1 if the initialisation is complete, 0 if
7157 * an errors occurs and -1 if more data are required for initializing
7158 * the applet.
7159 */
7160static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
7161{
7162 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007163 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007164 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007165 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007166 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007167 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007168
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007169 txn = strm->txn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007170
Willy Tarreau0078bfc2015-10-07 20:20:28 +02007171 /* We want two things in HTTP mode :
7172 * - enforce server-close mode if we were in keep-alive, so that the
7173 * applet is released after each response ;
7174 * - enable request body transfer to the applet in order to resync
7175 * with the response body.
7176 */
7177 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
7178 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02007179
Willy Tarreaubafbe012017-11-24 17:34:44 +01007180 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007181 if (!hlua) {
7182 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7183 ctx->rule->arg.hlua_rule->fcn.name);
7184 return 0;
7185 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007186 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007187 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007188 ctx->ctx.hlua_apphttp.left_bytes = -1;
7189 ctx->ctx.hlua_apphttp.flags = 0;
7190
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01007191 if (txn->req.flags & HTTP_MSGF_VER_11)
7192 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
7193
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007194 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007195 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007196 if (!task) {
7197 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7198 ctx->rule->arg.hlua_rule->fcn.name);
7199 return 0;
7200 }
7201 task->nice = 0;
7202 task->context = ctx;
7203 task->process = hlua_applet_wakeup;
7204 ctx->ctx.hlua_apphttp.task = task;
7205
7206 /* In the execution wrappers linked with a stream, the
7207 * Lua context can be not initialized. This behavior
7208 * permits to save performances because a systematic
7209 * Lua initialization cause 5% performances loss.
7210 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007211 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007212 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
7213 ctx->rule->arg.hlua_rule->fcn.name);
7214 return 0;
7215 }
7216
7217 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007218 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007219
7220 /* The following Lua calls can fail. */
7221 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007222 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7223 error = lua_tostring(hlua->T, -1);
7224 else
7225 error = "critical error";
7226 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7227 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007228 return 0;
7229 }
7230
7231 /* Check stack available size. */
7232 if (!lua_checkstack(hlua->T, 1)) {
7233 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7234 ctx->rule->arg.hlua_rule->fcn.name);
7235 RESET_SAFE_LJMP(hlua->T);
7236 return 0;
7237 }
7238
7239 /* Restore the function in the stack. */
7240 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7241
7242 /* Create and and push object stream in the stack. */
7243 if (!hlua_applet_http_new(hlua->T, ctx)) {
7244 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7245 ctx->rule->arg.hlua_rule->fcn.name);
7246 RESET_SAFE_LJMP(hlua->T);
7247 return 0;
7248 }
7249 hlua->nargs = 1;
7250
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007251 /* push keywords in the stack. */
7252 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7253 if (!lua_checkstack(hlua->T, 1)) {
7254 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7255 ctx->rule->arg.hlua_rule->fcn.name);
7256 RESET_SAFE_LJMP(hlua->T);
7257 return 0;
7258 }
7259 lua_pushstring(hlua->T, *arg);
7260 hlua->nargs++;
7261 }
7262
7263 RESET_SAFE_LJMP(hlua->T);
7264
7265 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007266 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007267
7268 return 1;
7269}
7270
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007271static void hlua_applet_htx_fct(struct appctx *ctx)
7272{
7273 struct stream_interface *si = ctx->owner;
7274 struct stream *strm = si_strm(si);
7275 struct channel *req = si_oc(si);
7276 struct channel *res = si_ic(si);
7277 struct act_rule *rule = ctx->rule;
7278 struct proxy *px = strm->be;
7279 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
7280 struct htx *req_htx, *res_htx;
7281
7282 res_htx = htx_from_buf(&res->buf);
7283
7284 /* If the stream is disconnect or closed, ldo nothing. */
7285 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7286 goto out;
7287
7288 /* Check if the input buffer is avalaible. */
7289 if (!b_size(&res->buf)) {
7290 si_rx_room_blk(si);
7291 goto out;
7292 }
7293 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007294 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007295 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7296
7297 /* Set the currently running flag. */
7298 if (!HLUA_IS_RUNNING(hlua) &&
7299 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7300 struct htx_blk *blk;
7301 size_t count = co_data(req);
7302
7303 if (!count) {
7304 si_cant_get(si);
7305 goto out;
7306 }
7307
7308 /* We need to flush the request header. This left the body for
7309 * the Lua.
7310 */
7311 req_htx = htx_from_buf(&req->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02007312 blk = htx_get_first_blk(req_htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007313 while (count && blk) {
7314 enum htx_blk_type type = htx_get_blk_type(blk);
7315 uint32_t sz = htx_get_blksz(blk);
7316
7317 if (sz > count) {
7318 si_cant_get(si);
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007319 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007320 goto out;
7321 }
7322
7323 count -= sz;
7324 co_set_data(req, co_data(req) - sz);
7325 blk = htx_remove_blk(req_htx, blk);
7326
7327 if (type == HTX_BLK_EOH)
7328 break;
7329 }
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007330 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007331 }
7332
7333 /* Executes The applet if it is not done. */
7334 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7335
7336 /* Execute the function. */
7337 switch (hlua_ctx_resume(hlua, 1)) {
7338 /* finished. */
7339 case HLUA_E_OK:
7340 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7341 break;
7342
7343 /* yield. */
7344 case HLUA_E_AGAIN:
7345 if (hlua->wake_time != TICK_ETERNITY)
7346 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007347 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007348
7349 /* finished with error. */
7350 case HLUA_E_ERRMSG:
7351 /* Display log. */
7352 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7353 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7354 lua_pop(hlua->T, 1);
7355 goto error;
7356
7357 case HLUA_E_ETMOUT:
7358 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7359 rule->arg.hlua_rule->fcn.name);
7360 goto error;
7361
7362 case HLUA_E_NOMEM:
7363 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7364 rule->arg.hlua_rule->fcn.name);
7365 goto error;
7366
7367 case HLUA_E_YIELD: /* unexpected */
7368 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7369 rule->arg.hlua_rule->fcn.name);
7370 goto error;
7371
7372 case HLUA_E_ERR:
7373 /* Display log. */
7374 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7375 rule->arg.hlua_rule->fcn.name);
7376 goto error;
7377
7378 default:
7379 goto error;
7380 }
7381 }
7382
7383 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007384 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7385 goto done;
7386
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007387 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7388 goto error;
7389
Christopher Faulet54b5e212019-06-04 10:08:28 +02007390 /* Don't add TLR because mux-h1 will take care of it */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007391 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
7392 si_rx_room_blk(si);
7393 goto out;
7394 }
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007395 channel_add_input(res, 1);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007396 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7397 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007398 }
7399
7400 done:
7401 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007402 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007403 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007404 si_shutr(si);
7405 }
7406
7407 /* eat the whole request */
7408 if (co_data(req)) {
7409 req_htx = htx_from_buf(&req->buf);
7410 co_htx_skip(req, req_htx, co_data(req));
7411 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007412 }
7413 }
7414
7415 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007416 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007417 return;
7418
7419 error:
7420
7421 /* If we are in HTTP mode, and we are not send any
7422 * data, return a 500 server error in best effort:
7423 * if there is no room available in the buffer,
7424 * just close the connection.
7425 */
7426 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
7427 struct buffer *err = &htx_err_chunks[HTTP_ERR_500];
7428
7429 channel_erase(res);
7430 res->buf.data = b_data(err);
7431 memcpy(res->buf.area, b_head(err), b_data(err));
7432 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007433 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007434 }
7435 if (!(strm->flags & SF_ERR_MASK))
7436 strm->flags |= SF_ERR_RESOURCE;
7437 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7438 goto done;
7439}
7440
Willy Tarreau83a5ff42019-08-21 14:14:50 +02007441void hlua_applet_http_fct(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007442{
7443 struct stream_interface *si = ctx->owner;
7444 struct stream *strm = si_strm(si);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007445 struct channel *req = si_oc(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007446 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007447 struct act_rule *rule = ctx->rule;
7448 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007449 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Willy Tarreau206ba832018-06-14 15:27:31 +02007450 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02007451 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02007452 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02007453 size_t len2;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007454 int ret;
7455
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007456 if (IS_HTX_STRM(strm))
7457 return hlua_applet_htx_fct(ctx);
7458
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007459 /* If the stream is disconnect or closed, ldo nothing. */
7460 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007461 goto out;
7462
7463 /* Check if the input buffer is avalaible. */
7464 if (!b_size(&res->buf)) {
7465 si_rx_room_blk(si);
7466 goto out;
7467 }
7468 /* check that the output is not closed */
7469 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
7470 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007471
7472 /* Set the currently running flag. */
7473 if (!HLUA_IS_RUNNING(hlua) &&
7474 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007475 /* Store the max amount of bytes that we can read. */
7476 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
7477
7478 /* We need to flush the request header. This left the body
7479 * for the Lua.
7480 */
7481
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007482 /* Read the maximum amount of data available. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007483 ret = co_getblk_nc(req, &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007484 if (ret == -1)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007485 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007486
7487 /* No data available, ask for more data. */
7488 if (ret == 1)
7489 len2 = 0;
7490 if (ret == 0)
7491 len1 = 0;
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02007492 if (len1 + len2 < strm->txn->req.eoh + strm->txn->req.eol) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007493 si_cant_get(si);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007494 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007495 }
7496
7497 /* skip the requests bytes. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007498 co_skip(req, strm->txn->req.eoh + strm->txn->req.eol);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007499 }
7500
7501 /* Executes The applet if it is not done. */
7502 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7503
7504 /* Execute the function. */
7505 switch (hlua_ctx_resume(hlua, 1)) {
7506 /* finished. */
7507 case HLUA_E_OK:
7508 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7509 break;
7510
7511 /* yield. */
7512 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007513 if (hlua->wake_time != TICK_ETERNITY)
7514 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007515 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007516
7517 /* finished with error. */
7518 case HLUA_E_ERRMSG:
7519 /* Display log. */
7520 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7521 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7522 lua_pop(hlua->T, 1);
7523 goto error;
7524
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007525 case HLUA_E_ETMOUT:
7526 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7527 rule->arg.hlua_rule->fcn.name);
7528 goto error;
7529
7530 case HLUA_E_NOMEM:
7531 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7532 rule->arg.hlua_rule->fcn.name);
7533 goto error;
7534
7535 case HLUA_E_YIELD: /* unexpected */
7536 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7537 rule->arg.hlua_rule->fcn.name);
7538 goto error;
7539
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007540 case HLUA_E_ERR:
7541 /* Display log. */
7542 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7543 rule->arg.hlua_rule->fcn.name);
7544 goto error;
7545
7546 default:
7547 goto error;
7548 }
7549 }
7550
7551 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007552 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7553 goto done;
7554
Christopher Fauletcc26b132018-12-18 21:20:57 +01007555 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7556 goto error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007557
7558 /* We must send the final chunk. */
7559 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
7560 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
7561
7562 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02007563 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007564
7565 /* critical error. */
7566 if (ret == -2 || ret == -3) {
7567 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
7568 rule->arg.hlua_rule->fcn.name);
7569 goto error;
7570 }
7571
7572 /* no enough space error. */
7573 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01007574 si_rx_room_blk(si);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007575 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007576 }
7577
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007578 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7579 ctx->ctx.hlua_apphttp.flags |= (APPLET_LAST_CHK|APPLET_RSP_SENT);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007580 }
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007581 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007582
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007583 done:
7584 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
7585 if (!(res->flags & CF_SHUTR)) {
7586 res->flags |= CF_READ_NULL;
7587 si_shutr(si);
7588 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007589
7590 /* eat the whole request */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007591 if (co_data(req))
7592 co_skip(req, co_data(req));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007593 }
7594
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007595 out:
7596 return;
7597
7598 error:
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007599
7600 /* If we are in HTTP mode, and we are not send any
7601 * data, return a 500 server error in best effort:
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007602 * if there is no room available in the buffer,
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007603 * just close the connection.
7604 */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007605 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
7606 channel_erase(res);
7607 ci_putblk(res, error_500, strlen(error_500));
7608 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007609 if (!(strm->flags & SF_ERR_MASK))
7610 strm->flags |= SF_ERR_RESOURCE;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007611 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007612 goto done;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007613}
7614
7615static void hlua_applet_http_release(struct appctx *ctx)
7616{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007617 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007618 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007619 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007620 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007621}
7622
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007623/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
7624 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007625 *
7626 * This function can fail with an abort() due to an Lua critical error.
7627 * We are in the configuration parsing process of HAProxy, this abort() is
7628 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007629 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007630static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
7631 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007632{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007633 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007634 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007635
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007636 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007637 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007638 if (!rule->arg.hlua_rule) {
7639 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007640 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007641 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007642
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007643 /* Memory for arguments. */
7644 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
7645 if (!rule->arg.hlua_rule->args) {
7646 memprintf(err, "out of memory error");
7647 return ACT_RET_PRS_ERR;
7648 }
7649
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007650 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007651 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007652
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007653 /* Expect some arguments */
7654 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007655 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007656 memprintf(err, "expect %d arguments", fcn->nargs);
7657 return ACT_RET_PRS_ERR;
7658 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007659 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007660 if (!rule->arg.hlua_rule->args[i]) {
7661 memprintf(err, "out of memory error");
7662 return ACT_RET_PRS_ERR;
7663 }
7664 (*cur_arg)++;
7665 }
7666 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007667
Thierry FOURNIER42148732015-09-02 17:17:33 +02007668 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007669 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007670 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007671}
7672
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007673static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
7674 struct act_rule *rule, char **err)
7675{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007676 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007677
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007678 /* HTTP applets are forbidden in tcp-request rules.
7679 * HTTP applet request requires everything initilized by
7680 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
7681 * The applet will be immediately initilized, but its before
7682 * the call of this analyzer.
7683 */
7684 if (rule->from != ACT_F_HTTP_REQ) {
7685 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
7686 return ACT_RET_PRS_ERR;
7687 }
7688
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007689 /* Memory for the rule. */
7690 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7691 if (!rule->arg.hlua_rule) {
7692 memprintf(err, "out of memory error");
7693 return ACT_RET_PRS_ERR;
7694 }
7695
7696 /* Reference the Lua function and store the reference. */
7697 rule->arg.hlua_rule->fcn = *fcn;
7698
7699 /* TODO: later accept arguments. */
7700 rule->arg.hlua_rule->args = NULL;
7701
7702 /* Add applet pointer in the rule. */
7703 rule->applet.obj_type = OBJ_TYPE_APPLET;
7704 rule->applet.name = fcn->name;
7705 rule->applet.init = hlua_applet_http_init;
7706 rule->applet.fct = hlua_applet_http_fct;
7707 rule->applet.release = hlua_applet_http_release;
7708 rule->applet.timeout = hlua_timeout_applet;
7709
7710 return ACT_RET_PRS_OK;
7711}
7712
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007713/* This function is an LUA binding used for registering
7714 * "sample-conv" functions. It expects a converter name used
7715 * in the haproxy configuration file, and an LUA function.
7716 */
7717__LJMP static int hlua_register_action(lua_State *L)
7718{
7719 struct action_kw_list *akl;
7720 const char *name;
7721 int ref;
7722 int len;
7723 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007724 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007725
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007726 /* Initialise the number of expected arguments at 0. */
7727 nargs = 0;
7728
7729 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7730 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007731
7732 /* First argument : converter name. */
7733 name = MAY_LJMP(luaL_checkstring(L, 1));
7734
7735 /* Second argument : environment. */
7736 if (lua_type(L, 2) != LUA_TTABLE)
7737 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7738
7739 /* Third argument : lua function. */
7740 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7741
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007742 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007743 if (lua_gettop(L) >= 4)
7744 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
7745
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007746 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007747 lua_pushnil(L);
7748 while (lua_next(L, 2) != 0) {
7749 if (lua_type(L, -1) != LUA_TSTRING)
7750 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7751
7752 /* Check required environment. Only accepted "http" or "tcp". */
7753 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007754 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007755 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007756 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007757 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007758 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007759 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007760
7761 /* Fill fcn. */
7762 fcn->name = strdup(name);
7763 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007764 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007765 fcn->function_ref = ref;
7766
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007767 /* Set the expected number od arguments. */
7768 fcn->nargs = nargs;
7769
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007770 /* List head */
7771 akl->list.n = akl->list.p = NULL;
7772
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007773 /* action keyword. */
7774 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007775 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007776 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007777 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007778
7779 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7780
7781 akl->kw[0].match_pfx = 0;
7782 akl->kw[0].private = fcn;
7783 akl->kw[0].parse = action_register_lua;
7784
7785 /* select the action registering point. */
7786 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
7787 tcp_req_cont_keywords_register(akl);
7788 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
7789 tcp_res_cont_keywords_register(akl);
7790 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
7791 http_req_keywords_register(akl);
7792 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
7793 http_res_keywords_register(akl);
7794 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007795 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007796 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
7797 "are expected.", lua_tostring(L, -1)));
7798
7799 /* pop the environment string. */
7800 lua_pop(L, 1);
7801 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007802 return ACT_RET_PRS_OK;
7803}
7804
7805static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7806 struct act_rule *rule, char **err)
7807{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007808 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007809
Christopher Fauleteb709802019-04-11 22:04:08 +02007810 if (px->mode == PR_MODE_HTTP && (px->options2 & PR_O2_USE_HTX)) {
Christopher Fauletafd8f102018-11-08 11:34:21 +01007811 memprintf(err, "Lua services cannot be used when the HTX internal representation is enabled");
7812 return ACT_RET_PRS_ERR;
7813 }
7814
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007815 /* Memory for the rule. */
7816 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7817 if (!rule->arg.hlua_rule) {
7818 memprintf(err, "out of memory error");
7819 return ACT_RET_PRS_ERR;
7820 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007821
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007822 /* Reference the Lua function and store the reference. */
7823 rule->arg.hlua_rule->fcn = *fcn;
7824
7825 /* TODO: later accept arguments. */
7826 rule->arg.hlua_rule->args = NULL;
7827
7828 /* Add applet pointer in the rule. */
7829 rule->applet.obj_type = OBJ_TYPE_APPLET;
7830 rule->applet.name = fcn->name;
7831 rule->applet.init = hlua_applet_tcp_init;
7832 rule->applet.fct = hlua_applet_tcp_fct;
7833 rule->applet.release = hlua_applet_tcp_release;
7834 rule->applet.timeout = hlua_timeout_applet;
7835
7836 return 0;
7837}
7838
7839/* This function is an LUA binding used for registering
7840 * "sample-conv" functions. It expects a converter name used
7841 * in the haproxy configuration file, and an LUA function.
7842 */
7843__LJMP static int hlua_register_service(lua_State *L)
7844{
7845 struct action_kw_list *akl;
7846 const char *name;
7847 const char *env;
7848 int ref;
7849 int len;
7850 struct hlua_function *fcn;
7851
7852 MAY_LJMP(check_args(L, 3, "register_service"));
7853
7854 /* First argument : converter name. */
7855 name = MAY_LJMP(luaL_checkstring(L, 1));
7856
7857 /* Second argument : environment. */
7858 env = MAY_LJMP(luaL_checkstring(L, 2));
7859
7860 /* Third argument : lua function. */
7861 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7862
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007863 /* Allocate and fill the sample fetch keyword struct. */
7864 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7865 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007866 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007867 fcn = calloc(1, sizeof(*fcn));
7868 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007869 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007870
7871 /* Fill fcn. */
7872 len = strlen("<lua.>") + strlen(name) + 1;
7873 fcn->name = calloc(1, len);
7874 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007875 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007876 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7877 fcn->function_ref = ref;
7878
7879 /* List head */
7880 akl->list.n = akl->list.p = NULL;
7881
7882 /* converter keyword. */
7883 len = strlen("lua.") + strlen(name) + 1;
7884 akl->kw[0].kw = calloc(1, len);
7885 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007886 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007887
7888 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7889
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007890 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007891 if (strcmp(env, "tcp") == 0)
7892 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007893 else if (strcmp(env, "http") == 0)
7894 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007895 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007896 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007897 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007898
7899 akl->kw[0].match_pfx = 0;
7900 akl->kw[0].private = fcn;
7901
7902 /* End of array. */
7903 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7904
7905 /* Register this new converter */
7906 service_keywords_register(akl);
7907
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007908 return 0;
7909}
7910
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007911/* This function initialises Lua cli handler. It copies the
7912 * arguments in the Lua stack and create channel IO objects.
7913 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007914static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007915{
7916 struct hlua *hlua;
7917 struct hlua_function *fcn;
7918 int i;
7919 const char *error;
7920
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007921 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007922 appctx->ctx.hlua_cli.fcn = private;
7923
Willy Tarreaubafbe012017-11-24 17:34:44 +01007924 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007925 if (!hlua) {
7926 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007927 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007928 }
7929 HLUA_INIT(hlua);
7930 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007931
7932 /* Create task used by signal to wakeup applets.
7933 * We use the same wakeup fonction than the Lua applet_tcp and
7934 * applet_http. It is absolutely compatible.
7935 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007936 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007937 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007938 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007939 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007940 }
7941 appctx->ctx.hlua_cli.task->nice = 0;
7942 appctx->ctx.hlua_cli.task->context = appctx;
7943 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7944
7945 /* Initialises the Lua context */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007946 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007947 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007948 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007949 }
7950
7951 /* The following Lua calls can fail. */
7952 if (!SET_SAFE_LJMP(hlua->T)) {
7953 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7954 error = lua_tostring(hlua->T, -1);
7955 else
7956 error = "critical error";
7957 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7958 goto error;
7959 }
7960
7961 /* Check stack available size. */
7962 if (!lua_checkstack(hlua->T, 2)) {
7963 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7964 goto error;
7965 }
7966
7967 /* Restore the function in the stack. */
7968 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7969
7970 /* Once the arguments parsed, the CLI is like an AppletTCP,
7971 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007972 */
7973 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7974 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7975 goto error;
7976 }
7977 hlua->nargs = 1;
7978
7979 /* push keywords in the stack. */
7980 for (i = 0; *args[i]; i++) {
7981 /* Check stack available size. */
7982 if (!lua_checkstack(hlua->T, 1)) {
7983 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7984 goto error;
7985 }
7986 lua_pushstring(hlua->T, args[i]);
7987 hlua->nargs++;
7988 }
7989
7990 /* We must initialize the execution timeouts. */
7991 hlua->max_time = hlua_timeout_session;
7992
7993 /* At this point the execution is safe. */
7994 RESET_SAFE_LJMP(hlua->T);
7995
7996 /* It's ok */
7997 return 0;
7998
7999 /* It's not ok. */
8000error:
8001 RESET_SAFE_LJMP(hlua->T);
8002 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01008003 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008004 return 1;
8005}
8006
8007static int hlua_cli_io_handler_fct(struct appctx *appctx)
8008{
8009 struct hlua *hlua;
8010 struct stream_interface *si;
8011 struct hlua_function *fcn;
8012
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008013 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008014 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01008015 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008016
8017 /* If the stream is disconnect or closed, ldo nothing. */
8018 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8019 return 1;
8020
8021 /* Execute the function. */
8022 switch (hlua_ctx_resume(hlua, 1)) {
8023
8024 /* finished. */
8025 case HLUA_E_OK:
8026 return 1;
8027
8028 /* yield. */
8029 case HLUA_E_AGAIN:
8030 /* We want write. */
8031 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01008032 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008033 /* Set the timeout. */
8034 if (hlua->wake_time != TICK_ETERNITY)
8035 task_schedule(hlua->task, hlua->wake_time);
8036 return 0;
8037
8038 /* finished with error. */
8039 case HLUA_E_ERRMSG:
8040 /* Display log. */
8041 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
8042 fcn->name, lua_tostring(hlua->T, -1));
8043 lua_pop(hlua->T, 1);
8044 return 1;
8045
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008046 case HLUA_E_ETMOUT:
8047 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
8048 fcn->name);
8049 return 1;
8050
8051 case HLUA_E_NOMEM:
8052 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
8053 fcn->name);
8054 return 1;
8055
8056 case HLUA_E_YIELD: /* unexpected */
8057 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
8058 fcn->name);
8059 return 1;
8060
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008061 case HLUA_E_ERR:
8062 /* Display log. */
8063 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
8064 fcn->name);
8065 return 1;
8066
8067 default:
8068 return 1;
8069 }
8070
8071 return 1;
8072}
8073
8074static void hlua_cli_io_release_fct(struct appctx *appctx)
8075{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008076 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008077 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008078}
8079
8080/* This function is an LUA binding used for registering
8081 * new keywords in the cli. It expects a list of keywords
8082 * which are the "path". It is limited to 5 keywords. A
8083 * description of the command, a function to be executed
8084 * for the parsing and a function for io handlers.
8085 */
8086__LJMP static int hlua_register_cli(lua_State *L)
8087{
8088 struct cli_kw_list *cli_kws;
8089 const char *message;
8090 int ref_io;
8091 int len;
8092 struct hlua_function *fcn;
8093 int index;
8094 int i;
8095
8096 MAY_LJMP(check_args(L, 3, "register_cli"));
8097
8098 /* First argument : an array of maximum 5 keywords. */
8099 if (!lua_istable(L, 1))
8100 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
8101
8102 /* Second argument : string with contextual message. */
8103 message = MAY_LJMP(luaL_checkstring(L, 2));
8104
8105 /* Third and fourth argument : lua function. */
8106 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
8107
8108 /* Allocate and fill the sample fetch keyword struct. */
8109 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
8110 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008111 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008112 fcn = calloc(1, sizeof(*fcn));
8113 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008114 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008115
8116 /* Fill path. */
8117 index = 0;
8118 lua_pushnil(L);
8119 while(lua_next(L, 1) != 0) {
8120 if (index >= 5)
8121 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
8122 if (lua_type(L, -1) != LUA_TSTRING)
8123 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
8124 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
8125 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008126 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008127 index++;
8128 lua_pop(L, 1);
8129 }
8130
8131 /* Copy help message. */
8132 cli_kws->kw[0].usage = strdup(message);
8133 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008134 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008135
8136 /* Fill fcn io handler. */
8137 len = strlen("<lua.cli>") + 1;
8138 for (i = 0; i < index; i++)
8139 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
8140 fcn->name = calloc(1, len);
8141 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008142 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008143 strncat((char *)fcn->name, "<lua.cli", len);
8144 for (i = 0; i < index; i++) {
8145 strncat((char *)fcn->name, ".", len);
8146 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
8147 }
8148 strncat((char *)fcn->name, ">", len);
8149 fcn->function_ref = ref_io;
8150
8151 /* Fill last entries. */
8152 cli_kws->kw[0].private = fcn;
8153 cli_kws->kw[0].parse = hlua_cli_parse_fct;
8154 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
8155 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
8156
8157 /* Register this new converter */
8158 cli_register_kw(cli_kws);
8159
8160 return 0;
8161}
8162
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008163static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
8164 struct proxy *defpx, const char *file, int line,
8165 char **err, unsigned int *timeout)
8166{
8167 const char *error;
8168
8169 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +02008170 if (error == PARSE_TIME_OVER) {
8171 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
8172 args[1], args[0]);
8173 return -1;
8174 }
8175 else if (error == PARSE_TIME_UNDER) {
8176 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
8177 args[1], args[0]);
8178 return -1;
8179 }
8180 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008181 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;
Christopher Faulet20699902020-07-28 10:33:25 +02008288#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008289 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008290 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008291 lua_pop(gL.T, 1);
8292 return -1;
Christopher Faulet20699902020-07-28 10:33:25 +02008293#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008294 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008295 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008296 lua_pop(gL.T, 1);
8297 return -1;
8298 }
8299
8300 return 0;
8301}
8302
8303/* configuration keywords declaration */
8304static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008305 { CFG_GLOBAL, "lua-load", hlua_load },
8306 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
8307 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02008308 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008309 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01008310 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008311 { 0, NULL, NULL },
8312}};
8313
Willy Tarreau0108d902018-11-25 19:14:37 +01008314INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
8315
Christopher Fauletafd8f102018-11-08 11:34:21 +01008316
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008317/* This function can fail with an abort() due to an Lua critical error.
8318 * We are in the initialisation process of HAProxy, this abort() is
8319 * tolerated.
8320 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008321int hlua_post_init()
8322{
8323 struct hlua_init_function *init;
8324 const char *msg;
8325 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008326 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008327
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008328 /* Call post initialisation function in safe environement. */
8329 if (!SET_SAFE_LJMP(gL.T)) {
8330 if (lua_type(gL.T, -1) == LUA_TSTRING)
8331 error = lua_tostring(gL.T, -1);
8332 else
8333 error = "critical error";
8334 fprintf(stderr, "Lua post-init: %s.\n", error);
8335 exit(1);
8336 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02008337
8338#if USE_OPENSSL
8339 /* Initialize SSL server. */
8340 if (socket_ssl.xprt->prepare_srv) {
8341 int saved_used_backed = global.ssl_used_backend;
8342 // don't affect maxconn automatic computation
8343 socket_ssl.xprt->prepare_srv(&socket_ssl);
8344 global.ssl_used_backend = saved_used_backed;
8345 }
8346#endif
8347
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008348 hlua_fcn_post_init(gL.T);
8349 RESET_SAFE_LJMP(gL.T);
8350
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008351 list_for_each_entry(init, &hlua_init_functions, l) {
8352 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
8353 ret = hlua_ctx_resume(&gL, 0);
8354 switch (ret) {
8355 case HLUA_E_OK:
8356 lua_pop(gL.T, -1);
8357 return 1;
8358 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008359 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008360 return 0;
8361 case HLUA_E_ERRMSG:
8362 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01008363 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008364 return 0;
8365 case HLUA_E_ERR:
8366 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008367 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008368 return 0;
8369 }
8370 }
8371 return 1;
8372}
8373
Willy Tarreau32f61e22015-03-18 17:54:59 +01008374/* The memory allocator used by the Lua stack. <ud> is a pointer to the
8375 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
8376 * is the previously allocated size or the kind of object in case of a new
8377 * allocation. <nsize> is the requested new size.
8378 */
8379static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
8380{
8381 struct hlua_mem_allocator *zone = ud;
8382
8383 if (nsize == 0) {
8384 /* it's a free */
8385 if (ptr)
8386 zone->allocated -= osize;
8387 free(ptr);
8388 return NULL;
8389 }
8390
8391 if (!ptr) {
8392 /* it's a new allocation */
8393 if (zone->limit && zone->allocated + nsize > zone->limit)
8394 return NULL;
8395
8396 ptr = malloc(nsize);
8397 if (ptr)
8398 zone->allocated += nsize;
8399 return ptr;
8400 }
8401
8402 /* it's a realloc */
8403 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
8404 return NULL;
8405
8406 ptr = realloc(ptr, nsize);
8407 if (ptr)
8408 zone->allocated += nsize - osize;
8409 return ptr;
8410}
8411
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008412/* Ithis function can fail with an abort() due to an Lua critical error.
8413 * We are in the initialisation process of HAProxy, this abort() is
8414 * tolerated.
8415 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008416void hlua_init(void)
8417{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008418 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008419 int idx;
8420 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008421 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008422 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008423 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008424#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008425 struct srv_kw *kw;
8426 int tmp_error;
8427 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008428 char *args[] = { /* SSL client configuration. */
8429 "ssl",
8430 "verify",
8431 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008432 NULL
8433 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008434#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008435
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008436 /* Init main lua stack. */
8437 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01008438 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01008439 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02008440 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008441 hlua_sethlua(&gL);
8442 gL.Tref = LUA_REFNIL;
8443 gL.task = NULL;
8444
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008445 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008446 * the Lua function can fail with an abort. We are in the initialisation
8447 * process of HAProxy, this abort() is tolerated.
8448 */
8449
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008450 /* Initialise lua. */
8451 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008452
Thierry Fournier75933d42016-01-21 09:30:18 +01008453 /* Set safe environment for the initialisation. */
8454 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008455 if (lua_type(gL.T, -1) == LUA_TSTRING)
8456 error_msg = lua_tostring(gL.T, -1);
8457 else
8458 error_msg = "critical error";
8459 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01008460 exit(1);
8461 }
8462
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008463 /*
8464 *
8465 * Create "core" object.
8466 *
8467 */
8468
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01008469 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008470 lua_newtable(gL.T);
8471
8472 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008473 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008474 hlua_class_const_int(gL.T, log_levels[i], i);
8475
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008476 /* Register special functions. */
8477 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008478 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008479 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008480 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008481 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008482 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008483 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008484 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01008485 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008486 hlua_class_function(gL.T, "sleep", hlua_sleep);
8487 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01008488 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
8489 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
8490 hlua_class_function(gL.T, "set_map", hlua_set_map);
8491 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008492 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008493 hlua_class_function(gL.T, "log", hlua_log);
8494 hlua_class_function(gL.T, "Debug", hlua_log_debug);
8495 hlua_class_function(gL.T, "Info", hlua_log_info);
8496 hlua_class_function(gL.T, "Warning", hlua_log_warning);
8497 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02008498 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01008499 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008500
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008501 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008502
8503 /*
8504 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008505 * Register class Map
8506 *
8507 */
8508
8509 /* This table entry is the object "Map" base. */
8510 lua_newtable(gL.T);
8511
8512 /* register pattern types. */
8513 for (i=0; i<PAT_MATCH_NUM; i++)
8514 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008515 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008516 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
8517 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008518 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008519
8520 /* register constructor. */
8521 hlua_class_function(gL.T, "new", hlua_map_new);
8522
8523 /* Create and fill the metatable. */
8524 lua_newtable(gL.T);
8525
8526 /* Create and fille the __index entry. */
8527 lua_pushstring(gL.T, "__index");
8528 lua_newtable(gL.T);
8529
8530 /* Register . */
8531 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
8532 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
8533
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008534 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008535
Thierry Fournier45e78d72016-02-19 18:34:46 +01008536 /* Register previous table in the registry with reference and named entry.
8537 * The function hlua_register_metatable() pops the stack, so we
8538 * previously create a copy of the table.
8539 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008540 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008541 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008542
8543 /* Assign the metatable to the mai Map object. */
8544 lua_setmetatable(gL.T, -2);
8545
8546 /* Set a name to the table. */
8547 lua_setglobal(gL.T, "Map");
8548
8549 /*
8550 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008551 * Register class Channel
8552 *
8553 */
8554
8555 /* Create and fill the metatable. */
8556 lua_newtable(gL.T);
8557
8558 /* Create and fille the __index entry. */
8559 lua_pushstring(gL.T, "__index");
8560 lua_newtable(gL.T);
8561
8562 /* Register . */
8563 hlua_class_function(gL.T, "get", hlua_channel_get);
8564 hlua_class_function(gL.T, "dup", hlua_channel_dup);
8565 hlua_class_function(gL.T, "getline", hlua_channel_getline);
8566 hlua_class_function(gL.T, "set", hlua_channel_set);
8567 hlua_class_function(gL.T, "append", hlua_channel_append);
8568 hlua_class_function(gL.T, "send", hlua_channel_send);
8569 hlua_class_function(gL.T, "forward", hlua_channel_forward);
8570 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
8571 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01008572 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008573
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008574 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008575
8576 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008577 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008578
8579 /*
8580 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008581 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008582 *
8583 */
8584
8585 /* Create and fill the metatable. */
8586 lua_newtable(gL.T);
8587
8588 /* Create and fille the __index entry. */
8589 lua_pushstring(gL.T, "__index");
8590 lua_newtable(gL.T);
8591
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008592 /* Browse existing fetches and create the associated
8593 * object method.
8594 */
8595 sf = NULL;
8596 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
8597
8598 /* Dont register the keywork if the arguments check function are
8599 * not safe during the runtime.
8600 */
8601 if ((sf->val_args != NULL) &&
8602 (sf->val_args != val_payload_lv) &&
8603 (sf->val_args != val_hdr))
8604 continue;
8605
8606 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8607 * by an underscore.
8608 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008609 strncpy(trash.area, sf->kw, trash.size);
8610 trash.area[trash.size - 1] = '\0';
8611 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008612 if (*p == '.' || *p == '-' || *p == '+')
8613 *p = '_';
8614
8615 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008616 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01008617 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008618 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008619 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008620 }
8621
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008622 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008623
8624 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008625 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008626
8627 /*
8628 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008629 * Register class Converters
8630 *
8631 */
8632
8633 /* Create and fill the metatable. */
8634 lua_newtable(gL.T);
8635
8636 /* Create and fill the __index entry. */
8637 lua_pushstring(gL.T, "__index");
8638 lua_newtable(gL.T);
8639
8640 /* Browse existing converters and create the associated
8641 * object method.
8642 */
8643 sc = NULL;
8644 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
8645 /* Dont register the keywork if the arguments check function are
8646 * not safe during the runtime.
8647 */
8648 if (sc->val_args != NULL)
8649 continue;
8650
8651 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8652 * by an underscore.
8653 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008654 strncpy(trash.area, sc->kw, trash.size);
8655 trash.area[trash.size - 1] = '\0';
8656 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008657 if (*p == '.' || *p == '-' || *p == '+')
8658 *p = '_';
8659
8660 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008661 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008662 lua_pushlightuserdata(gL.T, sc);
8663 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008664 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008665 }
8666
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008667 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008668
8669 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008670 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008671
8672 /*
8673 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008674 * Register class HTTP
8675 *
8676 */
8677
8678 /* Create and fill the metatable. */
8679 lua_newtable(gL.T);
8680
8681 /* Create and fille the __index entry. */
8682 lua_pushstring(gL.T, "__index");
8683 lua_newtable(gL.T);
8684
8685 /* Register Lua functions. */
8686 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
8687 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
8688 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
8689 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
8690 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
8691 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
8692 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
8693 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
8694 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
8695 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
8696
8697 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
8698 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
8699 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
8700 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
8701 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
8702 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02008703 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008704
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008705 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008706
8707 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008708 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008709
8710 /*
8711 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008712 * Register class AppletTCP
8713 *
8714 */
8715
8716 /* Create and fill the metatable. */
8717 lua_newtable(gL.T);
8718
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008719 /* Create and fille the __index entry. */
8720 lua_pushstring(gL.T, "__index");
8721 lua_newtable(gL.T);
8722
8723 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01008724 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
8725 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
8726 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
8727 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
8728 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008729 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
8730 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
8731 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008732
8733 lua_settable(gL.T, -3);
8734
8735 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008736 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008737
8738 /*
8739 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008740 * Register class AppletHTTP
8741 *
8742 */
8743
8744 /* Create and fill the metatable. */
8745 lua_newtable(gL.T);
8746
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008747 /* Create and fille the __index entry. */
8748 lua_pushstring(gL.T, "__index");
8749 lua_newtable(gL.T);
8750
8751 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01008752 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
8753 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008754 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
8755 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
8756 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008757 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
8758 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
8759 hlua_class_function(gL.T, "send", hlua_applet_http_send);
8760 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
8761 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
8762 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
8763
8764 lua_settable(gL.T, -3);
8765
8766 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008767 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008768
8769 /*
8770 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008771 * Register class TXN
8772 *
8773 */
8774
8775 /* Create and fill the metatable. */
8776 lua_newtable(gL.T);
8777
8778 /* Create and fille the __index entry. */
8779 lua_pushstring(gL.T, "__index");
8780 lua_newtable(gL.T);
8781
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008782 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04008783 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
8784 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
8785 hlua_class_function(gL.T, "set_var", hlua_set_var);
8786 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
8787 hlua_class_function(gL.T, "get_var", hlua_get_var);
8788 hlua_class_function(gL.T, "done", hlua_txn_done);
8789 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
8790 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
8791 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
8792 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
8793 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
8794 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
8795 hlua_class_function(gL.T, "log", hlua_txn_log);
8796 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
8797 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
8798 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
8799 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008800
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008801 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008802
8803 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008804 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008805
8806 /*
8807 *
8808 * Register class Socket
8809 *
8810 */
8811
8812 /* Create and fill the metatable. */
8813 lua_newtable(gL.T);
8814
8815 /* Create and fille the __index entry. */
8816 lua_pushstring(gL.T, "__index");
8817 lua_newtable(gL.T);
8818
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008819#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008820 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008821#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008822 hlua_class_function(gL.T, "connect", hlua_socket_connect);
8823 hlua_class_function(gL.T, "send", hlua_socket_send);
8824 hlua_class_function(gL.T, "receive", hlua_socket_receive);
8825 hlua_class_function(gL.T, "close", hlua_socket_close);
8826 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
8827 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8828 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8829 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8830
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008831 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008832
8833 /* Register the garbage collector entry. */
8834 lua_pushstring(gL.T, "__gc");
8835 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008836 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008837
8838 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008839 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008840
8841 /* Proxy and server configuration initialisation. */
8842 memset(&socket_proxy, 0, sizeof(socket_proxy));
8843 init_new_proxy(&socket_proxy);
8844 socket_proxy.parent = NULL;
8845 socket_proxy.last_change = now.tv_sec;
8846 socket_proxy.id = "LUA-SOCKET";
8847 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8848 socket_proxy.maxconn = 0;
8849 socket_proxy.accept = NULL;
8850 socket_proxy.options2 |= PR_O2_INDEPSTR;
8851 socket_proxy.srv = NULL;
8852 socket_proxy.conn_retries = 0;
8853 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8854
8855 /* Init TCP server: unchanged parameters */
8856 memset(&socket_tcp, 0, sizeof(socket_tcp));
8857 socket_tcp.next = NULL;
8858 socket_tcp.proxy = &socket_proxy;
8859 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8860 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008861 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008862 socket_tcp.priv_conns = NULL;
8863 socket_tcp.idle_conns = NULL;
8864 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008865 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008866 socket_tcp.last_change = 0;
8867 socket_tcp.id = "LUA-TCP-CONN";
8868 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8869 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8870 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
8871
8872 /* XXX: Copy default parameter from default server,
8873 * but the default server is not initialized.
8874 */
8875 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
8876 socket_tcp.minconn = socket_proxy.defsrv.minconn;
8877 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
8878 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
8879 socket_tcp.onerror = socket_proxy.defsrv.onerror;
8880 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8881 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
8882 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8883 socket_tcp.uweight = socket_proxy.defsrv.iweight;
8884 socket_tcp.iweight = socket_proxy.defsrv.iweight;
8885
8886 socket_tcp.check.status = HCHK_STATUS_INI;
8887 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
8888 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
8889 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
8890 socket_tcp.check.server = &socket_tcp;
8891
8892 socket_tcp.agent.status = HCHK_STATUS_INI;
8893 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
8894 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
8895 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
8896 socket_tcp.agent.server = &socket_tcp;
8897
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008898 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008899
8900#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008901 /* Init TCP server: unchanged parameters */
8902 memset(&socket_ssl, 0, sizeof(socket_ssl));
8903 socket_ssl.next = NULL;
8904 socket_ssl.proxy = &socket_proxy;
8905 socket_ssl.obj_type = OBJ_TYPE_SERVER;
8906 LIST_INIT(&socket_ssl.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008907 socket_ssl.pendconns = EB_ROOT;
Willy Tarreaub784b352019-02-07 14:48:24 +01008908 socket_ssl.priv_conns = NULL;
8909 socket_ssl.idle_conns = NULL;
8910 socket_ssl.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008911 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008912 socket_ssl.last_change = 0;
8913 socket_ssl.id = "LUA-SSL-CONN";
8914 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8915 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8916 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8917
8918 /* XXX: Copy default parameter from default server,
8919 * but the default server is not initialized.
8920 */
8921 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8922 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8923 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8924 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8925 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8926 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8927 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8928 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8929 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8930 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8931
8932 socket_ssl.check.status = HCHK_STATUS_INI;
8933 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8934 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8935 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8936 socket_ssl.check.server = &socket_ssl;
8937
8938 socket_ssl.agent.status = HCHK_STATUS_INI;
8939 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8940 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8941 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8942 socket_ssl.agent.server = &socket_ssl;
8943
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008944 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008945 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008946
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008947 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008948 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8949 /*
8950 *
8951 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008952 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008953 * features like client certificates and ssl_verify.
8954 *
8955 */
8956 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8957 if (tmp_error != 0) {
8958 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8959 abort(); /* This must be never arrives because the command line
8960 not editable by the user. */
8961 }
8962 idx += kw->skip;
8963 }
8964 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008965#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008966
8967 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008968}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008969
Willy Tarreau80713382018-11-26 10:19:54 +01008970static void hlua_register_build_options(void)
8971{
Willy Tarreaubb57d942016-12-21 19:04:56 +01008972 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +01008973
Willy Tarreaubb57d942016-12-21 19:04:56 +01008974 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8975 hap_register_build_opts(ptr, 1);
8976}
Willy Tarreau80713382018-11-26 10:19:54 +01008977
8978INITCALL0(STG_REGISTER, hlua_register_build_options);