blob: cb5feb514e0a9ccfeaa49e01dd8ed8979cdd372b [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{
1083 int ret;
1084 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001085 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001086
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001087 /* Initialise run time counter. */
1088 if (!HLUA_IS_RUNNING(lua))
1089 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001090
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001091 /* Lock the whole Lua execution. This lock must be before the
1092 * label "resume_execution".
1093 */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001094 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001095
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001096resume_execution:
1097
1098 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1099 * instructions. it is used for preventing infinite loops.
1100 */
1101 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1102
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001103 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001104 HLUA_SET_RUN(lua);
1105 HLUA_CLR_CTRLYIELD(lua);
1106 HLUA_CLR_WAKERESWR(lua);
1107 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001108
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001109 /* Update the start time. */
1110 lua->start_time = now_ms;
1111
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001112 /* Call the function. */
1113 ret = lua_resume(lua->T, gL.T, lua->nargs);
1114 switch (ret) {
1115
1116 case LUA_OK:
1117 ret = HLUA_E_OK;
1118 break;
1119
1120 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001121 /* Check if the execution timeout is expired. It it is the case, we
1122 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001123 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001124 tv_update_date(0, 1);
1125 lua->run_time += now_ms - lua->start_time;
1126 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001127 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001128 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001129 break;
1130 }
1131 /* Process the forced yield. if the general yield is not allowed or
1132 * if no task were associated this the current Lua execution
1133 * coroutine, we resume the execution. Else we want to return in the
1134 * scheduler and we want to be waked up again, to continue the
1135 * current Lua execution. So we schedule our own task.
1136 */
1137 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001138 if (!yield_allowed || !lua->task)
1139 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001140 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001141 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001142 if (!yield_allowed) {
1143 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001144 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001145 break;
1146 }
1147 ret = HLUA_E_AGAIN;
1148 break;
1149
1150 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001151
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001152 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001153 * because the errors ares the only one mean to return immediately
1154 * from and lua execution.
1155 */
1156 if (lua->flags & HLUA_EXIT) {
1157 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001158 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001159 break;
1160 }
1161
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001162 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001163 if (!lua_checkstack(lua->T, 1)) {
1164 ret = HLUA_E_ERR;
1165 break;
1166 }
1167 msg = lua_tostring(lua->T, -1);
1168 lua_settop(lua->T, 0); /* Empty the stack. */
1169 lua_pop(lua->T, 1);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001170 trace = hlua_traceback(lua->T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001171 if (msg)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001172 lua_pushfstring(lua->T, "runtime error: %s from %s", msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001173 else
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001174 lua_pushfstring(lua->T, "unknown runtime error from %s", trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001175 ret = HLUA_E_ERRMSG;
1176 break;
1177
1178 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001179 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001180 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001181 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001182 break;
1183
1184 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001185 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001186 if (!lua_checkstack(lua->T, 1)) {
1187 ret = HLUA_E_ERR;
1188 break;
1189 }
1190 msg = lua_tostring(lua->T, -1);
1191 lua_settop(lua->T, 0); /* Empty the stack. */
1192 lua_pop(lua->T, 1);
1193 if (msg)
1194 lua_pushfstring(lua->T, "message handler error: %s", msg);
1195 else
1196 lua_pushfstring(lua->T, "message handler error");
1197 ret = HLUA_E_ERRMSG;
1198 break;
1199
1200 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001201 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001202 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001203 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001204 break;
1205 }
1206
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001207 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001208 if (lua->flags & HLUA_MUST_GC &&
1209 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001210 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1211
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001212 switch (ret) {
1213 case HLUA_E_AGAIN:
1214 break;
1215
1216 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001217 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001218 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001219 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001220 break;
1221
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001222 case HLUA_E_ETMOUT:
1223 case HLUA_E_NOMEM:
1224 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001225 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001226 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001227 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001228 hlua_ctx_renew(lua, 0);
1229 break;
1230
1231 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001232 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001233 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001234 break;
1235 }
1236
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001237 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001238 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001239
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001240 return ret;
1241}
1242
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001243/* This function exit the current code. */
1244__LJMP static int hlua_done(lua_State *L)
1245{
1246 struct hlua *hlua = hlua_gethlua(L);
1247
1248 hlua->flags |= HLUA_EXIT;
1249 WILL_LJMP(lua_error(L));
1250
1251 return 0;
1252}
1253
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001254/* This function is an LUA binding. It provides a function
1255 * for deleting ACL from a referenced ACL file.
1256 */
1257__LJMP static int hlua_del_acl(lua_State *L)
1258{
1259 const char *name;
1260 const char *key;
1261 struct pat_ref *ref;
1262
1263 MAY_LJMP(check_args(L, 2, "del_acl"));
1264
1265 name = MAY_LJMP(luaL_checkstring(L, 1));
1266 key = MAY_LJMP(luaL_checkstring(L, 2));
1267
1268 ref = pat_ref_lookup(name);
1269 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001270 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001271
1272 pat_ref_delete(ref, key);
1273 return 0;
1274}
1275
1276/* This function is an LUA binding. It provides a function
1277 * for deleting map entry from a referenced map file.
1278 */
1279static int hlua_del_map(lua_State *L)
1280{
1281 const char *name;
1282 const char *key;
1283 struct pat_ref *ref;
1284
1285 MAY_LJMP(check_args(L, 2, "del_map"));
1286
1287 name = MAY_LJMP(luaL_checkstring(L, 1));
1288 key = MAY_LJMP(luaL_checkstring(L, 2));
1289
1290 ref = pat_ref_lookup(name);
1291 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001292 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001293
1294 pat_ref_delete(ref, key);
1295 return 0;
1296}
1297
1298/* This function is an LUA binding. It provides a function
1299 * for adding ACL pattern from a referenced ACL file.
1300 */
1301static int hlua_add_acl(lua_State *L)
1302{
1303 const char *name;
1304 const char *key;
1305 struct pat_ref *ref;
1306
1307 MAY_LJMP(check_args(L, 2, "add_acl"));
1308
1309 name = MAY_LJMP(luaL_checkstring(L, 1));
1310 key = MAY_LJMP(luaL_checkstring(L, 2));
1311
1312 ref = pat_ref_lookup(name);
1313 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001314 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001315
1316 if (pat_ref_find_elt(ref, key) == NULL)
1317 pat_ref_add(ref, key, NULL, NULL);
1318 return 0;
1319}
1320
1321/* This function is an LUA binding. It provides a function
1322 * for setting map pattern and sample from a referenced map
1323 * file.
1324 */
1325static int hlua_set_map(lua_State *L)
1326{
1327 const char *name;
1328 const char *key;
1329 const char *value;
1330 struct pat_ref *ref;
1331
1332 MAY_LJMP(check_args(L, 3, "set_map"));
1333
1334 name = MAY_LJMP(luaL_checkstring(L, 1));
1335 key = MAY_LJMP(luaL_checkstring(L, 2));
1336 value = MAY_LJMP(luaL_checkstring(L, 3));
1337
1338 ref = pat_ref_lookup(name);
1339 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001340 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001341
1342 if (pat_ref_find_elt(ref, key) != NULL)
1343 pat_ref_set(ref, key, value, NULL);
1344 else
1345 pat_ref_add(ref, key, value, NULL);
1346 return 0;
1347}
1348
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001349/* A class is a lot of memory that contain data. This data can be a table,
1350 * an integer or user data. This data is associated with a metatable. This
1351 * metatable have an original version registred in the global context with
1352 * the name of the object (_G[<name>] = <metable> ).
1353 *
1354 * A metable is a table that modify the standard behavior of a standard
1355 * access to the associated data. The entries of this new metatable are
1356 * defined as is:
1357 *
1358 * http://lua-users.org/wiki/MetatableEvents
1359 *
1360 * __index
1361 *
1362 * we access an absent field in a table, the result is nil. This is
1363 * true, but it is not the whole truth. Actually, such access triggers
1364 * the interpreter to look for an __index metamethod: If there is no
1365 * such method, as usually happens, then the access results in nil;
1366 * otherwise, the metamethod will provide the result.
1367 *
1368 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1369 * the key does not appear in the table, but the metatable has an __index
1370 * property:
1371 *
1372 * - if the value is a function, the function is called, passing in the
1373 * table and the key; the return value of that function is returned as
1374 * the result.
1375 *
1376 * - if the value is another table, the value of the key in that table is
1377 * asked for and returned (and if it doesn't exist in that table, but that
1378 * table's metatable has an __index property, then it continues on up)
1379 *
1380 * - Use "rawget(myTable,key)" to skip this metamethod.
1381 *
1382 * http://www.lua.org/pil/13.4.1.html
1383 *
1384 * __newindex
1385 *
1386 * Like __index, but control property assignment.
1387 *
1388 * __mode - Control weak references. A string value with one or both
1389 * of the characters 'k' and 'v' which specifies that the the
1390 * keys and/or values in the table are weak references.
1391 *
1392 * __call - Treat a table like a function. When a table is followed by
1393 * parenthesis such as "myTable( 'foo' )" and the metatable has
1394 * a __call key pointing to a function, that function is invoked
1395 * (passing any specified arguments) and the return value is
1396 * returned.
1397 *
1398 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1399 * called, if the metatable for myTable has a __metatable
1400 * key, the value of that key is returned instead of the
1401 * actual metatable.
1402 *
1403 * __tostring - Control string representation. When the builtin
1404 * "tostring( myTable )" function is called, if the metatable
1405 * for myTable has a __tostring property set to a function,
1406 * that function is invoked (passing myTable to it) and the
1407 * return value is used as the string representation.
1408 *
1409 * __len - Control table length. When the table length is requested using
1410 * the length operator ( '#' ), if the metatable for myTable has
1411 * a __len key pointing to a function, that function is invoked
1412 * (passing myTable to it) and the return value used as the value
1413 * of "#myTable".
1414 *
1415 * __gc - Userdata finalizer code. When userdata is set to be garbage
1416 * collected, if the metatable has a __gc field pointing to a
1417 * function, that function is first invoked, passing the userdata
1418 * to it. The __gc metamethod is not called for tables.
1419 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1420 *
1421 * Special metamethods for redefining standard operators:
1422 * http://www.lua.org/pil/13.1.html
1423 *
1424 * __add "+"
1425 * __sub "-"
1426 * __mul "*"
1427 * __div "/"
1428 * __unm "!"
1429 * __pow "^"
1430 * __concat ".."
1431 *
1432 * Special methods for redfining standar relations
1433 * http://www.lua.org/pil/13.2.html
1434 *
1435 * __eq "=="
1436 * __lt "<"
1437 * __le "<="
1438 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001439
1440/*
1441 *
1442 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001443 * Class Map
1444 *
1445 *
1446 */
1447
1448/* Returns a struct hlua_map if the stack entry "ud" is
1449 * a class session, otherwise it throws an error.
1450 */
1451__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1452{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001453 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001454}
1455
1456/* This function is the map constructor. It don't need
1457 * the class Map object. It creates and return a new Map
1458 * object. It must be called only during "body" or "init"
1459 * context because it process some filesystem accesses.
1460 */
1461__LJMP static int hlua_map_new(struct lua_State *L)
1462{
1463 const char *fn;
1464 int match = PAT_MATCH_STR;
1465 struct sample_conv conv;
1466 const char *file = "";
1467 int line = 0;
1468 lua_Debug ar;
1469 char *err = NULL;
1470 struct arg args[2];
1471
1472 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1473 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1474
1475 fn = MAY_LJMP(luaL_checkstring(L, 1));
1476
1477 if (lua_gettop(L) >= 2) {
1478 match = MAY_LJMP(luaL_checkinteger(L, 2));
1479 if (match < 0 || match >= PAT_MATCH_NUM)
1480 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1481 }
1482
1483 /* Get Lua filename and line number. */
1484 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1485 lua_getinfo(L, "Sl", &ar); /* get info about it */
1486 if (ar.currentline > 0) { /* is there info? */
1487 file = ar.short_src;
1488 line = ar.currentline;
1489 }
1490 }
1491
1492 /* fill fake sample_conv struct. */
1493 conv.kw = ""; /* unused. */
1494 conv.process = NULL; /* unused. */
1495 conv.arg_mask = 0; /* unused. */
1496 conv.val_args = NULL; /* unused. */
1497 conv.out_type = SMP_T_STR;
1498 conv.private = (void *)(long)match;
1499 switch (match) {
1500 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1501 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1502 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1503 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1504 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1505 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1506 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001507 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001508 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1509 default:
1510 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1511 }
1512
1513 /* fill fake args. */
1514 args[0].type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001515 args[0].data.str.area = (char *)fn;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001516 args[1].type = ARGT_STOP;
1517
1518 /* load the map. */
1519 if (!sample_load_map(args, &conv, file, line, &err)) {
1520 /* error case: we cant use luaL_error because we must
1521 * free the err variable.
1522 */
1523 luaL_where(L, 1);
1524 lua_pushfstring(L, "'new': %s.", err);
1525 lua_concat(L, 2);
1526 free(err);
1527 WILL_LJMP(lua_error(L));
1528 }
1529
1530 /* create the lua object. */
1531 lua_newtable(L);
1532 lua_pushlightuserdata(L, args[0].data.map);
1533 lua_rawseti(L, -2, 0);
1534
1535 /* Pop a class Map metatable and affect it to the userdata. */
1536 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1537 lua_setmetatable(L, -2);
1538
1539
1540 return 1;
1541}
1542
1543__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1544{
1545 struct map_descriptor *desc;
1546 struct pattern *pat;
1547 struct sample smp;
1548
1549 MAY_LJMP(check_args(L, 2, "lookup"));
1550 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001551 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001552 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001553 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001554 }
1555 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001556 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001557 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001558 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 +02001559 }
1560
1561 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001562 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001563 if (str)
1564 lua_pushstring(L, "");
1565 else
1566 lua_pushnil(L);
1567 return 1;
1568 }
1569
1570 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001571 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001572 return 1;
1573}
1574
1575__LJMP static int hlua_map_lookup(struct lua_State *L)
1576{
1577 return _hlua_map_lookup(L, 0);
1578}
1579
1580__LJMP static int hlua_map_slookup(struct lua_State *L)
1581{
1582 return _hlua_map_lookup(L, 1);
1583}
1584
1585/*
1586 *
1587 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001588 * Class Socket
1589 *
1590 *
1591 */
1592
1593__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1594{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001595 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001596}
1597
1598/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001599 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001600 * received.
1601 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001602static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001603{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001604 struct stream_interface *si = appctx->owner;
Olivier Houchard9aaf7782017-09-13 18:30:23 +02001605 struct connection *c = cs_conn(objt_cs(si_opposite(si)->end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001606
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001607 if (appctx->ctx.hlua_cosocket.die) {
1608 si_shutw(si);
1609 si_shutr(si);
1610 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001611 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1612 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001613 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1614 }
1615
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001616 /* If the connection object is not available, close all the
1617 * streams and wakeup everything waiting for.
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001618 */
1619 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001620 si_shutw(si);
1621 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001622 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001623 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1624 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001625 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001626 }
1627
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001628 /* If we cant write, wakeup the pending write signals. */
1629 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001630 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001631
1632 /* If we cant read, wakeup the pending read signals. */
1633 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001634 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001635
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001636 /* if the connection is not estabkished, inform the stream that we want
1637 * to be notified whenever the connection completes.
1638 */
1639 if (!(c->flags & CO_FL_CONNECTED)) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01001640 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01001641 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01001642 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001643 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001644 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001645
1646 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001647 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001648
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001649 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001650 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001651 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001652
1653 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001654 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001655 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001656
1657 /* Some data were injected in the buffer, notify the stream
1658 * interface.
1659 */
1660 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001661 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001662
1663 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001664 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001665 */
1666 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01001667 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001668}
1669
Willy Tarreau87b09662015-04-03 00:22:06 +02001670/* This function is called when the "struct stream" is destroyed.
1671 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001672 * Wake all the pending signals.
1673 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001674static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001675{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001676 struct xref *peer;
1677
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001678 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001679 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1680 if (peer)
1681 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001682
1683 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001684 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1685 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001686}
1687
1688/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001689 * uses this object. If the stream does not exists, just quit.
1690 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001691 * pending signal can rest in the read and write lists. destroy
1692 * it.
1693 */
1694__LJMP static int hlua_socket_gc(lua_State *L)
1695{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001696 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001697 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001698 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001699
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001700 MAY_LJMP(check_args(L, 1, "__gc"));
1701
1702 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001703 peer = xref_get_peer_and_lock(&socket->xref);
1704 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001705 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001706 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001707
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001708 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001709 appctx->ctx.hlua_cosocket.die = 1;
1710 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001711
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001712 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001713 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001714 return 0;
1715}
1716
1717/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001718 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001719 */
sada05ed3302018-05-11 11:48:18 -07001720__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001721{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001722 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001723 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001724 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001725
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001726 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001727
1728 /* Check if we run on the same thread than the xreator thread.
1729 * We cannot access to the socket if the thread is different.
1730 */
1731 if (socket->tid != tid)
1732 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1733
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001734 peer = xref_get_peer_and_lock(&socket->xref);
1735 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001736 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001737 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001738
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001739 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001740 appctx->ctx.hlua_cosocket.die = 1;
1741 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001742
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001743 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001744 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001745 return 0;
1746}
1747
sada05ed3302018-05-11 11:48:18 -07001748/* The close function calls close_helper.
1749 */
1750__LJMP static int hlua_socket_close(lua_State *L)
1751{
1752 MAY_LJMP(check_args(L, 1, "close"));
1753 return hlua_socket_close_helper(L);
1754}
1755
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001756/* This Lua function assumes that the stack contain three parameters.
1757 * 1 - USERDATA containing a struct socket
1758 * 2 - INTEGER with values of the macro defined below
1759 * If the integer is -1, we must read at most one line.
1760 * If the integer is -2, we ust read all the data until the
1761 * end of the stream.
1762 * If the integer is positive value, we must read a number of
1763 * bytes corresponding to this value.
1764 */
1765#define HLSR_READ_LINE (-1)
1766#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001767__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001768{
1769 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1770 int wanted = lua_tointeger(L, 2);
1771 struct hlua *hlua = hlua_gethlua(L);
1772 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001773 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001774 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02001775 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001776 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02001777 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001778 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001779 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001780 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001781 struct stream_interface *si;
1782 struct stream *s;
1783 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001784 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001785
1786 /* Check if this lua stack is schedulable. */
1787 if (!hlua || !hlua->task)
1788 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1789 "'frontend', 'backend' or 'task'"));
1790
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001791 /* Check if we run on the same thread than the xreator thread.
1792 * We cannot access to the socket if the thread is different.
1793 */
1794 if (socket->tid != tid)
1795 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1796
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001797 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001798 peer = xref_get_peer_and_lock(&socket->xref);
1799 if (!peer)
1800 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001801 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1802 si = appctx->owner;
1803 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001804
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001805 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001806 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001807 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001808 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001809 if (nblk < 0) /* Connection close. */
1810 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001811 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001812 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001813
1814 /* remove final \r\n. */
1815 if (nblk == 1) {
1816 if (blk1[len1-1] == '\n') {
1817 len1--;
1818 skip_at_end++;
1819 if (blk1[len1-1] == '\r') {
1820 len1--;
1821 skip_at_end++;
1822 }
1823 }
1824 }
1825 else {
1826 if (blk2[len2-1] == '\n') {
1827 len2--;
1828 skip_at_end++;
1829 if (blk2[len2-1] == '\r') {
1830 len2--;
1831 skip_at_end++;
1832 }
1833 }
1834 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001835 }
1836
1837 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001838 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001839 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001840 if (nblk < 0) /* Connection close. */
1841 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001842 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001843 goto connection_empty;
1844 }
1845
1846 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001847 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001848 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001849 if (nblk < 0) /* Connection close. */
1850 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001851 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001852 goto connection_empty;
1853
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001854 missing_bytes = wanted - socket->b.n;
1855 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001856 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001857 len1 = missing_bytes;
1858 } if (nblk == 2 && len1 + len2 > missing_bytes)
1859 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001860 }
1861
1862 len = len1;
1863
1864 luaL_addlstring(&socket->b, blk1, len1);
1865 if (nblk == 2) {
1866 len += len2;
1867 luaL_addlstring(&socket->b, blk2, len2);
1868 }
1869
1870 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001871 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001872
1873 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02001874 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001875
1876 /* If the pattern reclaim to read all the data
1877 * in the connection, got out.
1878 */
1879 if (wanted == HLSR_READ_ALL)
1880 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001881 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001882 goto connection_empty;
1883
1884 /* Return result. */
1885 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001886 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001887 return 1;
1888
1889connection_closed:
1890
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001891 xref_unlock(&socket->xref, peer);
1892
1893no_peer:
1894
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001895 /* If the buffer containds data. */
1896 if (socket->b.n > 0) {
1897 luaL_pushresult(&socket->b);
1898 return 1;
1899 }
1900 lua_pushnil(L);
1901 lua_pushstring(L, "connection closed.");
1902 return 2;
1903
1904connection_empty:
1905
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001906 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1907 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001908 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001909 }
1910 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02001911 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001912 return 0;
1913}
1914
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001915/* This Lua function gets two parameters. The first one can be string
1916 * or a number. If the string is "*l", the user requires one line. If
1917 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001918 * If the value is a number, the user require a number of bytes equal
1919 * to the value. The default value is "*l" (a line).
1920 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001921 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001922 * integer takes this values:
1923 * -1 : read a line
1924 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001925 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001926 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001927 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001928 * concatenated with the read data.
1929 */
1930__LJMP static int hlua_socket_receive(struct lua_State *L)
1931{
1932 int wanted = HLSR_READ_LINE;
1933 const char *pattern;
1934 int type;
1935 char *error;
1936 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001937 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001938
1939 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1940 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1941
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001942 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001943
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001944 /* Check if we run on the same thread than the xreator thread.
1945 * We cannot access to the socket if the thread is different.
1946 */
1947 if (socket->tid != tid)
1948 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1949
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001950 /* check for pattern. */
1951 if (lua_gettop(L) >= 2) {
1952 type = lua_type(L, 2);
1953 if (type == LUA_TSTRING) {
1954 pattern = lua_tostring(L, 2);
1955 if (strcmp(pattern, "*a") == 0)
1956 wanted = HLSR_READ_ALL;
1957 else if (strcmp(pattern, "*l") == 0)
1958 wanted = HLSR_READ_LINE;
1959 else {
1960 wanted = strtoll(pattern, &error, 10);
1961 if (*error != '\0')
1962 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1963 }
1964 }
1965 else if (type == LUA_TNUMBER) {
1966 wanted = lua_tointeger(L, 2);
1967 if (wanted < 0)
1968 WILL_LJMP(luaL_error(L, "Unsupported size."));
1969 }
1970 }
1971
1972 /* Set pattern. */
1973 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01001974
1975 /* Check if we would replace the top by itself. */
1976 if (lua_gettop(L) != 2)
1977 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001978
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001979 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001980 luaL_buffinit(L, &socket->b);
1981
1982 /* Check prefix. */
1983 if (lua_gettop(L) >= 3) {
1984 if (lua_type(L, 3) != LUA_TSTRING)
1985 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1986 pattern = lua_tolstring(L, 3, &len);
1987 luaL_addlstring(&socket->b, pattern, len);
1988 }
1989
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001990 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001991}
1992
1993/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08001994 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001995 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001996static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001997{
1998 struct hlua_socket *socket;
1999 struct hlua *hlua = hlua_gethlua(L);
2000 struct appctx *appctx;
2001 size_t buf_len;
2002 const char *buf;
2003 int len;
2004 int send_len;
2005 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002006 struct xref *peer;
2007 struct stream_interface *si;
2008 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002009
2010 /* Check if this lua stack is schedulable. */
2011 if (!hlua || !hlua->task)
2012 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2013 "'frontend', 'backend' or 'task'"));
2014
2015 /* Get object */
2016 socket = MAY_LJMP(hlua_checksocket(L, 1));
2017 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002018 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002019
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002020 /* Check if we run on the same thread than the xreator thread.
2021 * We cannot access to the socket if the thread is different.
2022 */
2023 if (socket->tid != tid)
2024 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2025
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002026 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002027 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002028 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002029 lua_pushinteger(L, -1);
2030 return 1;
2031 }
2032 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2033 si = appctx->owner;
2034 s = si_strm(si);
2035
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002036 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002037 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002038 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002039 lua_pushinteger(L, -1);
2040 return 1;
2041 }
2042
2043 /* Update the input buffer data. */
2044 buf += sent;
2045 send_len = buf_len - sent;
2046
2047 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002048 if (sent >= buf_len) {
2049 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002050 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002051 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002052
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002053 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002054 * the request buffer if its not required.
2055 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002056 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002057 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002058 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002059 }
2060
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002061 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002062 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002063 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002064 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002065 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002066
2067 /* send data */
2068 if (len < send_len)
2069 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002070 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002071
2072 /* "Not enough space" (-1), "Buffer too little to contain
2073 * the data" (-2) are not expected because the available length
2074 * is tested.
2075 * Other unknown error are also not expected.
2076 */
2077 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002078 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002079 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002080
sada05ed3302018-05-11 11:48:18 -07002081 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002082 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002083 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002084 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002085 return 1;
2086 }
2087
2088 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002089 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002090
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002091 s->req.rex = TICK_ETERNITY;
2092 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002093
2094 /* Update length sent. */
2095 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002096 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002097
2098 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002099 if (sent + len >= buf_len) {
2100 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002101 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002102 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002103
2104hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002105 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2106 xref_unlock(&socket->xref, peer);
2107 WILL_LJMP(luaL_error(L, "out of memory"));
2108 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002109 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002110 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002111 return 0;
2112}
2113
2114/* This function initiate the send of data. It just check the input
2115 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002116 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002117 * "hlua_socket_write_yield" that can yield.
2118 *
2119 * The Lua function gets between 3 and 4 parameters. The first one is
2120 * the associated object. The second is a string buffer. The third is
2121 * a facultative integer that represents where is the buffer position
2122 * of the start of the data that can send. The first byte is the
2123 * position "1". The default value is "1". The fourth argument is a
2124 * facultative integer that represents where is the buffer position
2125 * of the end of the data that can send. The default is the last byte.
2126 */
2127static int hlua_socket_send(struct lua_State *L)
2128{
2129 int i;
2130 int j;
2131 const char *buf;
2132 size_t buf_len;
2133
2134 /* Check number of arguments. */
2135 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2136 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2137
2138 /* Get the string. */
2139 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2140
2141 /* Get and check j. */
2142 if (lua_gettop(L) == 4) {
2143 j = MAY_LJMP(luaL_checkinteger(L, 4));
2144 if (j < 0)
2145 j = buf_len + j + 1;
2146 if (j > buf_len)
2147 j = buf_len + 1;
2148 lua_pop(L, 1);
2149 }
2150 else
2151 j = buf_len;
2152
2153 /* Get and check i. */
2154 if (lua_gettop(L) == 3) {
2155 i = MAY_LJMP(luaL_checkinteger(L, 3));
2156 if (i < 0)
2157 i = buf_len + i + 1;
2158 if (i > buf_len)
2159 i = buf_len + 1;
2160 lua_pop(L, 1);
2161 } else
2162 i = 1;
2163
2164 /* Check bth i and j. */
2165 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002166 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002167 return 1;
2168 }
2169 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002170 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002171 return 1;
2172 }
2173 if (i == 0)
2174 i = 1;
2175 if (j == 0)
2176 j = 1;
2177
2178 /* Pop the string. */
2179 lua_pop(L, 1);
2180
2181 /* Update the buffer length. */
2182 buf += i - 1;
2183 buf_len = j - i + 1;
2184 lua_pushlstring(L, buf, buf_len);
2185
2186 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002187 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002188
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002189 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002190}
2191
Willy Tarreau22b0a682015-06-17 19:43:49 +02002192#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002193__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2194{
2195 static char buffer[SOCKET_INFO_MAX_LEN];
2196 int ret;
2197 int len;
2198 char *p;
2199
2200 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2201 if (ret <= 0) {
2202 lua_pushnil(L);
2203 return 1;
2204 }
2205
2206 if (ret == AF_UNIX) {
2207 lua_pushstring(L, buffer+1);
2208 return 1;
2209 }
2210 else if (ret == AF_INET6) {
2211 buffer[0] = '[';
2212 len = strlen(buffer);
2213 buffer[len] = ']';
2214 len++;
2215 buffer[len] = ':';
2216 len++;
2217 p = buffer;
2218 }
2219 else if (ret == AF_INET) {
2220 p = buffer + 1;
2221 len = strlen(p);
2222 p[len] = ':';
2223 len++;
2224 }
2225 else {
2226 lua_pushnil(L);
2227 return 1;
2228 }
2229
2230 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2231 lua_pushnil(L);
2232 return 1;
2233 }
2234
2235 lua_pushstring(L, p);
2236 return 1;
2237}
2238
2239/* Returns information about the peer of the connection. */
2240__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2241{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002242 struct hlua_socket *socket;
2243 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002244 struct xref *peer;
2245 struct appctx *appctx;
2246 struct stream_interface *si;
2247 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002248 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002249
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002250 MAY_LJMP(check_args(L, 1, "getpeername"));
2251
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002252 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002253
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002254 /* Check if we run on the same thread than the xreator thread.
2255 * We cannot access to the socket if the thread is different.
2256 */
2257 if (socket->tid != tid)
2258 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2259
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002260 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002261 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002262 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002263 lua_pushnil(L);
2264 return 1;
2265 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002266 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2267 si = appctx->owner;
2268 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002269
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002270 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002271 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002272 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002273 lua_pushnil(L);
2274 return 1;
2275 }
2276
Willy Tarreaua71f6422016-11-16 17:00:14 +01002277 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002278 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002279 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002280 lua_pushnil(L);
2281 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002282 }
2283
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002284 ret = MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2285 xref_unlock(&socket->xref, peer);
2286 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002287}
2288
2289/* Returns information about my connection side. */
2290static int hlua_socket_getsockname(struct lua_State *L)
2291{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002292 struct hlua_socket *socket;
2293 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002294 struct appctx *appctx;
2295 struct xref *peer;
2296 struct stream_interface *si;
2297 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002298 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002299
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002300 MAY_LJMP(check_args(L, 1, "getsockname"));
2301
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002302 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002303
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002304 /* Check if we run on the same thread than the xreator thread.
2305 * We cannot access to the socket if the thread is different.
2306 */
2307 if (socket->tid != tid)
2308 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2309
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002310 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002311 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002312 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313 lua_pushnil(L);
2314 return 1;
2315 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002316 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2317 si = appctx->owner;
2318 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002319
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002320 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002322 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323 lua_pushnil(L);
2324 return 1;
2325 }
2326
Willy Tarreaua71f6422016-11-16 17:00:14 +01002327 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002328 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002329 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002330 lua_pushnil(L);
2331 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002332 }
2333
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002334 ret = hlua_socket_info(L, &conn->addr.from);
2335 xref_unlock(&socket->xref, peer);
2336 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002337}
2338
2339/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002340static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002341 .obj_type = OBJ_TYPE_APPLET,
2342 .name = "<LUA_TCP>",
2343 .fct = hlua_socket_handler,
2344 .release = hlua_socket_release,
2345};
2346
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002347__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002348{
2349 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2350 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002351 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002352 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002353 struct stream_interface *si;
2354 struct stream *s;
2355
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002356 /* Check if we run on the same thread than the xreator thread.
2357 * We cannot access to the socket if the thread is different.
2358 */
2359 if (socket->tid != tid)
2360 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2361
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002362 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002363 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002364 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002365 lua_pushnil(L);
2366 lua_pushstring(L, "Can't connect");
2367 return 2;
2368 }
2369 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2370 si = appctx->owner;
2371 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002372
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002373 /* Check if we run on the same thread than the xreator thread.
2374 * We cannot access to the socket if the thread is different.
2375 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002376 if (socket->tid != tid) {
2377 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002378 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002379 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002380
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002381 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002382 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002383 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002384 lua_pushnil(L);
2385 lua_pushstring(L, "Can't connect");
2386 return 2;
2387 }
2388
Willy Tarreaue09101e2018-10-16 17:37:12 +02002389 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002390
2391 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002392 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002393 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002394 lua_pushinteger(L, 1);
2395 return 1;
2396 }
2397
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002398 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2399 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002400 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002401 }
2402 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002403 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002404 return 0;
2405}
2406
2407/* This function fail or initite the connection. */
2408__LJMP static int hlua_socket_connect(struct lua_State *L)
2409{
2410 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002411 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002412 const char *ip;
2413 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002414 struct hlua *hlua;
2415 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002416 int low, high;
2417 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002418 struct xref *peer;
2419 struct stream_interface *si;
2420 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002421
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002422 if (lua_gettop(L) < 2)
2423 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002424
2425 /* Get args. */
2426 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002427
2428 /* Check if we run on the same thread than the xreator thread.
2429 * We cannot access to the socket if the thread is different.
2430 */
2431 if (socket->tid != tid)
2432 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2433
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002434 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002435 if (lua_gettop(L) >= 3) {
2436 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002437 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002438
Tim Duesterhus6edab862018-01-06 19:04:45 +01002439 /* Force the ip to end with a colon, to support IPv6 addresses
2440 * that are not enclosed within square brackets.
2441 */
2442 if (port > 0) {
2443 luaL_buffinit(L, &b);
2444 luaL_addstring(&b, ip);
2445 luaL_addchar(&b, ':');
2446 luaL_pushresult(&b);
2447 ip = lua_tolstring(L, lua_gettop(L), NULL);
2448 }
2449 }
2450
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002451 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002452 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002453 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002454 lua_pushnil(L);
2455 return 1;
2456 }
2457 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2458 si = appctx->owner;
2459 s = si_strm(si);
2460
2461 /* Initialise connection. */
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002462 conn = cs_conn(si_alloc_cs(&s->si[1], NULL));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002463 if (!conn) {
2464 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002465 WILL_LJMP(luaL_error(L, "connect: internal error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002466 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002467
Willy Tarreau3adac082015-09-26 17:51:09 +02002468 /* needed for the connection not to be closed */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002469 conn->target = s->target;
Willy Tarreau3adac082015-09-26 17:51:09 +02002470
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002471 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002472 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002473 if (!addr) {
2474 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002475 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002476 }
2477 if (low != high) {
2478 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002479 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002480 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002481 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002482
2483 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002484 if (low == 0) {
2485 if (conn->addr.to.ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002486 if (port == -1) {
2487 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002488 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002489 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002490 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2491 } else if (conn->addr.to.ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002492 if (port == -1) {
2493 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002494 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002495 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002496 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2497 }
2498 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002499
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002500 hlua = hlua_gethlua(L);
Willy Tarreaue09101e2018-10-16 17:37:12 +02002501 appctx = __objt_appctx(s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002502
2503 /* inform the stream that we want to be notified whenever the
2504 * connection completes.
2505 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002506 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002507 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002508 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002509
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002510 hlua->flags |= HLUA_MUST_GC;
2511
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002512 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2513 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002514 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002515 }
2516 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002517
2518 task_wakeup(s->task, TASK_WOKEN_INIT);
2519 /* Return yield waiting for connection. */
2520
Willy Tarreau9635e032018-10-16 17:52:55 +02002521 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002522
2523 return 0;
2524}
2525
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002526#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002527__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2528{
2529 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002530 struct xref *peer;
2531 struct appctx *appctx;
2532 struct stream_interface *si;
2533 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002534
2535 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2536 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002537
2538 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002539 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002540 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002541 lua_pushnil(L);
2542 return 1;
2543 }
2544 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2545 si = appctx->owner;
2546 s = si_strm(si);
2547
2548 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002549 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002550 return MAY_LJMP(hlua_socket_connect(L));
2551}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002552#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002553
2554__LJMP static int hlua_socket_setoption(struct lua_State *L)
2555{
2556 return 0;
2557}
2558
2559__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2560{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002561 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002562 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002563 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002564 struct xref *peer;
2565 struct appctx *appctx;
2566 struct stream_interface *si;
2567 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002568
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002569 MAY_LJMP(check_args(L, 2, "settimeout"));
2570
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002571 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002572
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002573 /* convert the timeout to millis */
2574 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002575
Thierry Fournier17a921b2018-03-08 09:59:02 +01002576 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002577 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002578 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2579
Mark Lakes56cc1252018-03-27 09:48:06 +02002580 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002581 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002582
2583 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002584 if (tmout == 0)
2585 tmout++; /* very small timeouts are adjusted to a minium of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002586
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002587 /* Check if we run on the same thread than the xreator thread.
2588 * We cannot access to the socket if the thread is different.
2589 */
2590 if (socket->tid != tid)
2591 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2592
Mark Lakes56cc1252018-03-27 09:48:06 +02002593 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002594 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002595 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002596 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2597 WILL_LJMP(lua_error(L));
2598 return 0;
2599 }
2600 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2601 si = appctx->owner;
2602 s = si_strm(si);
2603
Cyril Bonté7bb63452018-08-17 23:51:02 +02002604 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002605 s->req.rto = tmout;
2606 s->req.wto = tmout;
2607 s->res.rto = tmout;
2608 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002609 s->req.rex = tick_add_ifset(now_ms, tmout);
2610 s->req.wex = tick_add_ifset(now_ms, tmout);
2611 s->res.rex = tick_add_ifset(now_ms, tmout);
2612 s->res.wex = tick_add_ifset(now_ms, tmout);
2613
2614 s->task->expire = tick_add_ifset(now_ms, tmout);
2615 task_queue(s->task);
2616
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002617 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002618
Thierry Fourniere9636f12018-03-08 09:54:32 +01002619 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002620 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002621}
2622
2623__LJMP static int hlua_socket_new(lua_State *L)
2624{
2625 struct hlua_socket *socket;
2626 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002627 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002628 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002629
2630 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002631 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002632 hlua_pusherror(L, "socket: full stack");
2633 goto out_fail_conf;
2634 }
2635
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002636 /* Create the object: obj[0] = userdata. */
2637 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002638 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002639 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002640 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002641 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002642
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002643 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002644 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002645 hlua_pusherror(L, "socket: uninitialized pools.");
2646 goto out_fail_conf;
2647 }
2648
Willy Tarreau87b09662015-04-03 00:22:06 +02002649 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002650 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2651 lua_setmetatable(L, -2);
2652
Willy Tarreaud420a972015-04-06 00:39:18 +02002653 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002654 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002655 if (!appctx) {
2656 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002657 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002658 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002659
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002660 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002661 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002662 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2663 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002664
Willy Tarreaud420a972015-04-06 00:39:18 +02002665 /* Now create a session, task and stream for this applet */
2666 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2667 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002668 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002669 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002670 }
2671
Willy Tarreau87787ac2017-08-28 16:22:54 +02002672 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002673 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002674 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002675 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002676 }
2677
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002678 /* Initialise cross reference between stream and Lua socket object. */
2679 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002680
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002681 /* Configure "right" stream interface. this "si" is used to connect
2682 * and retrieve data from the server. The connection is initialized
2683 * with the "struct server".
2684 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002685 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002686
2687 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002688 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2689 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002690
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002691 return 1;
2692
Willy Tarreaud420a972015-04-06 00:39:18 +02002693 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002694 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002695 out_fail_sess:
2696 appctx_free(appctx);
2697 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002698 WILL_LJMP(lua_error(L));
2699 return 0;
2700}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002701
2702/*
2703 *
2704 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002705 * Class Channel
2706 *
2707 *
2708 */
2709
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002710/* This function is called before the Lua execution. It stores
2711 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002712 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002713static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002714{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002715 c->mode = stream->be->mode;
2716 switch (c->mode) {
2717 case PR_MODE_HTTP:
2718 c->data.http.dir = opt & SMP_OPT_DIR;
2719 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2720 c->data.http.state = stream->txn->req.msg_state;
2721 else
2722 c->data.http.state = stream->txn->rsp.msg_state;
2723 break;
2724 default:
2725 break;
2726 }
2727}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002728
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002729/* This function is called after the Lua execution. it
2730 * returns true if the parser state is consistent, otherwise,
2731 * it return false.
2732 *
2733 * In HTTP mode, the parser state must be in the same state
2734 * or greater when we exit the function. Even if we do a
2735 * control yield. This prevent to break the HTTP message
2736 * from the Lua code.
2737 */
2738static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2739{
2740 if (c->mode != stream->be->mode)
2741 return 0;
2742
2743 switch (c->mode) {
2744 case PR_MODE_HTTP:
2745 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002746 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002747 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2748 return stream->txn->req.msg_state >= c->data.http.state;
2749 else
2750 return stream->txn->rsp.msg_state >= c->data.http.state;
2751 default:
2752 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002753 }
2754 return 1;
2755}
2756
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002757/* Returns the struct hlua_channel join to the class channel in the
2758 * stack entry "ud" or throws an argument error.
2759 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002760__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002761{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002762 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002763}
2764
Willy Tarreau47860ed2015-03-10 14:07:50 +01002765/* Pushes the channel onto the top of the stack. If the stask does not have a
2766 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002767 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002768static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002769{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002770 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002771 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002772 return 0;
2773
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002774 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002775 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002776 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002777
2778 /* Pop a class sesison metatable and affect it to the userdata. */
2779 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2780 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002781 return 1;
2782}
2783
2784/* Duplicate all the data present in the input channel and put it
2785 * in a string LUA variables. Returns -1 and push a nil value in
2786 * the stack if the channel is closed and all the data are consumed,
2787 * returns 0 if no data are available, otherwise it returns the length
2788 * of the builded string.
2789 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002790static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002791{
2792 char *blk1;
2793 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002794 size_t len1;
2795 size_t len2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002796 int ret;
2797 luaL_Buffer b;
2798
Willy Tarreau06d80a92017-10-19 14:32:15 +02002799 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002800 if (unlikely(ret == 0))
2801 return 0;
2802
2803 if (unlikely(ret < 0)) {
2804 lua_pushnil(L);
2805 return -1;
2806 }
2807
2808 luaL_buffinit(L, &b);
2809 luaL_addlstring(&b, blk1, len1);
2810 if (unlikely(ret == 2))
2811 luaL_addlstring(&b, blk2, len2);
2812 luaL_pushresult(&b);
2813
2814 if (unlikely(ret == 2))
2815 return len1 + len2;
2816 return len1;
2817}
2818
2819/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2820 * a yield. This function keep the data in the buffer.
2821 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002822__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002823{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002824 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002825
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002826 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2827
Christopher Faulet3f829a42018-12-13 21:56:45 +01002828 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2829 WILL_LJMP(lua_error(L));
2830
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002831 if (_hlua_channel_dup(chn, L) == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002832 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002833 return 1;
2834}
2835
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002836/* Check arguments for the function "hlua_channel_dup_yield". */
2837__LJMP static int hlua_channel_dup(lua_State *L)
2838{
2839 MAY_LJMP(check_args(L, 1, "dup"));
2840 MAY_LJMP(hlua_checkchannel(L, 1));
2841 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2842}
2843
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002844/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2845 * a yield. This function consumes the data in the buffer. It returns
2846 * a string containing the data or a nil pointer if no data are available
2847 * and the channel is closed.
2848 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002849__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002850{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002851 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002852 int ret;
2853
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002854 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002855
Christopher Faulet3f829a42018-12-13 21:56:45 +01002856 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2857 WILL_LJMP(lua_error(L));
2858
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002859 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002860 if (unlikely(ret == 0))
Willy Tarreau9635e032018-10-16 17:52:55 +02002861 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002862
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002863 if (unlikely(ret == -1))
2864 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002865
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002866 b_sub(&chn->buf, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002867 return 1;
2868}
2869
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002870/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002871__LJMP static int hlua_channel_get(lua_State *L)
2872{
2873 MAY_LJMP(check_args(L, 1, "get"));
2874 MAY_LJMP(hlua_checkchannel(L, 1));
2875 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2876}
2877
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002878/* This functions consumes and returns one line. If the channel is closed,
2879 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002880 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002881 * value.
2882 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002883__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002884{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002885 char *blk1;
2886 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002887 size_t len1;
2888 size_t len2;
2889 size_t len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002890 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002891 int ret;
2892 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002893
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002894 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2895
Christopher Faulet3f829a42018-12-13 21:56:45 +01002896 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2897 WILL_LJMP(lua_error(L));
2898
Willy Tarreau06d80a92017-10-19 14:32:15 +02002899 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002900 if (ret == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002901 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002902
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002903 if (ret == -1) {
2904 lua_pushnil(L);
2905 return 1;
2906 }
2907
2908 luaL_buffinit(L, &b);
2909 luaL_addlstring(&b, blk1, len1);
2910 len = len1;
2911 if (unlikely(ret == 2)) {
2912 luaL_addlstring(&b, blk2, len2);
2913 len += len2;
2914 }
2915 luaL_pushresult(&b);
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002916 b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn) + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002917 return 1;
2918}
2919
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002920/* Check arguments for the function "hlua_channel_getline_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002921__LJMP static int hlua_channel_getline(lua_State *L)
2922{
2923 MAY_LJMP(check_args(L, 1, "getline"));
2924 MAY_LJMP(hlua_checkchannel(L, 1));
2925 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2926}
2927
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002928/* This function takes a string as input, and append it at the
2929 * input side of channel. If the data is too big, but a space
2930 * is probably available after sending some data, the function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002931 * yields. If the data is bigger than the buffer, or if the
2932 * channel is closed, it returns -1. Otherwise, it returns the
2933 * amount of data written.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002934 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002935__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002936{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002937 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002938 size_t len;
2939 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2940 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2941 int ret;
2942 int max;
2943
Christopher Faulet3f829a42018-12-13 21:56:45 +01002944 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2945 WILL_LJMP(lua_error(L));
2946
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002947 /* Check if the buffer is available because HAProxy doesn't allocate
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002948 * the request buffer if its not required.
2949 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002950 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01002951 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02002952 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002953 }
2954
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002955 max = channel_recv_limit(chn) - b_data(&chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002956 if (max > len - l)
2957 max = len - l;
2958
Willy Tarreau06d80a92017-10-19 14:32:15 +02002959 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002960 if (ret == -2 || ret == -3) {
2961 lua_pushinteger(L, -1);
2962 return 1;
2963 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002964 if (ret == -1) {
2965 chn->flags |= CF_WAKE_WRITE;
Willy Tarreau9635e032018-10-16 17:52:55 +02002966 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002967 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002968 l += ret;
2969 lua_pop(L, 1);
2970 lua_pushinteger(L, l);
2971
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002972 max = channel_recv_limit(chn) - b_data(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02002973 if (max == 0 && co_data(chn) == 0) {
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002974 /* There are no space available, and the output buffer is empty.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002975 * in this case, we cannot add more data, so we cannot yield,
2976 * we return the amount of copyied data.
2977 */
2978 return 1;
2979 }
2980 if (l < len)
Willy Tarreau9635e032018-10-16 17:52:55 +02002981 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002982 return 1;
2983}
2984
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002985/* Just a wrapper of "hlua_channel_append_yield". It returns the length
2986 * of the written string, or -1 if the channel is closed or if the
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002987 * buffer size is too little for the data.
2988 */
2989__LJMP static int hlua_channel_append(lua_State *L)
2990{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002991 size_t len;
2992
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002993 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002994 MAY_LJMP(hlua_checkchannel(L, 1));
2995 MAY_LJMP(luaL_checklstring(L, 2, &len));
2996 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002997 lua_pushinteger(L, 0);
2998
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002999 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003000}
3001
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003002/* Just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003003 * his process by cleaning the buffer. The result is a replacement
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003004 * of the current data. It returns the length of the written string,
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003005 * or -1 if the channel is closed or if the buffer size is too
3006 * little for the data.
3007 */
3008__LJMP static int hlua_channel_set(lua_State *L)
3009{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003010 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003011
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003012 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003013 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003014 lua_pushinteger(L, 0);
3015
Christopher Faulet3f829a42018-12-13 21:56:45 +01003016 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
3017 WILL_LJMP(lua_error(L));
3018
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003019 b_set_data(&chn->buf, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003020
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003021 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003022}
3023
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003024/* Append data in the output side of the buffer. This data is immediately
3025 * sent. The function returns the amount of data written. If the buffer
3026 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003027 * if the channel is closed.
3028 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003029__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003030{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003031 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003032 size_t len;
3033 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3034 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3035 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003036 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003037
Christopher Faulet3f829a42018-12-13 21:56:45 +01003038 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
3039 WILL_LJMP(lua_error(L));
3040
Willy Tarreau47860ed2015-03-10 14:07:50 +01003041 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003042 lua_pushinteger(L, -1);
3043 return 1;
3044 }
3045
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003046 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003047 * the request buffer if its not required.
3048 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003049 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01003050 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02003051 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003052 }
3053
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003054 /* The written data will be immediately sent, so we can check
3055 * the available space without taking in account the reserve.
3056 * The reserve is guaranteed for the processing of incoming
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003057 * data, because the buffer will be flushed.
3058 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003059 max = b_room(&chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003060
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003061 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003062 * in this case, we cannot add more data, so we cannot yield,
3063 * we return the amount of copyied data.
3064 */
Willy Tarreaua79021a2018-06-15 18:07:57 +02003065 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003066 return 1;
3067
3068 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003069 if (max > len - l)
3070 max = len - l;
3071
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003072 /* The buffer available size may be not contiguous. This test
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003073 * detects a non contiguous buffer and realign it.
3074 */
Willy Tarreau3f679992018-06-15 15:06:42 +02003075 if (ci_space_for_replace(chn) < max)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003076 channel_slow_realign(chn, trash.area);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003077
3078 /* Copy input data in the buffer. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003079 max = b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn), str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003080
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003081 /* buffer replace considers that the input part is filled.
3082 * so, I must forward these new data in the output part.
3083 */
Willy Tarreaubcbd3932018-06-06 07:13:22 +02003084 c_adv(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003085
3086 l += max;
3087 lua_pop(L, 1);
3088 lua_pushinteger(L, l);
3089
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003090 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003091 * in this case, we cannot add more data, so we cannot yield,
3092 * we return the amount of copyied data.
3093 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003094 max = b_room(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003095 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003096 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003097
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003098 if (l < len) {
3099 /* If we are waiting for space in the response buffer, we
3100 * must set the flag WAKERESWR. This flag required the task
3101 * wake up if any activity is detected on the response buffer.
3102 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003103 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003104 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003105 else
3106 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003107 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003108 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003109
3110 return 1;
3111}
3112
3113/* Just a wraper of "_hlua_channel_send". This wrapper permits
3114 * yield the LUA process, and resume it without checking the
3115 * input arguments.
3116 */
3117__LJMP static int hlua_channel_send(lua_State *L)
3118{
3119 MAY_LJMP(check_args(L, 2, "send"));
3120 lua_pushinteger(L, 0);
3121
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003122 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003123}
3124
3125/* This function forward and amount of butes. The data pass from
3126 * the input side of the buffer to the output side, and can be
3127 * forwarded. This function never fails.
3128 *
3129 * The Lua function takes an amount of bytes to be forwarded in
3130 * imput. It returns the number of bytes forwarded.
3131 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003132__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003133{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003134 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003135 int len;
3136 int l;
3137 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003138 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003139
3140 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003141
3142 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
3143 WILL_LJMP(lua_error(L));
3144
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003145 len = MAY_LJMP(luaL_checkinteger(L, 2));
3146 l = MAY_LJMP(luaL_checkinteger(L, -1));
3147
3148 max = len - l;
Willy Tarreaua79021a2018-06-15 18:07:57 +02003149 if (max > ci_data(chn))
3150 max = ci_data(chn);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003151 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003152 l += max;
3153
3154 lua_pop(L, 1);
3155 lua_pushinteger(L, l);
3156
3157 /* Check if it miss bytes to forward. */
3158 if (l < len) {
3159 /* The the input channel or the output channel are closed, we
3160 * must return the amount of data forwarded.
3161 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003162 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003163 return 1;
3164
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003165 /* If we are waiting for space data in the response buffer, we
3166 * must set the flag WAKERESWR. This flag required the task
3167 * wake up if any activity is detected on the response buffer.
3168 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003169 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003170 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003171 else
3172 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003173
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003174 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003175 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003176 }
3177
3178 return 1;
3179}
3180
3181/* Just check the input and prepare the stack for the previous
3182 * function "hlua_channel_forward_yield"
3183 */
3184__LJMP static int hlua_channel_forward(lua_State *L)
3185{
3186 MAY_LJMP(check_args(L, 2, "forward"));
3187 MAY_LJMP(hlua_checkchannel(L, 1));
3188 MAY_LJMP(luaL_checkinteger(L, 2));
3189
3190 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003191 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003192}
3193
3194/* Just returns the number of bytes available in the input
3195 * side of the buffer. This function never fails.
3196 */
3197__LJMP static int hlua_channel_get_in_len(lua_State *L)
3198{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003199 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003200
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003201 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003202 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003203 if (IS_HTX_STRM(chn_strm(chn))) {
3204 struct htx *htx = htxbuf(&chn->buf);
3205 lua_pushinteger(L, htx->data - co_data(chn));
3206 }
3207 else
3208 lua_pushinteger(L, ci_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003209 return 1;
3210}
3211
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003212/* Returns true if the channel is full. */
3213__LJMP static int hlua_channel_is_full(lua_State *L)
3214{
3215 struct channel *chn;
3216 int rem;
3217
3218 MAY_LJMP(check_args(L, 1, "is_full"));
3219 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3220
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003221 if (IS_HTX_STRM(chn_strm(chn))) {
3222 struct htx *htx = htxbuf(&chn->buf);
3223
3224 rem = htx_free_data_space(htx);
3225 }
3226 else
3227 rem = b_room(&chn->buf);
3228
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003229 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
3230
3231 lua_pushboolean(L, rem <= 0);
3232 return 1;
3233}
3234
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003235/* Just returns the number of bytes available in the output
3236 * side of the buffer. This function never fails.
3237 */
3238__LJMP static int hlua_channel_get_out_len(lua_State *L)
3239{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003240 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003241
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003242 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003243 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003244 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003245 return 1;
3246}
3247
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003248/*
3249 *
3250 *
3251 * Class Fetches
3252 *
3253 *
3254 */
3255
3256/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003257 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003258 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003259__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003260{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003261 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003262}
3263
3264/* This function creates and push in the stack a fetch object according
3265 * with a current TXN.
3266 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003267static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003268{
Willy Tarreau7073c472015-04-06 11:15:40 +02003269 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003270
3271 /* Check stack size. */
3272 if (!lua_checkstack(L, 3))
3273 return 0;
3274
3275 /* Create the object: obj[0] = userdata.
3276 * Note that the base of the Fetches object is the
3277 * transaction object.
3278 */
3279 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003280 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003281 lua_rawseti(L, -2, 0);
3282
Willy Tarreau7073c472015-04-06 11:15:40 +02003283 hsmp->s = txn->s;
3284 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003285 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003286 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003287
3288 /* Pop a class sesison metatable and affect it to the userdata. */
3289 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3290 lua_setmetatable(L, -2);
3291
3292 return 1;
3293}
3294
3295/* This function is an LUA binding. It is called with each sample-fetch.
3296 * It uses closure argument to store the associated sample-fetch. It
3297 * returns only one argument or throws an error. An error is thrown
3298 * only if an error is encountered during the argument parsing. If
3299 * the "sample-fetch" function fails, nil is returned.
3300 */
3301__LJMP static int hlua_run_sample_fetch(lua_State *L)
3302{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003303 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003304 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003305 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003306 int i;
3307 struct sample smp;
3308
3309 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003310 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003311
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003312 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003313 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003314
Thierry FOURNIERca988662015-12-20 18:43:03 +01003315 /* Check execution authorization. */
3316 if (f->use & SMP_USE_HTTP_ANY &&
3317 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3318 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3319 "is not available in Lua services", f->kw);
3320 WILL_LJMP(lua_error(L));
3321 }
3322
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003323 /* Get extra arguments. */
3324 for (i = 0; i < lua_gettop(L) - 1; i++) {
3325 if (i >= ARGM_NBARGS)
3326 break;
3327 hlua_lua2arg(L, i + 2, &args[i]);
3328 }
3329 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003330 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003331
3332 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003333 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003334
3335 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003336 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003337 lua_pushfstring(L, "error in arguments");
3338 WILL_LJMP(lua_error(L));
3339 }
3340
3341 /* Initialise the sample. */
3342 memset(&smp, 0, sizeof(smp));
3343
3344 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003345 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003346 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003347 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003348 lua_pushstring(L, "");
3349 else
3350 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003351 return 1;
3352 }
3353
3354 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003355 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003356 hlua_smp2lua_str(L, &smp);
3357 else
3358 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003359 return 1;
3360}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003361
3362/*
3363 *
3364 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003365 * Class Converters
3366 *
3367 *
3368 */
3369
3370/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003371 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003372 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003373__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003374{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003375 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003376}
3377
3378/* This function creates and push in the stack a Converters object
3379 * according with a current TXN.
3380 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003381static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003382{
Willy Tarreau7073c472015-04-06 11:15:40 +02003383 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003384
3385 /* Check stack size. */
3386 if (!lua_checkstack(L, 3))
3387 return 0;
3388
3389 /* Create the object: obj[0] = userdata.
3390 * Note that the base of the Converters object is the
3391 * same than the TXN object.
3392 */
3393 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003394 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003395 lua_rawseti(L, -2, 0);
3396
Willy Tarreau7073c472015-04-06 11:15:40 +02003397 hsmp->s = txn->s;
3398 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003399 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003400 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003401
Willy Tarreau87b09662015-04-03 00:22:06 +02003402 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003403 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3404 lua_setmetatable(L, -2);
3405
3406 return 1;
3407}
3408
3409/* This function is an LUA binding. It is called with each converter.
3410 * It uses closure argument to store the associated converter. It
3411 * returns only one argument or throws an error. An error is thrown
3412 * only if an error is encountered during the argument parsing. If
3413 * the converter function function fails, nil is returned.
3414 */
3415__LJMP static int hlua_run_sample_conv(lua_State *L)
3416{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003417 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003418 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003419 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003420 int i;
3421 struct sample smp;
3422
3423 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003424 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003425
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003426 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003427 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003428
3429 /* Get extra arguments. */
3430 for (i = 0; i < lua_gettop(L) - 2; i++) {
3431 if (i >= ARGM_NBARGS)
3432 break;
3433 hlua_lua2arg(L, i + 3, &args[i]);
3434 }
3435 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003436 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003437
3438 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003439 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003440
3441 /* Run the special args checker. */
3442 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3443 hlua_pusherror(L, "error in arguments");
3444 WILL_LJMP(lua_error(L));
3445 }
3446
3447 /* Initialise the sample. */
3448 if (!hlua_lua2smp(L, 2, &smp)) {
3449 hlua_pusherror(L, "error in the input argument");
3450 WILL_LJMP(lua_error(L));
3451 }
3452
Willy Tarreau1777ea62016-03-10 16:15:46 +01003453 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3454
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003455 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003456 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003457 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003458 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003459 WILL_LJMP(lua_error(L));
3460 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003461 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3462 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003463 hlua_pusherror(L, "error during the input argument casting");
3464 WILL_LJMP(lua_error(L));
3465 }
3466
3467 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003468 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003469 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003470 lua_pushstring(L, "");
3471 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003472 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003473 return 1;
3474 }
3475
3476 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003477 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003478 hlua_smp2lua_str(L, &smp);
3479 else
3480 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003481 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003482}
3483
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003484/*
3485 *
3486 *
3487 * Class AppletTCP
3488 *
3489 *
3490 */
3491
3492/* Returns a struct hlua_txn if the stack entry "ud" is
3493 * a class stream, otherwise it throws an error.
3494 */
3495__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3496{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003497 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003498}
3499
3500/* This function creates and push in the stack an Applet object
3501 * according with a current TXN.
3502 */
3503static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3504{
3505 struct hlua_appctx *appctx;
3506 struct stream_interface *si = ctx->owner;
3507 struct stream *s = si_strm(si);
3508 struct proxy *p = s->be;
3509
3510 /* Check stack size. */
3511 if (!lua_checkstack(L, 3))
3512 return 0;
3513
3514 /* Create the object: obj[0] = userdata.
3515 * Note that the base of the Converters object is the
3516 * same than the TXN object.
3517 */
3518 lua_newtable(L);
3519 appctx = lua_newuserdata(L, sizeof(*appctx));
3520 lua_rawseti(L, -2, 0);
3521 appctx->appctx = ctx;
3522 appctx->htxn.s = s;
3523 appctx->htxn.p = p;
3524
3525 /* Create the "f" field that contains a list of fetches. */
3526 lua_pushstring(L, "f");
3527 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3528 return 0;
3529 lua_settable(L, -3);
3530
3531 /* Create the "sf" field that contains a list of stringsafe fetches. */
3532 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003533 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003534 return 0;
3535 lua_settable(L, -3);
3536
3537 /* Create the "c" field that contains a list of converters. */
3538 lua_pushstring(L, "c");
3539 if (!hlua_converters_new(L, &appctx->htxn, 0))
3540 return 0;
3541 lua_settable(L, -3);
3542
3543 /* Create the "sc" field that contains a list of stringsafe converters. */
3544 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003545 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003546 return 0;
3547 lua_settable(L, -3);
3548
3549 /* Pop a class stream metatable and affect it to the table. */
3550 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3551 lua_setmetatable(L, -2);
3552
3553 return 1;
3554}
3555
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003556__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3557{
3558 struct hlua_appctx *appctx;
3559 struct stream *s;
3560 const char *name;
3561 size_t len;
3562 struct sample smp;
3563
3564 MAY_LJMP(check_args(L, 3, "set_var"));
3565
3566 /* It is useles to retrieve the stream, but this function
3567 * runs only in a stream context.
3568 */
3569 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3570 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3571 s = appctx->htxn.s;
3572
3573 /* Converts the third argument in a sample. */
3574 hlua_lua2smp(L, 3, &smp);
3575
3576 /* Store the sample in a variable. */
3577 smp_set_owner(&smp, s->be, s->sess, s, 0);
3578 vars_set_by_name(name, len, &smp);
3579 return 0;
3580}
3581
3582__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3583{
3584 struct hlua_appctx *appctx;
3585 struct stream *s;
3586 const char *name;
3587 size_t len;
3588 struct sample smp;
3589
3590 MAY_LJMP(check_args(L, 2, "unset_var"));
3591
3592 /* It is useles to retrieve the stream, but this function
3593 * runs only in a stream context.
3594 */
3595 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3596 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3597 s = appctx->htxn.s;
3598
3599 /* Unset the variable. */
3600 smp_set_owner(&smp, s->be, s->sess, s, 0);
3601 vars_unset_by_name(name, len, &smp);
3602 return 0;
3603}
3604
3605__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3606{
3607 struct hlua_appctx *appctx;
3608 struct stream *s;
3609 const char *name;
3610 size_t len;
3611 struct sample smp;
3612
3613 MAY_LJMP(check_args(L, 2, "get_var"));
3614
3615 /* It is useles to retrieve the stream, but this function
3616 * runs only in a stream context.
3617 */
3618 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3619 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3620 s = appctx->htxn.s;
3621
3622 smp_set_owner(&smp, s->be, s->sess, s, 0);
3623 if (!vars_get_by_name(name, len, &smp)) {
3624 lua_pushnil(L);
3625 return 1;
3626 }
3627
3628 return hlua_smp2lua(L, &smp);
3629}
3630
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003631__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3632{
3633 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3634 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003635 struct hlua *hlua;
3636
3637 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003638 if (!s->hlua)
3639 return 0;
3640 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003641
3642 MAY_LJMP(check_args(L, 2, "set_priv"));
3643
3644 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003645 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003646
3647 /* Get and store new value. */
3648 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3649 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3650
3651 return 0;
3652}
3653
3654__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3655{
3656 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3657 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003658 struct hlua *hlua;
3659
3660 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003661 if (!s->hlua) {
3662 lua_pushnil(L);
3663 return 1;
3664 }
3665 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003666
3667 /* Push configuration index in the stack. */
3668 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3669
3670 return 1;
3671}
3672
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003673/* If expected data not yet available, it returns a yield. This function
3674 * consumes the data in the buffer. It returns a string containing the
3675 * data. This string can be empty.
3676 */
3677__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3678{
3679 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3680 struct stream_interface *si = appctx->appctx->owner;
3681 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003682 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003683 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003684 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003685 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003686
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003687 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003688 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003689
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003690 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003691 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003692 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003693 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003694 }
3695
3696 /* End of data: commit the total strings and return. */
3697 if (ret < 0) {
3698 luaL_pushresult(&appctx->b);
3699 return 1;
3700 }
3701
3702 /* Ensure that the block 2 length is usable. */
3703 if (ret == 1)
3704 len2 = 0;
3705
3706 /* dont check the max length read and dont check. */
3707 luaL_addlstring(&appctx->b, blk1, len1);
3708 luaL_addlstring(&appctx->b, blk2, len2);
3709
3710 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003711 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003712 luaL_pushresult(&appctx->b);
3713 return 1;
3714}
3715
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003716/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003717__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3718{
3719 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3720
3721 /* Initialise the string catenation. */
3722 luaL_buffinit(L, &appctx->b);
3723
3724 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3725}
3726
3727/* If expected data not yet available, it returns a yield. This function
3728 * consumes the data in the buffer. It returns a string containing the
3729 * data. This string can be empty.
3730 */
3731__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3732{
3733 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3734 struct stream_interface *si = appctx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003735 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003736 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003737 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003738 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003739 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003740 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003741
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003742 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003743 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003744
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003745 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003746 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003747 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003748 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003749 }
3750
3751 /* End of data: commit the total strings and return. */
3752 if (ret < 0) {
3753 luaL_pushresult(&appctx->b);
3754 return 1;
3755 }
3756
3757 /* Ensure that the block 2 length is usable. */
3758 if (ret == 1)
3759 len2 = 0;
3760
3761 if (len == -1) {
3762
3763 /* If len == -1, catenate all the data avalaile and
3764 * yield because we want to get all the data until
3765 * the end of data stream.
3766 */
3767 luaL_addlstring(&appctx->b, blk1, len1);
3768 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003769 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003770 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003771 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003772
3773 } else {
3774
3775 /* Copy the fisrt block caping to the length required. */
3776 if (len1 > len)
3777 len1 = len;
3778 luaL_addlstring(&appctx->b, blk1, len1);
3779 len -= len1;
3780
3781 /* Copy the second block. */
3782 if (len2 > len)
3783 len2 = len;
3784 luaL_addlstring(&appctx->b, blk2, len2);
3785 len -= len2;
3786
3787 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003788 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003789
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003790 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003791 if (len > 0) {
3792 lua_pushinteger(L, len);
3793 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003794 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003795 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003796 }
3797
3798 /* return the result. */
3799 luaL_pushresult(&appctx->b);
3800 return 1;
3801 }
3802
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003803 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003804 hlua_pusherror(L, "Lua: internal error");
3805 WILL_LJMP(lua_error(L));
3806 return 0;
3807}
3808
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003809/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003810__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3811{
3812 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3813 int len = -1;
3814
3815 if (lua_gettop(L) > 2)
3816 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3817 if (lua_gettop(L) >= 2) {
3818 len = MAY_LJMP(luaL_checkinteger(L, 2));
3819 lua_pop(L, 1);
3820 }
3821
3822 /* Confirm or set the required length */
3823 lua_pushinteger(L, len);
3824
3825 /* Initialise the string catenation. */
3826 luaL_buffinit(L, &appctx->b);
3827
3828 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3829}
3830
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003831/* Append data in the output side of the buffer. This data is immediately
3832 * sent. The function returns the amount of data written. If the buffer
3833 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003834 * if the channel is closed.
3835 */
3836__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3837{
3838 size_t len;
3839 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3840 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3841 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3842 struct stream_interface *si = appctx->appctx->owner;
3843 struct channel *chn = si_ic(si);
3844 int max;
3845
3846 /* Get the max amount of data which can write as input in the channel. */
3847 max = channel_recv_max(chn);
3848 if (max > (len - l))
3849 max = len - l;
3850
3851 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003852 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003853
3854 /* update counters. */
3855 l += max;
3856 lua_pop(L, 1);
3857 lua_pushinteger(L, l);
3858
3859 /* If some data is not send, declares the situation to the
3860 * applet, and returns a yield.
3861 */
3862 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01003863 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003864 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003865 }
3866
3867 return 1;
3868}
3869
3870/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3871 * yield the LUA process, and resume it without checking the
3872 * input arguments.
3873 */
3874__LJMP static int hlua_applet_tcp_send(lua_State *L)
3875{
3876 MAY_LJMP(check_args(L, 2, "send"));
3877 lua_pushinteger(L, 0);
3878
3879 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3880}
3881
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003882/*
3883 *
3884 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003885 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003886 *
3887 *
3888 */
3889
3890/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003891 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003892 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003893__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003894{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003895 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003896}
3897
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003898/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003899 * according with a current TXN.
3900 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003901static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003902{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003903 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003904 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003905 struct stream_interface *si = ctx->owner;
3906 struct stream *s = si_strm(si);
3907 struct proxy *px = s->be;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003908
3909 /* Check stack size. */
3910 if (!lua_checkstack(L, 3))
3911 return 0;
3912
3913 /* Create the object: obj[0] = userdata.
3914 * Note that the base of the Converters object is the
3915 * same than the TXN object.
3916 */
3917 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003918 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003919 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003920 appctx->appctx = ctx;
3921 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003922 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003923 appctx->htxn.s = s;
3924 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003925
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003926 /* Create the "f" field that contains a list of fetches. */
3927 lua_pushstring(L, "f");
3928 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3929 return 0;
3930 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003931
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003932 /* Create the "sf" field that contains a list of stringsafe fetches. */
3933 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003934 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003935 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 "c" field that contains a list of converters. */
3939 lua_pushstring(L, "c");
3940 if (!hlua_converters_new(L, &appctx->htxn, 0))
3941 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 "sc" field that contains a list of stringsafe converters. */
3945 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003946 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003947 return 0;
3948 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003949
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003950 if (IS_HTX_STRM(s)) {
3951 /* HTX version */
3952 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet29f17582019-05-23 11:03:26 +02003953 struct htx_blk *blk;
3954 struct htx_sl *sl;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003955 struct ist path;
3956 unsigned long long len = 0;
3957 int32_t pos;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003958
Christopher Faulet29f17582019-05-23 11:03:26 +02003959 blk = htx_get_first_blk(htx);
3960 BUG_ON(htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
3961 sl = htx_get_blk_ptr(htx, blk);
3962
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003963 /* Stores the request method. */
3964 lua_pushstring(L, "method");
3965 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
3966 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003967
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003968 /* Stores the http version. */
3969 lua_pushstring(L, "version");
3970 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
3971 lua_settable(L, -3);
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003972
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003973 /* creates an array of headers. hlua_http_get_headers() crates and push
3974 * the array on the top of the stack.
3975 */
3976 lua_pushstring(L, "headers");
3977 htxn.s = s;
3978 htxn.p = px;
3979 htxn.dir = SMP_OPT_DIR_REQ;
3980 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3981 return 0;
3982 lua_settable(L, -3);
3983
3984 path = http_get_path(htx_sl_req_uri(sl));
3985 if (path.ptr) {
3986 char *p, *q, *end;
3987
3988 p = path.ptr;
3989 end = path.ptr + path.len;
3990 q = p;
3991 while (q < end && *q != '?')
3992 q++;
3993
3994 /* Stores the request path. */
3995 lua_pushstring(L, "path");
3996 lua_pushlstring(L, p, q - p);
3997 lua_settable(L, -3);
3998
3999 /* Stores the query string. */
4000 lua_pushstring(L, "qs");
4001 if (*q == '?')
4002 q++;
4003 lua_pushlstring(L, q, end - q);
4004 lua_settable(L, -3);
4005 }
4006
Christopher Fauleta3f15502019-05-13 15:27:23 +02004007 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004008 struct htx_blk *blk = htx_get_blk(htx, pos);
4009 enum htx_blk_type type = htx_get_blk_type(blk);
4010
Christopher Faulet54b5e212019-06-04 10:08:28 +02004011 if (type == HTX_BLK_EOM || type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004012 break;
4013 if (type == HTX_BLK_DATA)
4014 len += htx_get_blksz(blk);
4015 }
4016 if (htx->extra != ULLONG_MAX)
4017 len += htx->extra;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004018
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004019 /* Stores the request path. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004020 lua_pushstring(L, "length");
4021 lua_pushinteger(L, len);
4022 lua_settable(L, -3);
4023 }
4024 else {
4025 /* Legacy HTTP version */
4026 struct http_txn *txn = s->txn;
4027 const char *path;
4028 const char *end;
4029 const char *p;
4030
4031 /* Stores the request method. */
4032 lua_pushstring(L, "method");
4033 lua_pushlstring(L, ci_head(txn->req.chn), txn->req.sl.rq.m_l);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004034 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004035
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004036 /* Stores the http version. */
4037 lua_pushstring(L, "version");
4038 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 +01004039 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004040
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004041 /* creates an array of headers. hlua_http_get_headers() crates and push
4042 * the array on the top of the stack.
4043 */
4044 lua_pushstring(L, "headers");
4045 htxn.s = s;
4046 htxn.p = px;
4047 htxn.dir = SMP_OPT_DIR_REQ;
4048 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
4049 return 0;
4050 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004051
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004052 /* Get path and qs */
4053 path = http_txn_get_path(txn);
4054 if (path) {
4055 end = ci_head(txn->req.chn) + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
4056 p = path;
4057 while (p < end && *p != '?')
4058 p++;
4059
4060 /* Stores the request path. */
4061 lua_pushstring(L, "path");
4062 lua_pushlstring(L, path, p - path);
4063 lua_settable(L, -3);
4064
4065 /* Stores the query string. */
4066 lua_pushstring(L, "qs");
4067 if (*p == '?')
4068 p++;
4069 lua_pushlstring(L, p, end - p);
4070 lua_settable(L, -3);
4071 }
4072
4073 /* Stores the request path. */
4074 lua_pushstring(L, "length");
4075 lua_pushinteger(L, txn->req.body_len);
4076 lua_settable(L, -3);
4077 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004078
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004079 /* Create an empty array of HTTP request headers. */
4080 lua_pushstring(L, "response");
4081 lua_newtable(L);
4082 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004083
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004084 /* Pop a class stream metatable and affect it to the table. */
4085 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4086 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004087
4088 return 1;
4089}
4090
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004091__LJMP static int hlua_applet_http_set_var(lua_State *L)
4092{
4093 struct hlua_appctx *appctx;
4094 struct stream *s;
4095 const char *name;
4096 size_t len;
4097 struct sample smp;
4098
4099 MAY_LJMP(check_args(L, 3, "set_var"));
4100
4101 /* It is useles to retrieve the stream, but this function
4102 * runs only in a stream context.
4103 */
4104 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4105 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4106 s = appctx->htxn.s;
4107
4108 /* Converts the third argument in a sample. */
4109 hlua_lua2smp(L, 3, &smp);
4110
4111 /* Store the sample in a variable. */
4112 smp_set_owner(&smp, s->be, s->sess, s, 0);
4113 vars_set_by_name(name, len, &smp);
4114 return 0;
4115}
4116
4117__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4118{
4119 struct hlua_appctx *appctx;
4120 struct stream *s;
4121 const char *name;
4122 size_t len;
4123 struct sample smp;
4124
4125 MAY_LJMP(check_args(L, 2, "unset_var"));
4126
4127 /* It is useles to retrieve the stream, but this function
4128 * runs only in a stream context.
4129 */
4130 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4131 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4132 s = appctx->htxn.s;
4133
4134 /* Unset the variable. */
4135 smp_set_owner(&smp, s->be, s->sess, s, 0);
4136 vars_unset_by_name(name, len, &smp);
4137 return 0;
4138}
4139
4140__LJMP static int hlua_applet_http_get_var(lua_State *L)
4141{
4142 struct hlua_appctx *appctx;
4143 struct stream *s;
4144 const char *name;
4145 size_t len;
4146 struct sample smp;
4147
4148 MAY_LJMP(check_args(L, 2, "get_var"));
4149
4150 /* It is useles to retrieve the stream, but this function
4151 * runs only in a stream context.
4152 */
4153 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4154 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4155 s = appctx->htxn.s;
4156
4157 smp_set_owner(&smp, s->be, s->sess, s, 0);
4158 if (!vars_get_by_name(name, len, &smp)) {
4159 lua_pushnil(L);
4160 return 1;
4161 }
4162
4163 return hlua_smp2lua(L, &smp);
4164}
4165
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004166__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4167{
4168 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4169 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004170 struct hlua *hlua;
4171
4172 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004173 if (!s->hlua)
4174 return 0;
4175 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004176
4177 MAY_LJMP(check_args(L, 2, "set_priv"));
4178
4179 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004180 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004181
4182 /* Get and store new value. */
4183 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4184 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4185
4186 return 0;
4187}
4188
4189__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4190{
4191 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4192 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004193 struct hlua *hlua;
4194
4195 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004196 if (!s->hlua) {
4197 lua_pushnil(L);
4198 return 1;
4199 }
4200 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004201
4202 /* Push configuration index in the stack. */
4203 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4204
4205 return 1;
4206}
4207
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004208/* If expected data not yet available, it returns a yield. This function
4209 * consumes the data in the buffer. It returns a string containing the
4210 * data. This string can be empty.
4211 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004212__LJMP static int hlua_applet_htx_getline_yield(lua_State *L, int status, lua_KContext ctx)
4213{
4214 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4215 struct stream_interface *si = appctx->appctx->owner;
4216 struct channel *req = si_oc(si);
4217 struct htx *htx;
4218 struct htx_blk *blk;
4219 size_t count;
4220 int stop = 0;
4221
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004222 htx = htx_from_buf(&req->buf);
4223 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004224 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004225
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004226 while (count && !stop && blk) {
4227 enum htx_blk_type type = htx_get_blk_type(blk);
4228 uint32_t sz = htx_get_blksz(blk);
4229 struct ist v;
4230 uint32_t vlen;
4231 char *nl;
4232
Christopher Faulete461e342018-12-18 16:43:35 +01004233 if (type == HTX_BLK_EOM) {
4234 stop = 1;
4235 break;
4236 }
4237
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004238 vlen = sz;
4239 if (vlen > count) {
4240 if (type != HTX_BLK_DATA)
4241 break;
4242 vlen = count;
4243 }
4244
4245 switch (type) {
4246 case HTX_BLK_UNUSED:
4247 break;
4248
4249 case HTX_BLK_DATA:
4250 v = htx_get_blk_value(htx, blk);
4251 v.len = vlen;
4252 nl = istchr(v, '\n');
4253 if (nl != NULL) {
4254 stop = 1;
4255 vlen = nl - v.ptr + 1;
4256 }
4257 luaL_addlstring(&appctx->b, v.ptr, vlen);
4258 break;
4259
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004260 case HTX_BLK_TLR:
4261 case HTX_BLK_EOM:
4262 stop = 1;
4263 break;
4264
4265 default:
4266 break;
4267 }
4268
4269 co_set_data(req, co_data(req) - vlen);
4270 count -= vlen;
4271 if (sz == vlen)
4272 blk = htx_remove_blk(htx, blk);
4273 else {
4274 htx_cut_data_blk(htx, blk, vlen);
4275 break;
4276 }
4277 }
4278
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004279 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004280 if (!stop) {
4281 si_cant_get(si);
4282 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_getline_yield, TICK_ETERNITY, 0));
4283 }
4284
4285 /* return the result. */
4286 luaL_pushresult(&appctx->b);
4287 return 1;
4288}
4289
4290
4291/* If expected data not yet available, it returns a yield. This function
4292 * consumes the data in the buffer. It returns a string containing the
4293 * data. This string can be empty.
4294 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004295__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004296{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004297 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4298 struct stream_interface *si = appctx->appctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004299 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004300 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004301 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004302 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004303 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004304
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004305 /* Check for the end of the data. */
4306 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4307 luaL_pushresult(&appctx->b);
4308 return 1;
4309 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004310
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004311 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004312 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004313
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004314 /* Data not yet available. return yield. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004315 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004316 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004317 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004318 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004319
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004320 /* End of data: commit the total strings and return. */
4321 if (ret < 0) {
4322 luaL_pushresult(&appctx->b);
4323 return 1;
4324 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004325
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004326 /* Ensure that the block 2 length is usable. */
4327 if (ret == 1)
4328 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004329
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004330 /* Copy the fisrt block caping to the length required. */
4331 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4332 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4333 luaL_addlstring(&appctx->b, blk1, len1);
4334 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004335
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004336 /* Copy the second block. */
4337 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4338 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4339 luaL_addlstring(&appctx->b, blk2, len2);
4340 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004341
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004342 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004343 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004344 luaL_pushresult(&appctx->b);
4345 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004346}
4347
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004348/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004349__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004350{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004351 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004352
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004353 /* Initialise the string catenation. */
4354 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004355
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004356 if (IS_HTX_STRM(si_strm(appctx->appctx->owner)))
4357 return MAY_LJMP(hlua_applet_htx_getline_yield(L, 0, 0));
4358 else
4359 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004360}
4361
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004362/* If expected data not yet available, it returns a yield. This function
4363 * consumes the data in the buffer. It returns a string containing the
4364 * data. This string can be empty.
4365 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004366__LJMP static int hlua_applet_htx_recv_yield(lua_State *L, int status, lua_KContext ctx)
4367{
4368 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4369 struct stream_interface *si = appctx->appctx->owner;
4370 struct channel *req = si_oc(si);
4371 struct htx *htx;
4372 struct htx_blk *blk;
4373 size_t count;
4374 int len;
4375
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004376 htx = htx_from_buf(&req->buf);
4377 len = MAY_LJMP(luaL_checkinteger(L, 2));
4378 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02004379 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004380 while (count && len && blk) {
4381 enum htx_blk_type type = htx_get_blk_type(blk);
4382 uint32_t sz = htx_get_blksz(blk);
4383 struct ist v;
4384 uint32_t vlen;
4385
Christopher Faulete461e342018-12-18 16:43:35 +01004386 if (type == HTX_BLK_EOM) {
4387 len = 0;
4388 break;
4389 }
4390
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004391 vlen = sz;
4392 if (len > 0 && vlen > len)
4393 vlen = len;
4394 if (vlen > count) {
4395 if (type != HTX_BLK_DATA)
4396 break;
4397 vlen = count;
4398 }
4399
4400 switch (type) {
4401 case HTX_BLK_UNUSED:
4402 break;
4403
4404 case HTX_BLK_DATA:
4405 v = htx_get_blk_value(htx, blk);
4406 luaL_addlstring(&appctx->b, v.ptr, vlen);
4407 break;
4408
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004409 case HTX_BLK_TLR:
4410 case HTX_BLK_EOM:
4411 len = 0;
4412 break;
4413
4414 default:
4415 break;
4416 }
4417
4418 co_set_data(req, co_data(req) - vlen);
4419 count -= vlen;
4420 if (len > 0)
4421 len -= vlen;
4422 if (sz == vlen)
4423 blk = htx_remove_blk(htx, blk);
4424 else {
4425 htx_cut_data_blk(htx, blk, vlen);
4426 break;
4427 }
4428 }
4429
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004430 htx_to_buf(htx, &req->buf);
4431
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004432 /* If we are no other data available, yield waiting for new data. */
4433 if (len) {
4434 if (len > 0) {
4435 lua_pushinteger(L, len);
4436 lua_replace(L, 2);
4437 }
4438 si_cant_get(si);
4439 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_recv_yield, TICK_ETERNITY, 0));
4440 }
4441
4442 /* return the result. */
4443 luaL_pushresult(&appctx->b);
4444 return 1;
4445}
4446
4447/* If expected data not yet available, it returns a yield. This function
4448 * consumes the data in the buffer. It returns a string containing the
4449 * data. This string can be empty.
4450 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004451__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004452{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004453 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4454 struct stream_interface *si = appctx->appctx->owner;
4455 int len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004456 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004457 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004458 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004459 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004460 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004461
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004462 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004463 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004464
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004465 /* Data not yet available. return yield. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004466 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004467 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004468 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004469 }
4470
4471 /* End of data: commit the total strings and return. */
4472 if (ret < 0) {
4473 luaL_pushresult(&appctx->b);
4474 return 1;
4475 }
4476
4477 /* Ensure that the block 2 length is usable. */
4478 if (ret == 1)
4479 len2 = 0;
4480
4481 /* Copy the fisrt block caping to the length required. */
4482 if (len1 > len)
4483 len1 = len;
4484 luaL_addlstring(&appctx->b, blk1, len1);
4485 len -= len1;
4486
4487 /* Copy the second block. */
4488 if (len2 > len)
4489 len2 = len;
4490 luaL_addlstring(&appctx->b, blk2, len2);
4491 len -= len2;
4492
4493 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004494 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004495 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4496 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4497
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004498 /* If we are no other data available, yield waiting for new data. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004499 if (len > 0) {
4500 lua_pushinteger(L, len);
4501 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004502 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004503 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004504 }
4505
4506 /* return the result. */
4507 luaL_pushresult(&appctx->b);
4508 return 1;
4509}
4510
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004511/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004512__LJMP static int hlua_applet_http_recv(lua_State *L)
4513{
4514 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4515 int len = -1;
4516
4517 /* Check arguments. */
4518 if (lua_gettop(L) > 2)
4519 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4520 if (lua_gettop(L) >= 2) {
4521 len = MAY_LJMP(luaL_checkinteger(L, 2));
4522 lua_pop(L, 1);
4523 }
4524
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004525 if (IS_HTX_STRM(si_strm(appctx->appctx->owner))) {
4526 /* HTX version */
4527 lua_pushinteger(L, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004528
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004529 /* Initialise the string catenation. */
4530 luaL_buffinit(L, &appctx->b);
4531
4532 return MAY_LJMP(hlua_applet_htx_recv_yield(L, 0, 0));
4533 }
4534 else {
4535 /* Legacy HTTP version */
4536 /* Check the required length */
4537 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4538 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4539 lua_pushinteger(L, len);
4540
4541 /* Initialise the string catenation. */
4542 luaL_buffinit(L, &appctx->b);
4543
4544 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4545 }
4546}
4547
4548/* Append data in the output side of the buffer. This data is immediately
4549 * sent. The function returns the amount of data written. If the buffer
4550 * cannot contain the data, the function yields. The function returns -1
4551 * if the channel is closed.
4552 */
4553__LJMP static int hlua_applet_htx_send_yield(lua_State *L, int status, lua_KContext ctx)
4554{
4555 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4556 struct stream_interface *si = appctx->appctx->owner;
4557 struct channel *res = si_ic(si);
4558 struct htx *htx = htx_from_buf(&res->buf);
4559 const char *data;
4560 size_t len;
4561 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4562 int max;
4563
Christopher Faulet4e963012019-07-03 11:39:30 +02004564 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004565 if (!max)
4566 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004567
4568 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
4569
4570 /* Get the max amount of data which can write as input in the channel. */
4571 if (max > (len - l))
4572 max = len - l;
4573
4574 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02004575 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004576 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004577
4578 /* update counters. */
4579 l += max;
4580 lua_pop(L, 1);
4581 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004582
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004583 /* If some data is not send, declares the situation to the
4584 * applet, and returns a yield.
4585 */
4586 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004587 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004588 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004589 si_rx_room_blk(si);
4590 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_send_yield, TICK_ETERNITY, 0));
4591 }
4592
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004593 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004594 return 1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004595}
4596
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004597/* Append data in the output side of the buffer. This data is immediately
4598 * sent. The function returns the amount of data written. If the buffer
4599 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004600 * if the channel is closed.
4601 */
4602__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4603{
4604 size_t len;
4605 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4606 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4607 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4608 struct stream_interface *si = appctx->appctx->owner;
4609 struct channel *chn = si_ic(si);
4610 int max;
4611
4612 /* Get the max amount of data which can write as input in the channel. */
4613 max = channel_recv_max(chn);
4614 if (max > (len - l))
4615 max = len - l;
4616
4617 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004618 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004619
4620 /* update counters. */
4621 l += max;
4622 lua_pop(L, 1);
4623 lua_pushinteger(L, l);
4624
4625 /* If some data is not send, declares the situation to the
4626 * applet, and returns a yield.
4627 */
4628 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004629 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004630 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004631 }
4632
4633 return 1;
4634}
4635
4636/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4637 * yield the LUA process, and resume it without checking the
4638 * input arguments.
4639 */
4640__LJMP static int hlua_applet_http_send(lua_State *L)
4641{
4642 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004643
4644 /* We want to send some data. Headers must be sent. */
4645 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4646 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4647 WILL_LJMP(lua_error(L));
4648 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004649
4650 if (IS_HTX_STRM(si_strm(appctx->appctx->owner))) {
4651 /* HTX version */
4652 /* This interger is used for followinf the amount of data sent. */
4653 lua_pushinteger(L, 0);
4654
4655 return MAY_LJMP(hlua_applet_htx_send_yield(L, 0, 0));
4656 }
4657 else {
4658 /* Legacy HTTP version */
4659 size_t len;
4660 char hex[10];
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004661
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004662 MAY_LJMP(luaL_checklstring(L, 2, &len));
4663
4664 /* If transfer encoding chunked is selected, we surround the data
4665 * by chunk data.
4666 */
4667 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4668 snprintf(hex, 9, "%x", (unsigned int)len);
4669 lua_pushfstring(L, "%s\r\n", hex);
4670 lua_insert(L, 2); /* swap the last 2 entries. */
4671 lua_pushstring(L, "\r\n");
4672 lua_concat(L, 3);
4673 }
4674
4675 /* This interger is used for followinf the amount of data sent. */
4676 lua_pushinteger(L, 0);
4677
4678 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4679 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004680}
4681
4682__LJMP static int hlua_applet_http_addheader(lua_State *L)
4683{
4684 const char *name;
4685 int ret;
4686
4687 MAY_LJMP(hlua_checkapplet_http(L, 1));
4688 name = MAY_LJMP(luaL_checkstring(L, 2));
4689 MAY_LJMP(luaL_checkstring(L, 3));
4690
4691 /* Push in the stack the "response" entry. */
4692 ret = lua_getfield(L, 1, "response");
4693 if (ret != LUA_TTABLE) {
4694 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4695 "is expected as an array. %s found", lua_typename(L, ret));
4696 WILL_LJMP(lua_error(L));
4697 }
4698
4699 /* check if the header is already registered if it is not
4700 * the case, register it.
4701 */
4702 ret = lua_getfield(L, -1, name);
4703 if (ret == LUA_TNIL) {
4704
4705 /* Entry not found. */
4706 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4707
4708 /* Insert the new header name in the array in the top of the stack.
4709 * It left the new array in the top of the stack.
4710 */
4711 lua_newtable(L);
4712 lua_pushvalue(L, 2);
4713 lua_pushvalue(L, -2);
4714 lua_settable(L, -4);
4715
4716 } else if (ret != LUA_TTABLE) {
4717
4718 /* corruption error. */
4719 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4720 "is expected as an array. %s found", name, lua_typename(L, ret));
4721 WILL_LJMP(lua_error(L));
4722 }
4723
4724 /* Now the top od thestack is an array of values. We push
4725 * the header value as new entry.
4726 */
4727 lua_pushvalue(L, 3);
4728 ret = lua_rawlen(L, -2);
4729 lua_rawseti(L, -2, ret + 1);
4730 lua_pushboolean(L, 1);
4731 return 1;
4732}
4733
4734__LJMP static int hlua_applet_http_status(lua_State *L)
4735{
4736 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4737 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004738 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004739
4740 if (status < 100 || status > 599) {
4741 lua_pushboolean(L, 0);
4742 return 1;
4743 }
4744
4745 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004746 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004747 lua_pushboolean(L, 1);
4748 return 1;
4749}
4750
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004751
4752__LJMP static int hlua_applet_htx_send_response(lua_State *L)
4753{
4754 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4755 struct stream_interface *si = appctx->appctx->owner;
4756 struct channel *res = si_ic(si);
4757 struct htx *htx;
4758 struct htx_sl *sl;
4759 struct h1m h1m;
4760 const char *status, *reason;
4761 const char *name, *value;
4762 size_t nlen, vlen;
4763 unsigned int flags;
4764
4765 /* Send the message at once. */
4766 htx = htx_from_buf(&res->buf);
4767 h1m_init_res(&h1m);
4768
4769 /* Use the same http version than the request. */
4770 status = ultoa_r(appctx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
4771 reason = appctx->appctx->ctx.hlua_apphttp.reason;
4772 if (reason == NULL)
4773 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
4774 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
4775 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
4776 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
4777 }
4778 else {
4779 flags = HTX_SL_F_IS_RESP;
4780 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
4781 }
4782 if (!sl) {
4783 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
4784 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4785 WILL_LJMP(lua_error(L));
4786 }
4787 sl->info.res.status = appctx->appctx->ctx.hlua_apphttp.status;
4788
4789 /* Get the array associated to the field "response" in the object AppletHTTP. */
4790 lua_pushvalue(L, 0);
4791 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4792 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4793 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4794 WILL_LJMP(lua_error(L));
4795 }
4796
4797 /* Browse the list of headers. */
4798 lua_pushnil(L);
4799 while(lua_next(L, -2) != 0) {
4800 /* We expect a string as -2. */
4801 if (lua_type(L, -2) != LUA_TSTRING) {
4802 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4803 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4804 lua_typename(L, lua_type(L, -2)));
4805 WILL_LJMP(lua_error(L));
4806 }
4807 name = lua_tolstring(L, -2, &nlen);
4808
4809 /* We expect an array as -1. */
4810 if (lua_type(L, -1) != LUA_TTABLE) {
4811 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4812 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4813 name,
4814 lua_typename(L, lua_type(L, -1)));
4815 WILL_LJMP(lua_error(L));
4816 }
4817
4818 /* Browse the table who is on the top of the stack. */
4819 lua_pushnil(L);
4820 while(lua_next(L, -2) != 0) {
4821 int id;
4822
4823 /* We expect a number as -2. */
4824 if (lua_type(L, -2) != LUA_TNUMBER) {
4825 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4826 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4827 name,
4828 lua_typename(L, lua_type(L, -2)));
4829 WILL_LJMP(lua_error(L));
4830 }
4831 id = lua_tointeger(L, -2);
4832
4833 /* We expect a string as -2. */
4834 if (lua_type(L, -1) != LUA_TSTRING) {
4835 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4836 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4837 name, id,
4838 lua_typename(L, lua_type(L, -1)));
4839 WILL_LJMP(lua_error(L));
4840 }
4841 value = lua_tolstring(L, -1, &vlen);
4842
4843 /* Simple Protocol checks. */
4844 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
4845 h1_parse_xfer_enc_header(&h1m, ist2(name, nlen));
4846 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
4847 struct ist v = ist2(value, vlen);
4848 int ret;
4849
4850 ret = h1_parse_cont_len_header(&h1m, &v);
4851 if (ret < 0) {
4852 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
4853 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4854 name);
4855 WILL_LJMP(lua_error(L));
4856 }
4857 else if (ret == 0)
4858 goto next; /* Skip it */
4859 }
4860
4861 /* Add a new header */
4862 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
4863 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
4864 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4865 name);
4866 WILL_LJMP(lua_error(L));
4867 }
4868 next:
4869 /* Remove the array from the stack, and get next element with a remaining string. */
4870 lua_pop(L, 1);
4871 }
4872
4873 /* Remove the array from the stack, and get next element with a remaining string. */
4874 lua_pop(L, 1);
4875 }
4876
4877 if (h1m.flags & H1_MF_CHNK)
4878 h1m.flags &= ~H1_MF_CLEN;
4879 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
4880 h1m.flags |= H1_MF_XFER_LEN;
4881
4882 /* Uset HTX start-line flags */
4883 if (h1m.flags & H1_MF_XFER_ENC)
4884 flags |= HTX_SL_F_XFER_ENC;
4885 if (h1m.flags & H1_MF_XFER_LEN) {
4886 flags |= HTX_SL_F_XFER_LEN;
4887 if (h1m.flags & H1_MF_CHNK)
4888 flags |= HTX_SL_F_CHNK;
4889 else if (h1m.flags & H1_MF_CLEN)
4890 flags |= HTX_SL_F_CLEN;
4891 if (h1m.body_len == 0)
4892 flags |= HTX_SL_F_BODYLESS;
4893 }
4894 sl->flags |= flags;
4895
4896 /* If we dont have a content-length set, and the HTTP version is 1.1
4897 * and the status code implies the presence of a message body, we must
4898 * announce a transfer encoding chunked. This is required by haproxy
4899 * for the keepalive compliance. If the applet annouces a transfer-encoding
4900 * chunked itslef, don't do anything.
4901 */
4902 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
4903 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4904 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4905 appctx->appctx->ctx.hlua_apphttp.status != 304) {
4906 /* Add a new header */
4907 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
4908 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
4909 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
4910 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4911 WILL_LJMP(lua_error(L));
4912 }
4913 }
4914
4915 /* Finalize headers. */
4916 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
4917 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
4918 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4919 WILL_LJMP(lua_error(L));
4920 }
4921
4922 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
4923 b_reset(&res->buf);
4924 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4925 WILL_LJMP(lua_error(L));
4926 }
4927
4928 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004929 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004930
4931 /* Headers sent, set the flag. */
4932 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4933 return 0;
4934
4935}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004936/* We will build the status line and the headers of the HTTP response.
4937 * We will try send at once if its not possible, we give back the hand
4938 * waiting for more room.
4939 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004940__LJMP static int hlua_applet_htx_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4941{
4942 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4943 struct stream_interface *si = appctx->appctx->owner;
4944 struct channel *res = si_ic(si);
4945
4946 if (co_data(res)) {
4947 si_rx_room_blk(si);
4948 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_start_response_yield, TICK_ETERNITY, 0));
4949 }
4950 return MAY_LJMP(hlua_applet_htx_send_response(L));
4951}
4952
4953
4954__LJMP static int hlua_applet_htx_start_response(lua_State *L)
4955{
4956 return MAY_LJMP(hlua_applet_htx_start_response_yield(L, 0, 0));
4957}
4958
4959/* We will build the status line and the headers of the HTTP response.
4960 * We will try send at once if its not possible, we give back the hand
4961 * waiting for more room.
4962 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004963__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4964{
4965 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4966 struct stream_interface *si = appctx->appctx->owner;
4967 struct channel *chn = si_ic(si);
4968 int ret;
4969 size_t len;
4970 const char *msg;
4971
4972 /* Get the message as the first argument on the stack. */
4973 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4974
4975 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004976 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004977
4978 /* if ret == -2 or -3 the channel closed or the message si too
4979 * big for the buffers.
4980 */
4981 if (ret == -2 || ret == -3) {
4982 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4983 WILL_LJMP(lua_error(L));
4984 }
4985
4986 /* If ret is -1, we dont have room in the buffer, so we yield. */
4987 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004988 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004989 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004990 }
4991
4992 /* Headers sent, set the flag. */
4993 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4994 return 0;
4995}
4996
4997__LJMP static int hlua_applet_http_start_response(lua_State *L)
4998{
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004999 struct buffer *tmp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005000 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005001 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02005002 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005003 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02005004 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005005 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005006 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005007 int hdr_chunked = 0;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005008 const char *reason;
5009
5010 if (IS_HTX_STRM(si_strm(appctx->appctx->owner)))
5011 return MAY_LJMP(hlua_applet_htx_start_response(L));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005012
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005013 reason = appctx->appctx->ctx.hlua_apphttp.reason;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005014 if (reason == NULL)
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02005015 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005016
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005017 tmp = get_trash_chunk();
5018
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005019 /* Use the same http version than the request. */
5020 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01005021 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005022 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005023 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005024
5025 /* Get the array associated to the field "response" in the object AppletHTTP. */
5026 lua_pushvalue(L, 0);
5027 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5028 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
5029 appctx->appctx->rule->arg.hlua_rule->fcn.name);
5030 WILL_LJMP(lua_error(L));
5031 }
5032
5033 /* Browse the list of headers. */
5034 lua_pushnil(L);
5035 while(lua_next(L, -2) != 0) {
5036
5037 /* We expect a string as -2. */
5038 if (lua_type(L, -2) != LUA_TSTRING) {
5039 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
5040 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5041 lua_typename(L, lua_type(L, -2)));
5042 WILL_LJMP(lua_error(L));
5043 }
Willy Tarreaua3294632017-08-23 11:24:47 +02005044 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005045
5046 /* We expect an array as -1. */
5047 if (lua_type(L, -1) != LUA_TTABLE) {
5048 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
5049 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5050 name,
5051 lua_typename(L, lua_type(L, -1)));
5052 WILL_LJMP(lua_error(L));
5053 }
5054
5055 /* Browse the table who is on the top of the stack. */
5056 lua_pushnil(L);
5057 while(lua_next(L, -2) != 0) {
5058
5059 /* We expect a number as -2. */
5060 if (lua_type(L, -2) != LUA_TNUMBER) {
5061 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
5062 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5063 name,
5064 lua_typename(L, lua_type(L, -2)));
5065 WILL_LJMP(lua_error(L));
5066 }
5067 id = lua_tointeger(L, -2);
5068
5069 /* We expect a string as -2. */
5070 if (lua_type(L, -1) != LUA_TSTRING) {
5071 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
5072 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5073 name, id,
5074 lua_typename(L, lua_type(L, -1)));
5075 WILL_LJMP(lua_error(L));
5076 }
Willy Tarreaua3294632017-08-23 11:24:47 +02005077 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005078
5079 /* Catenate a new header. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005080 if (tmp->data + name_len + 2 + value_len + 2 < tmp->size) {
5081 memcpy(tmp->area + tmp->data, name, name_len);
5082 tmp->data += name_len;
5083 tmp->area[tmp->data++] = ':';
5084 tmp->area[tmp->data++] = ' ';
Willy Tarreaua3294632017-08-23 11:24:47 +02005085
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005086 memcpy(tmp->area + tmp->data, value,
5087 value_len);
5088 tmp->data += value_len;
5089 tmp->area[tmp->data++] = '\r';
5090 tmp->area[tmp->data++] = '\n';
Willy Tarreaua3294632017-08-23 11:24:47 +02005091 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005092
5093 /* Protocol checks. */
5094
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005095 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005096 * is done without control. If it contains a bad value,
5097 * the content-length remains negative so that we can
5098 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005099 */
Willy Tarreaua3294632017-08-23 11:24:47 +02005100 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005101 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005102
5103 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02005104 if (name_len == 17 && value_len == 7 &&
5105 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005106 strcasecmp("chunked", value) == 0)
5107 hdr_chunked = 1;
5108
5109 /* Remove the array from the stack, and get next element with a remaining string. */
5110 lua_pop(L, 1);
5111 }
5112
5113 /* Remove the array from the stack, and get next element with a remaining string. */
5114 lua_pop(L, 1);
5115 }
5116
Willy Tarreau06c75fe2017-08-23 09:10:38 +02005117 /* If we dont have a content-length set, and the HTTP version is 1.1
5118 * and the status code implies the presence of a message body, we must
5119 * announce a transfer encoding chunked. This is required by haproxy
5120 * for the keepalive compliance. If the applet annouces a transfer-encoding
5121 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005122 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005123 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02005124 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
5125 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
5126 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
5127 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005128 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
5129 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
5130 }
5131
5132 /* Finalize headers. */
5133 chunk_appendf(tmp, "\r\n");
5134
5135 /* Remove the last entry and the array of headers */
5136 lua_pop(L, 2);
5137
5138 /* Push the headers block. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005139 lua_pushlstring(L, tmp->area, tmp->data);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005140
5141 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
5142}
5143
5144/*
5145 *
5146 *
5147 * Class HTTP
5148 *
5149 *
5150 */
5151
5152/* Returns a struct hlua_txn if the stack entry "ud" is
5153 * a class stream, otherwise it throws an error.
5154 */
5155__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
5156{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005157 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005158}
5159
5160/* This function creates and push in the stack a HTTP object
5161 * according with a current TXN.
5162 */
5163static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5164{
5165 struct hlua_txn *htxn;
5166
5167 /* Check stack size. */
5168 if (!lua_checkstack(L, 3))
5169 return 0;
5170
5171 /* Create the object: obj[0] = userdata.
5172 * Note that the base of the Converters object is the
5173 * same than the TXN object.
5174 */
5175 lua_newtable(L);
5176 htxn = lua_newuserdata(L, sizeof(*htxn));
5177 lua_rawseti(L, -2, 0);
5178
5179 htxn->s = txn->s;
5180 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005181 htxn->dir = txn->dir;
5182 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005183
5184 /* Pop a class stream metatable and affect it to the table. */
5185 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5186 lua_setmetatable(L, -2);
5187
5188 return 1;
5189}
5190
5191/* This function creates ans returns an array of HTTP headers.
5192 * This function does not fails. It is used as wrapper with the
5193 * 2 following functions.
5194 */
5195__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5196{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005197 /* Create the table. */
5198 lua_newtable(L);
5199
5200 if (!htxn->s->txn)
5201 return 1;
5202
Christopher Faulet724a12c2018-12-13 22:12:15 +01005203 if (IS_HTX_STRM(htxn->s)) {
5204 /* HTX version */
5205 struct htx *htx = htxbuf(&msg->chn->buf);
5206 int32_t pos;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005207
Christopher Fauleta3f15502019-05-13 15:27:23 +02005208 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet724a12c2018-12-13 22:12:15 +01005209 struct htx_blk *blk = htx_get_blk(htx, pos);
5210 enum htx_blk_type type = htx_get_blk_type(blk);
5211 struct ist n, v;
5212 int len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005213
Christopher Faulet724a12c2018-12-13 22:12:15 +01005214 if (type == HTX_BLK_HDR) {
5215 n = htx_get_blk_name(htx,blk);
5216 v = htx_get_blk_value(htx, blk);
5217 }
5218 else if (type == HTX_BLK_EOH)
5219 break;
5220 else
5221 continue;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005222
Christopher Faulet724a12c2018-12-13 22:12:15 +01005223 /* Check for existing entry:
5224 * assume that the table is on the top of the stack, and
5225 * push the key in the stack, the function lua_gettable()
5226 * perform the lookup.
5227 */
5228 lua_pushlstring(L, n.ptr, n.len);
5229 lua_gettable(L, -2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005230
Christopher Faulet724a12c2018-12-13 22:12:15 +01005231 switch (lua_type(L, -1)) {
5232 case LUA_TNIL:
5233 /* Table not found, create it. */
5234 lua_pop(L, 1); /* remove the nil value. */
5235 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5236 lua_newtable(L); /* create and push empty table. */
5237 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5238 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5239 lua_rawset(L, -3); /* index new table with header name (pop the values). */
5240 break;
5241
5242 case LUA_TTABLE:
5243 /* Entry found: push the value in the table. */
5244 len = lua_rawlen(L, -1);
5245 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5246 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5247 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5248 break;
5249
5250 default:
5251 /* Other cases are errors. */
5252 hlua_pusherror(L, "internal error during the parsing of headers.");
5253 WILL_LJMP(lua_error(L));
5254 }
5255 }
5256 }
5257 else {
5258 /* Legacy HTTP version */
5259 const char *cur_ptr, *cur_next, *p;
5260 int old_idx, cur_idx;
5261 struct hdr_idx_elem *cur_hdr;
5262 const char *hn, *hv;
5263 int hnl, hvl;
5264 const char *in;
5265 char *out;
5266 int len;
5267
5268 /* Build array of headers. */
5269 old_idx = 0;
5270 cur_next = ci_head(msg->chn) + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
5271
5272 while (1) {
5273 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
5274 if (!cur_idx)
5275 break;
5276 old_idx = cur_idx;
5277
5278 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
5279 cur_ptr = cur_next;
5280 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
5281
5282 /* Now we have one full header at cur_ptr of len cur_hdr->len,
5283 * and the next header starts at cur_next. We'll check
5284 * this header in the list as well as against the default
5285 * rule.
5286 */
5287
5288 /* look for ': *'. */
5289 hn = cur_ptr;
5290 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
5291 if (p >= cur_ptr+cur_hdr->len)
5292 continue;
5293 hnl = p - hn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005294 p++;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005295 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
5296 p++;
5297 if (p >= cur_ptr+cur_hdr->len)
5298 continue;
5299 hv = p;
5300 hvl = cur_ptr+cur_hdr->len-p;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005301
Christopher Faulet724a12c2018-12-13 22:12:15 +01005302 /* Lowercase the key. Don't check the size of trash, it have
5303 * the size of one buffer and the input data contains in one
5304 * buffer.
5305 */
5306 out = trash.area;
5307 for (in=hn; in<hn+hnl; in++, out++)
5308 *out = tolower(*in);
5309 *out = '\0';
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005310
Christopher Faulet724a12c2018-12-13 22:12:15 +01005311 /* Check for existing entry:
5312 * assume that the table is on the top of the stack, and
5313 * push the key in the stack, the function lua_gettable()
5314 * perform the lookup.
5315 */
5316 lua_pushlstring(L, trash.area, hnl);
5317 lua_gettable(L, -2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005318
Christopher Faulet724a12c2018-12-13 22:12:15 +01005319 switch (lua_type(L, -1)) {
5320 case LUA_TNIL:
5321 /* Table not found, create it. */
5322 lua_pop(L, 1); /* remove the nil value. */
5323 lua_pushlstring(L, trash.area, hnl); /* push the header name as key. */
5324 lua_newtable(L); /* create and push empty table. */
5325 lua_pushlstring(L, hv, hvl); /* push header value. */
5326 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5327 lua_rawset(L, -3); /* index new table with header name (pop the values). */
5328 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005329
Christopher Faulet724a12c2018-12-13 22:12:15 +01005330 case LUA_TTABLE:
5331 /* Entry found: push the value in the table. */
5332 len = lua_rawlen(L, -1);
5333 lua_pushlstring(L, hv, hvl); /* push header value. */
5334 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5335 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5336 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005337
Christopher Faulet724a12c2018-12-13 22:12:15 +01005338 default:
5339 /* Other cases are errors. */
5340 hlua_pusherror(L, "internal error during the parsing of headers.");
5341 WILL_LJMP(lua_error(L));
5342 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005343 }
5344 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005345 return 1;
5346}
5347
5348__LJMP static int hlua_http_req_get_headers(lua_State *L)
5349{
5350 struct hlua_txn *htxn;
5351
5352 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5353 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5354
Christopher Faulet2351ca22019-07-26 16:31:34 +02005355 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005356 WILL_LJMP(lua_error(L));
5357
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005358 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
5359}
5360
5361__LJMP static int hlua_http_res_get_headers(lua_State *L)
5362{
5363 struct hlua_txn *htxn;
5364
5365 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5366 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5367
Christopher Faulet2351ca22019-07-26 16:31:34 +02005368 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005369 WILL_LJMP(lua_error(L));
5370
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005371 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
5372}
5373
5374/* This function replace full header, or just a value in
5375 * the request or in the response. It is a wrapper fir the
5376 * 4 following functions.
5377 */
5378__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
5379 struct http_msg *msg, int action)
5380{
5381 size_t name_len;
5382 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5383 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5384 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Dragan Dosen26743032019-04-30 15:54:36 +02005385 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005386
Dragan Dosen26743032019-04-30 15:54:36 +02005387 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005388 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5389
Christopher Faulet5a8549e2019-06-17 13:36:06 +02005390 if (IS_HTX_STRM(htxn->s)) {
5391 struct htx *htx = htxbuf(&msg->chn->buf);
5392
5393 htx_transform_header_str(htxn->s, msg->chn, htx, ist2(name, name_len), value, re, action);
5394 }
5395 else
5396 http_transform_header_str(htxn->s, msg, name, name_len, value, re, action);
Dragan Dosen26743032019-04-30 15:54:36 +02005397 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005398 return 0;
5399}
5400
5401__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5402{
5403 struct hlua_txn *htxn;
5404
5405 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5406 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5407
Christopher Faulet2351ca22019-07-26 16:31:34 +02005408 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005409 WILL_LJMP(lua_error(L));
5410
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005411 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
5412}
5413
5414__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5415{
5416 struct hlua_txn *htxn;
5417
5418 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5419 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5420
Christopher Faulet2351ca22019-07-26 16:31:34 +02005421 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005422 WILL_LJMP(lua_error(L));
5423
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005424 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
5425}
5426
5427__LJMP static int hlua_http_req_rep_val(lua_State *L)
5428{
5429 struct hlua_txn *htxn;
5430
5431 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5432 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5433
Christopher Faulet2351ca22019-07-26 16:31:34 +02005434 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005435 WILL_LJMP(lua_error(L));
5436
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005437 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
5438}
5439
5440__LJMP static int hlua_http_res_rep_val(lua_State *L)
5441{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005442 struct hlua_txn *htxn;
5443
5444 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5445 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5446
Christopher Faulet2351ca22019-07-26 16:31:34 +02005447 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005448 WILL_LJMP(lua_error(L));
5449
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02005450 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005451}
5452
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005453/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005454 * It is a wrapper for the 2 following functions.
5455 */
5456__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5457{
5458 size_t len;
5459 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005460
Christopher Faulet724a12c2018-12-13 22:12:15 +01005461 if (IS_HTX_STRM(htxn->s)) {
5462 /* HTX version */
5463 struct htx *htx = htxbuf(&msg->chn->buf);
5464 struct http_hdr_ctx ctx;
5465
5466 ctx.blk = NULL;
5467 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5468 http_remove_header(htx, &ctx);
5469 }
5470 else {
5471 /* Legacy HTTP version */
5472 struct hdr_ctx ctx;
5473 struct http_txn *txn = htxn->s->txn;
5474
5475 ctx.idx = 0;
5476 while (http_find_header2(name, len, ci_head(msg->chn), &txn->hdr_idx, &ctx))
5477 http_remove_header2(msg, &txn->hdr_idx, &ctx);
5478 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005479 return 0;
5480}
5481
5482__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5483{
5484 struct hlua_txn *htxn;
5485
5486 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5487 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5488
Christopher Faulet2351ca22019-07-26 16:31:34 +02005489 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005490 WILL_LJMP(lua_error(L));
5491
Willy Tarreaueee5b512015-04-03 23:46:31 +02005492 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005493}
5494
5495__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5496{
5497 struct hlua_txn *htxn;
5498
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005499 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005500 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5501
Christopher Faulet2351ca22019-07-26 16:31:34 +02005502 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005503 WILL_LJMP(lua_error(L));
5504
Willy Tarreaueee5b512015-04-03 23:46:31 +02005505 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005506}
5507
5508/* This function adds an header. It is a wrapper used by
5509 * the 2 following functions.
5510 */
5511__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5512{
5513 size_t name_len;
5514 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5515 size_t value_len;
5516 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
5517 char *p;
5518
Christopher Faulet724a12c2018-12-13 22:12:15 +01005519 if (IS_HTX_STRM(htxn->s)) {
5520 /* HTX version */
5521 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005522
Christopher Faulet724a12c2018-12-13 22:12:15 +01005523 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5524 ist2(value, value_len)));
5525 }
5526 else {
5527 /* Legacy HTTP version */
5528 /* Check length. */
5529 trash.data = value_len + name_len + 2;
5530 if (trash.data > trash.size)
5531 return 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005532
Christopher Faulet724a12c2018-12-13 22:12:15 +01005533 /* Creates the header string. */
5534 p = trash.area;
5535 memcpy(p, name, name_len);
5536 p += name_len;
5537 *p = ':';
5538 p++;
5539 *p = ' ';
5540 p++;
5541 memcpy(p, value, value_len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005542
Christopher Faulet724a12c2018-12-13 22:12:15 +01005543 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
5544 trash.area, trash.data) != 0);
5545 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005546 return 0;
5547}
5548
5549__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5550{
5551 struct hlua_txn *htxn;
5552
5553 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5554 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5555
Christopher Faulet2351ca22019-07-26 16:31:34 +02005556 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005557 WILL_LJMP(lua_error(L));
5558
Willy Tarreaueee5b512015-04-03 23:46:31 +02005559 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005560}
5561
5562__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5563{
5564 struct hlua_txn *htxn;
5565
5566 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5567 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5568
Christopher Faulet2351ca22019-07-26 16:31:34 +02005569 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005570 WILL_LJMP(lua_error(L));
5571
Willy Tarreaueee5b512015-04-03 23:46:31 +02005572 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005573}
5574
5575static int hlua_http_req_set_hdr(lua_State *L)
5576{
5577 struct hlua_txn *htxn;
5578
5579 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5580 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5581
Christopher Faulet2351ca22019-07-26 16:31:34 +02005582 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005583 WILL_LJMP(lua_error(L));
5584
Willy Tarreaueee5b512015-04-03 23:46:31 +02005585 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
5586 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005587}
5588
5589static int hlua_http_res_set_hdr(lua_State *L)
5590{
5591 struct hlua_txn *htxn;
5592
5593 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5594 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5595
Christopher Faulet2351ca22019-07-26 16:31:34 +02005596 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005597 WILL_LJMP(lua_error(L));
5598
Willy Tarreaueee5b512015-04-03 23:46:31 +02005599 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
5600 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005601}
5602
5603/* This function set the method. */
5604static int hlua_http_req_set_meth(lua_State *L)
5605{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005606 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005607 size_t name_len;
5608 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005609
Christopher Faulet2351ca22019-07-26 16:31:34 +02005610 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005611 WILL_LJMP(lua_error(L));
5612
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005613 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005614 return 1;
5615}
5616
5617/* This function set the method. */
5618static int hlua_http_req_set_path(lua_State *L)
5619{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005620 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005621 size_t name_len;
5622 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005623
Christopher Faulet2351ca22019-07-26 16:31:34 +02005624 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005625 WILL_LJMP(lua_error(L));
5626
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005627 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005628 return 1;
5629}
5630
5631/* This function set the query-string. */
5632static int hlua_http_req_set_query(lua_State *L)
5633{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005634 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005635 size_t name_len;
5636 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005637
Christopher Faulet2351ca22019-07-26 16:31:34 +02005638 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005639 WILL_LJMP(lua_error(L));
5640
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005641 /* Check length. */
5642 if (name_len > trash.size - 1) {
5643 lua_pushboolean(L, 0);
5644 return 1;
5645 }
5646
5647 /* Add the mark question as prefix. */
5648 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005649 trash.area[trash.data++] = '?';
5650 memcpy(trash.area + trash.data, name, name_len);
5651 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005652
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005653 lua_pushboolean(L,
5654 http_replace_req_line(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005655 return 1;
5656}
5657
5658/* This function set the uri. */
5659static int hlua_http_req_set_uri(lua_State *L)
5660{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005661 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005662 size_t name_len;
5663 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005664
Christopher Faulet2351ca22019-07-26 16:31:34 +02005665 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005666 WILL_LJMP(lua_error(L));
5667
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005668 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005669 return 1;
5670}
5671
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005672/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005673static int hlua_http_res_set_status(lua_State *L)
5674{
5675 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5676 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005677 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005678
Christopher Faulet2351ca22019-07-26 16:31:34 +02005679 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005680 WILL_LJMP(lua_error(L));
5681
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005682 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005683 return 0;
5684}
5685
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005686/*
5687 *
5688 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005689 * Class TXN
5690 *
5691 *
5692 */
5693
5694/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005695 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005696 */
5697__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5698{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005699 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005700}
5701
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005702__LJMP static int hlua_set_var(lua_State *L)
5703{
5704 struct hlua_txn *htxn;
5705 const char *name;
5706 size_t len;
5707 struct sample smp;
5708
5709 MAY_LJMP(check_args(L, 3, "set_var"));
5710
5711 /* It is useles to retrieve the stream, but this function
5712 * runs only in a stream context.
5713 */
5714 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5715 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5716
5717 /* Converts the third argument in a sample. */
5718 hlua_lua2smp(L, 3, &smp);
5719
5720 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005721 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005722 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005723 return 0;
5724}
5725
Christopher Faulet85d79c92016-11-09 16:54:56 +01005726__LJMP static int hlua_unset_var(lua_State *L)
5727{
5728 struct hlua_txn *htxn;
5729 const char *name;
5730 size_t len;
5731 struct sample smp;
5732
5733 MAY_LJMP(check_args(L, 2, "unset_var"));
5734
5735 /* It is useles to retrieve the stream, but this function
5736 * runs only in a stream context.
5737 */
5738 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5739 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5740
5741 /* Unset the variable. */
5742 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5743 vars_unset_by_name(name, len, &smp);
5744 return 0;
5745}
5746
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005747__LJMP static int hlua_get_var(lua_State *L)
5748{
5749 struct hlua_txn *htxn;
5750 const char *name;
5751 size_t len;
5752 struct sample smp;
5753
5754 MAY_LJMP(check_args(L, 2, "get_var"));
5755
5756 /* It is useles to retrieve the stream, but this function
5757 * runs only in a stream context.
5758 */
5759 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5760 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5761
Willy Tarreau7560dd42016-03-10 16:28:58 +01005762 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005763 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005764 lua_pushnil(L);
5765 return 1;
5766 }
5767
5768 return hlua_smp2lua(L, &smp);
5769}
5770
Willy Tarreau59551662015-03-10 14:23:13 +01005771__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005772{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005773 struct hlua *hlua;
5774
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005775 MAY_LJMP(check_args(L, 2, "set_priv"));
5776
Willy Tarreau87b09662015-04-03 00:22:06 +02005777 /* It is useles to retrieve the stream, but this function
5778 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005779 */
5780 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005781 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005782
5783 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005784 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005785
5786 /* Get and store new value. */
5787 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5788 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5789
5790 return 0;
5791}
5792
Willy Tarreau59551662015-03-10 14:23:13 +01005793__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005794{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005795 struct hlua *hlua;
5796
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005797 MAY_LJMP(check_args(L, 1, "get_priv"));
5798
Willy Tarreau87b09662015-04-03 00:22:06 +02005799 /* It is useles to retrieve the stream, but this function
5800 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005801 */
5802 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005803 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005804
5805 /* Push configuration index in the stack. */
5806 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5807
5808 return 1;
5809}
5810
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005811/* Create stack entry containing a class TXN. This function
5812 * return 0 if the stack does not contains free slots,
5813 * otherwise it returns 1.
5814 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005815static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005816{
Willy Tarreaude491382015-04-06 11:04:28 +02005817 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005818
5819 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005820 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005821 return 0;
5822
5823 /* NOTE: The allocation never fails. The failure
5824 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005825 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005826 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005827 /* Create the object: obj[0] = userdata. */
5828 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005829 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005830 lua_rawseti(L, -2, 0);
5831
Willy Tarreaude491382015-04-06 11:04:28 +02005832 htxn->s = s;
5833 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005834 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005835 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005836
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005837 /* Create the "f" field that contains a list of fetches. */
5838 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005839 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005840 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005841 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005842
5843 /* Create the "sf" field that contains a list of stringsafe fetches. */
5844 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005845 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005846 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005847 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005848
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005849 /* Create the "c" field that contains a list of converters. */
5850 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005851 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005852 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005853 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005854
5855 /* Create the "sc" field that contains a list of stringsafe converters. */
5856 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005857 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005858 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005859 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005860
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005861 /* Create the "req" field that contains the request channel object. */
5862 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005863 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005864 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005865 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005866
5867 /* Create the "res" field that contains the response channel object. */
5868 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005869 if (!hlua_channel_new(L, &s->res))
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
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005873 /* Creates the HTTP object is the current proxy allows http. */
5874 lua_pushstring(L, "http");
5875 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005876 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005877 return 0;
5878 }
5879 else
5880 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005881 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005882
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005883 /* Pop a class sesison metatable and affect it to the userdata. */
5884 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5885 lua_setmetatable(L, -2);
5886
5887 return 1;
5888}
5889
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005890__LJMP static int hlua_txn_deflog(lua_State *L)
5891{
5892 const char *msg;
5893 struct hlua_txn *htxn;
5894
5895 MAY_LJMP(check_args(L, 2, "deflog"));
5896 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5897 msg = MAY_LJMP(luaL_checkstring(L, 2));
5898
5899 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5900 return 0;
5901}
5902
5903__LJMP static int hlua_txn_log(lua_State *L)
5904{
5905 int level;
5906 const char *msg;
5907 struct hlua_txn *htxn;
5908
5909 MAY_LJMP(check_args(L, 3, "log"));
5910 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5911 level = MAY_LJMP(luaL_checkinteger(L, 2));
5912 msg = MAY_LJMP(luaL_checkstring(L, 3));
5913
5914 if (level < 0 || level >= NB_LOG_LEVELS)
5915 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5916
5917 hlua_sendlog(htxn->s->be, level, msg);
5918 return 0;
5919}
5920
5921__LJMP static int hlua_txn_log_debug(lua_State *L)
5922{
5923 const char *msg;
5924 struct hlua_txn *htxn;
5925
5926 MAY_LJMP(check_args(L, 2, "Debug"));
5927 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5928 msg = MAY_LJMP(luaL_checkstring(L, 2));
5929 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5930 return 0;
5931}
5932
5933__LJMP static int hlua_txn_log_info(lua_State *L)
5934{
5935 const char *msg;
5936 struct hlua_txn *htxn;
5937
5938 MAY_LJMP(check_args(L, 2, "Info"));
5939 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5940 msg = MAY_LJMP(luaL_checkstring(L, 2));
5941 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5942 return 0;
5943}
5944
5945__LJMP static int hlua_txn_log_warning(lua_State *L)
5946{
5947 const char *msg;
5948 struct hlua_txn *htxn;
5949
5950 MAY_LJMP(check_args(L, 2, "Warning"));
5951 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5952 msg = MAY_LJMP(luaL_checkstring(L, 2));
5953 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5954 return 0;
5955}
5956
5957__LJMP static int hlua_txn_log_alert(lua_State *L)
5958{
5959 const char *msg;
5960 struct hlua_txn *htxn;
5961
5962 MAY_LJMP(check_args(L, 2, "Alert"));
5963 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5964 msg = MAY_LJMP(luaL_checkstring(L, 2));
5965 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5966 return 0;
5967}
5968
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005969__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5970{
5971 struct hlua_txn *htxn;
5972 int ll;
5973
5974 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5975 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5976 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5977
5978 if (ll < 0 || ll > 7)
5979 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5980
5981 htxn->s->logs.level = ll;
5982 return 0;
5983}
5984
5985__LJMP static int hlua_txn_set_tos(lua_State *L)
5986{
5987 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005988 int tos;
5989
5990 MAY_LJMP(check_args(L, 2, "set_tos"));
5991 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5992 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5993
Willy Tarreau1a18b542018-12-11 16:37:42 +01005994 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005995 return 0;
5996}
5997
5998__LJMP static int hlua_txn_set_mark(lua_State *L)
5999{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006000 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006001 int mark;
6002
6003 MAY_LJMP(check_args(L, 2, "set_mark"));
6004 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6005 mark = MAY_LJMP(luaL_checkinteger(L, 2));
6006
Lukas Tribusb59291a2019-08-11 18:03:45 +02006007 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006008 return 0;
6009}
6010
Patrick Hemmer268a7072018-05-11 12:52:31 -04006011__LJMP static int hlua_txn_set_priority_class(lua_State *L)
6012{
6013 struct hlua_txn *htxn;
6014
6015 MAY_LJMP(check_args(L, 2, "set_priority_class"));
6016 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6017 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
6018 return 0;
6019}
6020
6021__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
6022{
6023 struct hlua_txn *htxn;
6024
6025 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
6026 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6027 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
6028 return 0;
6029}
6030
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006031/* This function is an Lua binding that send pending data
6032 * to the client, and close the stream interface.
6033 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006034__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006035{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006036 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006037 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01006038 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006039
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006040 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006041 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006042 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006043
Thierry FOURNIERab00df62016-07-14 11:42:37 +02006044 /* If the flags NOTERM is set, we cannot terminate the http
6045 * session, so we just end the execution of the current
6046 * lua code.
6047 */
6048 if (htxn->flags & HLUA_TXN_NOTERM) {
6049 WILL_LJMP(hlua_done(L));
6050 return 0;
6051 }
6052
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006053 ic = &htxn->s->req;
6054 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01006055
Christopher Faulet72c69272019-07-26 16:40:24 +02006056 if (IS_HTX_STRM(htxn->s)) {
6057 htxn->s->txn->status = 0;
6058 http_reply_and_close(htxn->s, 0, NULL);
6059 ic->analysers &= AN_REQ_FLT_END;
6060 oc->analysers &= AN_RES_FLT_END;
6061 }
Christopher Fauletb58fb792019-07-16 10:52:40 +02006062 else {
6063 if (htxn->s->txn) {
6064 /* HTTP mode, let's stay in sync with the stream */
6065 b_del(&ic->buf, htxn->s->txn->req.sov);
6066 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
6067 htxn->s->txn->req.sov = 0;
6068
6069 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
6070 oc->analysers = AN_RES_HTTP_XFER_BODY;
6071 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
6072 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
Willy Tarreau630ef452015-08-28 10:06:15 +02006073
Willy Tarreau630ef452015-08-28 10:06:15 +02006074 /* Note that if we want to support keep-alive, we need
6075 * to bypass the close/shutr_now calls below, but that
6076 * may only be done if the HTTP request was already
6077 * processed and the connection header is known (ie
6078 * not during TCP rules).
6079 */
Christopher Fauletb58fb792019-07-16 10:52:40 +02006080 }
Willy Tarreau630ef452015-08-28 10:06:15 +02006081
Christopher Fauletb58fb792019-07-16 10:52:40 +02006082 channel_auto_read(ic);
6083 channel_abort(ic);
6084 channel_auto_close(ic);
6085 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02006086
Christopher Fauletb58fb792019-07-16 10:52:40 +02006087 oc->wex = tick_add_ifset(now_ms, oc->wto);
6088 channel_auto_read(oc);
6089 channel_auto_close(oc);
6090 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006091
Christopher Fauletb58fb792019-07-16 10:52:40 +02006092 ic->analysers = 0;
6093 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006094
Christopher Faulet72c69272019-07-26 16:40:24 +02006095 if (!(htxn->s->flags & SF_ERR_MASK)) // this is not really an error but it is
6096 htxn->s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
6097
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006098 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006099 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006100 return 0;
6101}
6102
6103__LJMP static int hlua_log(lua_State *L)
6104{
6105 int level;
6106 const char *msg;
6107
6108 MAY_LJMP(check_args(L, 2, "log"));
6109 level = MAY_LJMP(luaL_checkinteger(L, 1));
6110 msg = MAY_LJMP(luaL_checkstring(L, 2));
6111
6112 if (level < 0 || level >= NB_LOG_LEVELS)
6113 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
6114
6115 hlua_sendlog(NULL, level, msg);
6116 return 0;
6117}
6118
6119__LJMP static int hlua_log_debug(lua_State *L)
6120{
6121 const char *msg;
6122
6123 MAY_LJMP(check_args(L, 1, "debug"));
6124 msg = MAY_LJMP(luaL_checkstring(L, 1));
6125 hlua_sendlog(NULL, LOG_DEBUG, msg);
6126 return 0;
6127}
6128
6129__LJMP static int hlua_log_info(lua_State *L)
6130{
6131 const char *msg;
6132
6133 MAY_LJMP(check_args(L, 1, "info"));
6134 msg = MAY_LJMP(luaL_checkstring(L, 1));
6135 hlua_sendlog(NULL, LOG_INFO, msg);
6136 return 0;
6137}
6138
6139__LJMP static int hlua_log_warning(lua_State *L)
6140{
6141 const char *msg;
6142
6143 MAY_LJMP(check_args(L, 1, "warning"));
6144 msg = MAY_LJMP(luaL_checkstring(L, 1));
6145 hlua_sendlog(NULL, LOG_WARNING, msg);
6146 return 0;
6147}
6148
6149__LJMP static int hlua_log_alert(lua_State *L)
6150{
6151 const char *msg;
6152
6153 MAY_LJMP(check_args(L, 1, "alert"));
6154 msg = MAY_LJMP(luaL_checkstring(L, 1));
6155 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006156 return 0;
6157}
6158
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006159__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006160{
6161 int wakeup_ms = lua_tointeger(L, -1);
6162 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02006163 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006164 return 0;
6165}
6166
6167__LJMP static int hlua_sleep(lua_State *L)
6168{
6169 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006170 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006171
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006172 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006173
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006174 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006175 wakeup_ms = tick_add(now_ms, delay);
6176 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006177
Willy Tarreau9635e032018-10-16 17:52:55 +02006178 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006179 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006180}
6181
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006182__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006183{
6184 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006185 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006186
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006187 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006188
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006189 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006190 wakeup_ms = tick_add(now_ms, delay);
6191 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006192
Willy Tarreau9635e032018-10-16 17:52:55 +02006193 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006194 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006195}
6196
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006197/* This functionis an LUA binding. it permits to give back
6198 * the hand at the HAProxy scheduler. It is used when the
6199 * LUA processing consumes a lot of time.
6200 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006201__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006202{
6203 return 0;
6204}
6205
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006206__LJMP static int hlua_yield(lua_State *L)
6207{
Willy Tarreau9635e032018-10-16 17:52:55 +02006208 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006209 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006210}
6211
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006212/* This function change the nice of the currently executed
6213 * task. It is used set low or high priority at the current
6214 * task.
6215 */
Willy Tarreau59551662015-03-10 14:23:13 +01006216__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006217{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006218 struct hlua *hlua;
6219 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006220
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006221 MAY_LJMP(check_args(L, 1, "set_nice"));
6222 hlua = hlua_gethlua(L);
6223 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006224
6225 /* If he task is not set, I'm in a start mode. */
6226 if (!hlua || !hlua->task)
6227 return 0;
6228
6229 if (nice < -1024)
6230 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006231 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006232 nice = 1024;
6233
6234 hlua->task->nice = nice;
6235 return 0;
6236}
6237
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006238/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006239 * HAProxy task subsystem when the task is awaked. The LUA runtime can
6240 * return an E_AGAIN signal, the emmiter of this signal must set a
6241 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006242 *
6243 * Task wrapper are longjmp safe because the only one Lua code
6244 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006245 */
Willy Tarreau83a5ff42019-08-21 14:14:50 +02006246struct task *hlua_process_task(struct task *task, void *context, unsigned short state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006247{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006248 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006249 enum hlua_exec status;
6250
Christopher Faulet5bc99722018-04-25 10:34:45 +02006251 if (task->thread_mask == MAX_THREADS_MASK)
6252 task_set_affinity(task, tid_bit);
6253
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006254 /* If it is the first call to the task, we must initialize the
6255 * execution timeouts.
6256 */
6257 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006258 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006259
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006260 /* Execute the Lua code. */
6261 status = hlua_ctx_resume(hlua, 1);
6262
6263 switch (status) {
6264 /* finished or yield */
6265 case HLUA_E_OK:
6266 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006267 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02006268 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006269 break;
6270
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006271 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01006272 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02006273 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006274 break;
6275
6276 /* finished with error. */
6277 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006278 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006279 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006280 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006281 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006282 break;
6283
6284 case HLUA_E_ERR:
6285 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006286 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006287 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006288 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006289 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006290 break;
6291 }
Emeric Brun253e53e2017-10-17 18:58:40 +02006292 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006293}
6294
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006295/* This function is an LUA binding that register LUA function to be
6296 * executed after the HAProxy configuration parsing and before the
6297 * HAProxy scheduler starts. This function expect only one LUA
6298 * argument that is a function. This function returns nothing, but
6299 * throws if an error is encountered.
6300 */
6301__LJMP static int hlua_register_init(lua_State *L)
6302{
6303 struct hlua_init_function *init;
6304 int ref;
6305
6306 MAY_LJMP(check_args(L, 1, "register_init"));
6307
6308 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6309
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006310 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006311 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006312 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006313
6314 init->function_ref = ref;
6315 LIST_ADDQ(&hlua_init_functions, &init->l);
6316 return 0;
6317}
6318
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006319/* This functio is an LUA binding. It permits to register a task
6320 * executed in parallel of the main HAroxy activity. The task is
6321 * created and it is set in the HAProxy scheduler. It can be called
6322 * from the "init" section, "post init" or during the runtime.
6323 *
6324 * Lua prototype:
6325 *
6326 * <none> core.register_task(<function>)
6327 */
6328static int hlua_register_task(lua_State *L)
6329{
6330 struct hlua *hlua;
6331 struct task *task;
6332 int ref;
6333
6334 MAY_LJMP(check_args(L, 1, "register_task"));
6335
6336 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6337
Willy Tarreaubafbe012017-11-24 17:34:44 +01006338 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006339 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006340 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006341
Emeric Brunc60def82017-09-27 14:59:38 +02006342 task = task_new(MAX_THREADS_MASK);
Willy Tarreaue09101e2018-10-16 17:37:12 +02006343 if (!task)
6344 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
6345
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006346 task->context = hlua;
6347 task->process = hlua_process_task;
6348
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006349 if (!hlua_ctx_init(hlua, task, 1))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006350 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006351
6352 /* Restore the function in the stack. */
6353 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
6354 hlua->nargs = 0;
6355
6356 /* Schedule task. */
6357 task_schedule(task, now_ms);
6358
6359 return 0;
6360}
6361
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006362/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
6363 * doesn't allow "yield" functions because the HAProxy engine cannot
6364 * resume converters.
6365 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006366static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006367{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006368 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006369 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006370 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006371
Willy Tarreaube508f12016-03-10 11:47:01 +01006372 if (!stream)
6373 return 0;
6374
Willy Tarreau87b09662015-04-03 00:22:06 +02006375 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006376 * Lua context can be not initialized. This behavior
6377 * permits to save performances because a systematic
6378 * Lua initialization cause 5% performances loss.
6379 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006380 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006381 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006382 if (!stream->hlua) {
6383 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6384 return 0;
6385 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006386 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006387 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6388 return 0;
6389 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006390 }
6391
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006392 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006393 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006394
6395 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006396 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6397 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6398 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006399 else
6400 error = "critical error";
6401 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006402 return 0;
6403 }
6404
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006405 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006406 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006407 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006408 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006409 return 0;
6410 }
6411
6412 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006413 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006414
6415 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006416 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006417 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006418 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006419 return 0;
6420 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006421 hlua_smp2lua(stream->hlua->T, smp);
6422 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006423
6424 /* push keywords in the stack. */
6425 if (arg_p) {
6426 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006427 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006428 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006429 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006430 return 0;
6431 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006432 hlua_arg2lua(stream->hlua->T, arg_p);
6433 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006434 }
6435 }
6436
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006437 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006438 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006439
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006440 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006441 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006442 }
6443
6444 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006445 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006446 /* finished. */
6447 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006448 /* If the stack is empty, the function fails. */
6449 if (lua_gettop(stream->hlua->T) <= 0)
6450 return 0;
6451
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006452 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006453 hlua_lua2smp(stream->hlua->T, -1, smp);
6454 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006455 return 1;
6456
6457 /* yield. */
6458 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006459 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006460 return 0;
6461
6462 /* finished with error. */
6463 case HLUA_E_ERRMSG:
6464 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006465 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006466 fcn->name, lua_tostring(stream->hlua->T, -1));
6467 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006468 return 0;
6469
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006470 case HLUA_E_ETMOUT:
6471 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
6472 return 0;
6473
6474 case HLUA_E_NOMEM:
6475 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
6476 return 0;
6477
6478 case HLUA_E_YIELD:
6479 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
6480 return 0;
6481
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006482 case HLUA_E_ERR:
6483 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006484 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006485
6486 default:
6487 return 0;
6488 }
6489}
6490
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006491/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
6492 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01006493 * resume sample-fetches. This function will be called by the sample
6494 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006495 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02006496static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
6497 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006498{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006499 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006500 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006501 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006502 const struct buffer msg = { };
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006503 unsigned int hflags = HLUA_TXN_NOTERM;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006504
Willy Tarreaube508f12016-03-10 11:47:01 +01006505 if (!stream)
6506 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01006507
Willy Tarreau87b09662015-04-03 00:22:06 +02006508 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006509 * Lua context can be not initialized. This behavior
6510 * permits to save performances because a systematic
6511 * Lua initialization cause 5% performances loss.
6512 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006513 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006514 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006515 if (!stream->hlua) {
6516 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6517 return 0;
6518 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006519 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006520 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6521 return 0;
6522 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006523 }
6524
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006525 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006526
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006527 if (stream->be->mode == PR_MODE_HTTP) {
6528 if ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ)
6529 hflags |= ((stream->txn->req.msg_state < HTTP_MSG_BODY) ? 0 : HLUA_TXN_HTTP_RDY);
6530 else
6531 hflags |= ((stream->txn->rsp.msg_state < HTTP_MSG_BODY) ? 0 : HLUA_TXN_HTTP_RDY);
6532 }
6533
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006534 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006535 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006536
6537 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006538 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6539 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6540 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006541 else
6542 error = "critical error";
6543 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006544 return 0;
6545 }
6546
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006547 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006548 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006549 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006550 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006551 return 0;
6552 }
6553
6554 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006555 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006556
6557 /* push arguments in the stack. */
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006558 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006559 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006560 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006561 return 0;
6562 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006563 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006564
6565 /* push keywords in the stack. */
6566 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
6567 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006568 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006569 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006570 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006571 return 0;
6572 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006573 hlua_arg2lua(stream->hlua->T, arg_p);
6574 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006575 }
6576
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006577 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006578 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006579
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006580 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006581 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006582 }
6583
6584 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006585 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006586 /* finished. */
6587 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006588 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006589 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006590 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006591 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006592 /* If the stack is empty, the function fails. */
6593 if (lua_gettop(stream->hlua->T) <= 0)
6594 return 0;
6595
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006596 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006597 hlua_lua2smp(stream->hlua->T, -1, smp);
6598 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006599
6600 /* Set the end of execution flag. */
6601 smp->flags &= ~SMP_F_MAY_CHANGE;
6602 return 1;
6603
6604 /* yield. */
6605 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006606 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006607 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006608 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006609 return 0;
6610
6611 /* finished with error. */
6612 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006613 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006614 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006615 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006616 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006617 fcn->name, lua_tostring(stream->hlua->T, -1));
6618 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006619 return 0;
6620
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006621 case HLUA_E_ETMOUT:
6622 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006623 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006624 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
6625 return 0;
6626
6627 case HLUA_E_NOMEM:
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': out of memory error.\n", fcn->name);
6631 return 0;
6632
6633 case HLUA_E_YIELD:
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': yield not allowed.\n", fcn->name);
6637 return 0;
6638
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006639 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006640 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006641 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006642 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006643 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006644
6645 default:
6646 return 0;
6647 }
6648}
6649
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006650/* This function is an LUA binding used for registering
6651 * "sample-conv" functions. It expects a converter name used
6652 * in the haproxy configuration file, and an LUA function.
6653 */
6654__LJMP static int hlua_register_converters(lua_State *L)
6655{
6656 struct sample_conv_kw_list *sck;
6657 const char *name;
6658 int ref;
6659 int len;
6660 struct hlua_function *fcn;
6661
6662 MAY_LJMP(check_args(L, 2, "register_converters"));
6663
6664 /* First argument : converter name. */
6665 name = MAY_LJMP(luaL_checkstring(L, 1));
6666
6667 /* Second argument : lua function. */
6668 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6669
6670 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006671 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006672 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006673 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006674 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006675 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006676 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006677
6678 /* Fill fcn. */
6679 fcn->name = strdup(name);
6680 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006681 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006682 fcn->function_ref = ref;
6683
6684 /* List head */
6685 sck->list.n = sck->list.p = NULL;
6686
6687 /* converter keyword. */
6688 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006689 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006690 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006691 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006692
6693 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6694 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006695 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 +01006696 sck->kw[0].val_args = NULL;
6697 sck->kw[0].in_type = SMP_T_STR;
6698 sck->kw[0].out_type = SMP_T_STR;
6699 sck->kw[0].private = fcn;
6700
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006701 /* Register this new converter */
6702 sample_register_convs(sck);
6703
6704 return 0;
6705}
6706
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006707/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006708 * "sample-fetch" functions. It expects a converter name used
6709 * in the haproxy configuration file, and an LUA function.
6710 */
6711__LJMP static int hlua_register_fetches(lua_State *L)
6712{
6713 const char *name;
6714 int ref;
6715 int len;
6716 struct sample_fetch_kw_list *sfk;
6717 struct hlua_function *fcn;
6718
6719 MAY_LJMP(check_args(L, 2, "register_fetches"));
6720
6721 /* First argument : sample-fetch name. */
6722 name = MAY_LJMP(luaL_checkstring(L, 1));
6723
6724 /* Second argument : lua function. */
6725 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6726
6727 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006728 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006729 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006730 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006731 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006732 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006733 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006734
6735 /* Fill fcn. */
6736 fcn->name = strdup(name);
6737 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006738 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006739 fcn->function_ref = ref;
6740
6741 /* List head */
6742 sfk->list.n = sfk->list.p = NULL;
6743
6744 /* sample-fetch keyword. */
6745 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006746 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006747 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006748 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006749
6750 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6751 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006752 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 +01006753 sfk->kw[0].val_args = NULL;
6754 sfk->kw[0].out_type = SMP_T_STR;
6755 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6756 sfk->kw[0].val = 0;
6757 sfk->kw[0].private = fcn;
6758
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006759 /* Register this new fetch. */
6760 sample_register_fetches(sfk);
6761
6762 return 0;
6763}
6764
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006765/* This function is a wrapper to execute each LUA function declared
6766 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006767 * return ACT_RET_CONT if the processing is finished (with or without
6768 * error) and return ACT_RET_YIELD if the function must be called again
6769 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006770 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006771static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006772 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006773{
6774 char **arg;
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006775 unsigned int hflags = 0;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006776 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006777 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006778 const struct buffer msg = { };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006779
6780 switch (rule->from) {
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006781 case ACT_F_TCP_REQ_CNT: ; dir = SMP_OPT_DIR_REQ; break;
6782 case ACT_F_TCP_RES_CNT: ; dir = SMP_OPT_DIR_RES; break;
6783 case ACT_F_HTTP_REQ: hflags = HLUA_TXN_HTTP_RDY ; dir = SMP_OPT_DIR_REQ; break;
6784 case ACT_F_HTTP_RES: hflags = HLUA_TXN_HTTP_RDY ; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006785 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006786 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006787 return ACT_RET_CONT;
6788 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006789
Willy Tarreau87b09662015-04-03 00:22:06 +02006790 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006791 * Lua context can be not initialized. This behavior
6792 * permits to save performances because a systematic
6793 * Lua initialization cause 5% performances loss.
6794 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006795 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006796 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006797 if (!s->hlua) {
6798 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6799 rule->arg.hlua_rule->fcn.name);
6800 return ACT_RET_CONT;
6801 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006802 if (!hlua_ctx_init(s->hlua, s->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006803 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6804 rule->arg.hlua_rule->fcn.name);
6805 return ACT_RET_CONT;
6806 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006807 }
6808
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006809 consistency_set(s, dir, &s->hlua->cons);
6810
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006811 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006812 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006813
6814 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006815 if (!SET_SAFE_LJMP(s->hlua->T)) {
6816 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6817 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006818 else
6819 error = "critical error";
6820 SEND_ERR(px, "Lua function '%s': %s.\n",
6821 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006822 return ACT_RET_CONT;
6823 }
6824
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006825 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006826 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006827 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006828 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006829 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006830 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006831 }
6832
6833 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006834 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006835
Willy Tarreau87b09662015-04-03 00:22:06 +02006836 /* Create and and push object stream in the stack. */
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006837 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006838 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006839 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006840 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006841 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006842 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006843 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006844
6845 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006846 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006847 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006848 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006849 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006850 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006851 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006852 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006853 lua_pushstring(s->hlua->T, *arg);
6854 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006855 }
6856
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006857 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006858 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006859
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006860 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006861 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006862 }
6863
6864 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006865 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006866 /* finished. */
6867 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006868 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006869 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006870 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006871 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006872 if (s->hlua->flags & HLUA_STOP)
Christopher Faulet4629d082019-07-04 11:27:15 +02006873 return ACT_RET_DONE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006874 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006875
6876 /* yield. */
6877 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006878 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006879 if (s->hlua->wake_time != TICK_ETERNITY) {
Christopher Fauletea0b0e22019-08-14 23:19:45 +02006880 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006881 s->req.analyse_exp = s->hlua->wake_time;
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006882 else
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006883 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006884 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006885 /* Some actions can be wake up when a "write" event
6886 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006887 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006888 */
Christopher Fauletb22f6502019-07-26 14:54:52 +02006889 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006890 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006891 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006892 s->req.flags |= CF_WAKE_WRITE;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006893 /* We can quit the function without consistency check
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006894 * because HAProxy is not able to manipulate data, it
6895 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006896 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006897
6898 /* finished with error. */
6899 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006900 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006901 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006902 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006903 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006904 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006905 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006906 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6907 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006908 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006909
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006910 case HLUA_E_ETMOUT:
6911 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006912 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006913 return ACT_RET_ERR;
6914 }
6915 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
6916 return 0;
6917
6918 case HLUA_E_NOMEM:
6919 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006920 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006921 return ACT_RET_ERR;
6922 }
6923 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
6924 return 0;
6925
6926 case HLUA_E_YIELD:
6927 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006928 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006929 return ACT_RET_ERR;
6930 }
6931 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6932 rule->arg.hlua_rule->fcn.name);
6933 return 0;
6934
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006935 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006936 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006937 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006938 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006939 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006940 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006941 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006942 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006943
6944 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006945 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006946 }
6947}
6948
Olivier Houchard9f6af332018-05-25 14:04:04 +02006949struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006950{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006951 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006952
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006953 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006954 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006955 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006956}
6957
6958static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6959{
6960 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006961 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006962 struct task *task;
6963 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006964 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006965
Willy Tarreaubafbe012017-11-24 17:34:44 +01006966 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006967 if (!hlua) {
6968 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6969 ctx->rule->arg.hlua_rule->fcn.name);
6970 return 0;
6971 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006972 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006973 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006974 ctx->ctx.hlua_apptcp.flags = 0;
6975
6976 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006977 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006978 if (!task) {
6979 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6980 ctx->rule->arg.hlua_rule->fcn.name);
6981 return 0;
6982 }
6983 task->nice = 0;
6984 task->context = ctx;
6985 task->process = hlua_applet_wakeup;
6986 ctx->ctx.hlua_apptcp.task = task;
6987
6988 /* In the execution wrappers linked with a stream, the
6989 * Lua context can be not initialized. This behavior
6990 * permits to save performances because a systematic
6991 * Lua initialization cause 5% performances loss.
6992 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006993 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006994 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6995 ctx->rule->arg.hlua_rule->fcn.name);
6996 return 0;
6997 }
6998
6999 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007000 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007001
7002 /* The following Lua calls can fail. */
7003 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007004 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7005 error = lua_tostring(hlua->T, -1);
7006 else
7007 error = "critical error";
7008 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
7009 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007010 return 0;
7011 }
7012
7013 /* Check stack available size. */
7014 if (!lua_checkstack(hlua->T, 1)) {
7015 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7016 ctx->rule->arg.hlua_rule->fcn.name);
7017 RESET_SAFE_LJMP(hlua->T);
7018 return 0;
7019 }
7020
7021 /* Restore the function in the stack. */
7022 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7023
7024 /* Create and and push object stream in the stack. */
7025 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
7026 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7027 ctx->rule->arg.hlua_rule->fcn.name);
7028 RESET_SAFE_LJMP(hlua->T);
7029 return 0;
7030 }
7031 hlua->nargs = 1;
7032
7033 /* push keywords in the stack. */
7034 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7035 if (!lua_checkstack(hlua->T, 1)) {
7036 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7037 ctx->rule->arg.hlua_rule->fcn.name);
7038 RESET_SAFE_LJMP(hlua->T);
7039 return 0;
7040 }
7041 lua_pushstring(hlua->T, *arg);
7042 hlua->nargs++;
7043 }
7044
7045 RESET_SAFE_LJMP(hlua->T);
7046
7047 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007048 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01007049 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007050
7051 return 1;
7052}
7053
Willy Tarreau83a5ff42019-08-21 14:14:50 +02007054void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007055{
7056 struct stream_interface *si = ctx->owner;
7057 struct stream *strm = si_strm(si);
7058 struct channel *res = si_ic(si);
7059 struct act_rule *rule = ctx->rule;
7060 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007061 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007062
7063 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02007064 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
7065 /* eat the whole request */
7066 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007067 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02007068 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007069
7070 /* If the stream is disconnect or closed, ldo nothing. */
7071 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7072 return;
7073
7074 /* Execute the function. */
7075 switch (hlua_ctx_resume(hlua, 1)) {
7076 /* finished. */
7077 case HLUA_E_OK:
7078 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7079
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007080 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02007081 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007082 res->flags |= CF_READ_NULL;
7083 si_shutr(si);
7084 return;
7085
7086 /* yield. */
7087 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007088 if (hlua->wake_time != TICK_ETERNITY)
7089 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007090 return;
7091
7092 /* finished with error. */
7093 case HLUA_E_ERRMSG:
7094 /* Display log. */
7095 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
7096 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7097 lua_pop(hlua->T, 1);
7098 goto error;
7099
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007100 case HLUA_E_ETMOUT:
7101 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
7102 rule->arg.hlua_rule->fcn.name);
7103 goto error;
7104
7105 case HLUA_E_NOMEM:
7106 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
7107 rule->arg.hlua_rule->fcn.name);
7108 goto error;
7109
7110 case HLUA_E_YIELD: /* unexpected */
7111 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
7112 rule->arg.hlua_rule->fcn.name);
7113 goto error;
7114
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007115 case HLUA_E_ERR:
7116 /* Display log. */
7117 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
7118 rule->arg.hlua_rule->fcn.name);
7119 goto error;
7120
7121 default:
7122 goto error;
7123 }
7124
7125error:
7126
7127 /* For all other cases, just close the stream. */
7128 si_shutw(si);
7129 si_shutr(si);
7130 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7131}
7132
7133static void hlua_applet_tcp_release(struct appctx *ctx)
7134{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007135 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007136 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007137 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007138 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007139}
7140
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007141/* The function returns 1 if the initialisation is complete, 0 if
7142 * an errors occurs and -1 if more data are required for initializing
7143 * the applet.
7144 */
7145static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
7146{
7147 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007148 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007149 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007150 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007151 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007152 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007153
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007154 txn = strm->txn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007155
Willy Tarreau0078bfc2015-10-07 20:20:28 +02007156 /* We want two things in HTTP mode :
7157 * - enforce server-close mode if we were in keep-alive, so that the
7158 * applet is released after each response ;
7159 * - enable request body transfer to the applet in order to resync
7160 * with the response body.
7161 */
7162 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
7163 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02007164
Willy Tarreaubafbe012017-11-24 17:34:44 +01007165 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007166 if (!hlua) {
7167 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7168 ctx->rule->arg.hlua_rule->fcn.name);
7169 return 0;
7170 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007171 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007172 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007173 ctx->ctx.hlua_apphttp.left_bytes = -1;
7174 ctx->ctx.hlua_apphttp.flags = 0;
7175
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01007176 if (txn->req.flags & HTTP_MSGF_VER_11)
7177 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
7178
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007179 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007180 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007181 if (!task) {
7182 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7183 ctx->rule->arg.hlua_rule->fcn.name);
7184 return 0;
7185 }
7186 task->nice = 0;
7187 task->context = ctx;
7188 task->process = hlua_applet_wakeup;
7189 ctx->ctx.hlua_apphttp.task = task;
7190
7191 /* In the execution wrappers linked with a stream, the
7192 * Lua context can be not initialized. This behavior
7193 * permits to save performances because a systematic
7194 * Lua initialization cause 5% performances loss.
7195 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007196 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007197 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
7198 ctx->rule->arg.hlua_rule->fcn.name);
7199 return 0;
7200 }
7201
7202 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007203 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007204
7205 /* The following Lua calls can fail. */
7206 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007207 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7208 error = lua_tostring(hlua->T, -1);
7209 else
7210 error = "critical error";
7211 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7212 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007213 return 0;
7214 }
7215
7216 /* Check stack available size. */
7217 if (!lua_checkstack(hlua->T, 1)) {
7218 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7219 ctx->rule->arg.hlua_rule->fcn.name);
7220 RESET_SAFE_LJMP(hlua->T);
7221 return 0;
7222 }
7223
7224 /* Restore the function in the stack. */
7225 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7226
7227 /* Create and and push object stream in the stack. */
7228 if (!hlua_applet_http_new(hlua->T, ctx)) {
7229 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7230 ctx->rule->arg.hlua_rule->fcn.name);
7231 RESET_SAFE_LJMP(hlua->T);
7232 return 0;
7233 }
7234 hlua->nargs = 1;
7235
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007236 /* push keywords in the stack. */
7237 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7238 if (!lua_checkstack(hlua->T, 1)) {
7239 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7240 ctx->rule->arg.hlua_rule->fcn.name);
7241 RESET_SAFE_LJMP(hlua->T);
7242 return 0;
7243 }
7244 lua_pushstring(hlua->T, *arg);
7245 hlua->nargs++;
7246 }
7247
7248 RESET_SAFE_LJMP(hlua->T);
7249
7250 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007251 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007252
7253 return 1;
7254}
7255
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007256static void hlua_applet_htx_fct(struct appctx *ctx)
7257{
7258 struct stream_interface *si = ctx->owner;
7259 struct stream *strm = si_strm(si);
7260 struct channel *req = si_oc(si);
7261 struct channel *res = si_ic(si);
7262 struct act_rule *rule = ctx->rule;
7263 struct proxy *px = strm->be;
7264 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
7265 struct htx *req_htx, *res_htx;
7266
7267 res_htx = htx_from_buf(&res->buf);
7268
7269 /* If the stream is disconnect or closed, ldo nothing. */
7270 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7271 goto out;
7272
7273 /* Check if the input buffer is avalaible. */
7274 if (!b_size(&res->buf)) {
7275 si_rx_room_blk(si);
7276 goto out;
7277 }
7278 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007279 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007280 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7281
7282 /* Set the currently running flag. */
7283 if (!HLUA_IS_RUNNING(hlua) &&
7284 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7285 struct htx_blk *blk;
7286 size_t count = co_data(req);
7287
7288 if (!count) {
7289 si_cant_get(si);
7290 goto out;
7291 }
7292
7293 /* We need to flush the request header. This left the body for
7294 * the Lua.
7295 */
7296 req_htx = htx_from_buf(&req->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02007297 blk = htx_get_first_blk(req_htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007298 while (count && blk) {
7299 enum htx_blk_type type = htx_get_blk_type(blk);
7300 uint32_t sz = htx_get_blksz(blk);
7301
7302 if (sz > count) {
7303 si_cant_get(si);
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007304 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007305 goto out;
7306 }
7307
7308 count -= sz;
7309 co_set_data(req, co_data(req) - sz);
7310 blk = htx_remove_blk(req_htx, blk);
7311
7312 if (type == HTX_BLK_EOH)
7313 break;
7314 }
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007315 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007316 }
7317
7318 /* Executes The applet if it is not done. */
7319 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7320
7321 /* Execute the function. */
7322 switch (hlua_ctx_resume(hlua, 1)) {
7323 /* finished. */
7324 case HLUA_E_OK:
7325 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7326 break;
7327
7328 /* yield. */
7329 case HLUA_E_AGAIN:
7330 if (hlua->wake_time != TICK_ETERNITY)
7331 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007332 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007333
7334 /* finished with error. */
7335 case HLUA_E_ERRMSG:
7336 /* Display log. */
7337 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7338 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7339 lua_pop(hlua->T, 1);
7340 goto error;
7341
7342 case HLUA_E_ETMOUT:
7343 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7344 rule->arg.hlua_rule->fcn.name);
7345 goto error;
7346
7347 case HLUA_E_NOMEM:
7348 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7349 rule->arg.hlua_rule->fcn.name);
7350 goto error;
7351
7352 case HLUA_E_YIELD: /* unexpected */
7353 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7354 rule->arg.hlua_rule->fcn.name);
7355 goto error;
7356
7357 case HLUA_E_ERR:
7358 /* Display log. */
7359 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7360 rule->arg.hlua_rule->fcn.name);
7361 goto error;
7362
7363 default:
7364 goto error;
7365 }
7366 }
7367
7368 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007369 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7370 goto done;
7371
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007372 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7373 goto error;
7374
Christopher Faulet54b5e212019-06-04 10:08:28 +02007375 /* Don't add TLR because mux-h1 will take care of it */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007376 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
7377 si_rx_room_blk(si);
7378 goto out;
7379 }
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007380 channel_add_input(res, 1);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007381 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7382 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007383 }
7384
7385 done:
7386 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007387 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007388 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007389 si_shutr(si);
7390 }
7391
7392 /* eat the whole request */
7393 if (co_data(req)) {
7394 req_htx = htx_from_buf(&req->buf);
7395 co_htx_skip(req, req_htx, co_data(req));
7396 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007397 }
7398 }
7399
7400 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007401 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007402 return;
7403
7404 error:
7405
7406 /* If we are in HTTP mode, and we are not send any
7407 * data, return a 500 server error in best effort:
7408 * if there is no room available in the buffer,
7409 * just close the connection.
7410 */
7411 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
7412 struct buffer *err = &htx_err_chunks[HTTP_ERR_500];
7413
7414 channel_erase(res);
7415 res->buf.data = b_data(err);
7416 memcpy(res->buf.area, b_head(err), b_data(err));
7417 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007418 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007419 }
7420 if (!(strm->flags & SF_ERR_MASK))
7421 strm->flags |= SF_ERR_RESOURCE;
7422 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7423 goto done;
7424}
7425
Willy Tarreau83a5ff42019-08-21 14:14:50 +02007426void hlua_applet_http_fct(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007427{
7428 struct stream_interface *si = ctx->owner;
7429 struct stream *strm = si_strm(si);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007430 struct channel *req = si_oc(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007431 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007432 struct act_rule *rule = ctx->rule;
7433 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007434 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Willy Tarreau206ba832018-06-14 15:27:31 +02007435 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02007436 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02007437 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02007438 size_t len2;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007439 int ret;
7440
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007441 if (IS_HTX_STRM(strm))
7442 return hlua_applet_htx_fct(ctx);
7443
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007444 /* If the stream is disconnect or closed, ldo nothing. */
7445 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007446 goto out;
7447
7448 /* Check if the input buffer is avalaible. */
7449 if (!b_size(&res->buf)) {
7450 si_rx_room_blk(si);
7451 goto out;
7452 }
7453 /* check that the output is not closed */
7454 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
7455 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007456
7457 /* Set the currently running flag. */
7458 if (!HLUA_IS_RUNNING(hlua) &&
7459 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007460 /* Store the max amount of bytes that we can read. */
7461 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
7462
7463 /* We need to flush the request header. This left the body
7464 * for the Lua.
7465 */
7466
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007467 /* Read the maximum amount of data available. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007468 ret = co_getblk_nc(req, &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007469 if (ret == -1)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007470 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007471
7472 /* No data available, ask for more data. */
7473 if (ret == 1)
7474 len2 = 0;
7475 if (ret == 0)
7476 len1 = 0;
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02007477 if (len1 + len2 < strm->txn->req.eoh + strm->txn->req.eol) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007478 si_cant_get(si);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007479 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007480 }
7481
7482 /* skip the requests bytes. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007483 co_skip(req, strm->txn->req.eoh + strm->txn->req.eol);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007484 }
7485
7486 /* Executes The applet if it is not done. */
7487 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7488
7489 /* Execute the function. */
7490 switch (hlua_ctx_resume(hlua, 1)) {
7491 /* finished. */
7492 case HLUA_E_OK:
7493 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7494 break;
7495
7496 /* yield. */
7497 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007498 if (hlua->wake_time != TICK_ETERNITY)
7499 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007500 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007501
7502 /* finished with error. */
7503 case HLUA_E_ERRMSG:
7504 /* Display log. */
7505 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7506 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7507 lua_pop(hlua->T, 1);
7508 goto error;
7509
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007510 case HLUA_E_ETMOUT:
7511 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7512 rule->arg.hlua_rule->fcn.name);
7513 goto error;
7514
7515 case HLUA_E_NOMEM:
7516 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7517 rule->arg.hlua_rule->fcn.name);
7518 goto error;
7519
7520 case HLUA_E_YIELD: /* unexpected */
7521 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7522 rule->arg.hlua_rule->fcn.name);
7523 goto error;
7524
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007525 case HLUA_E_ERR:
7526 /* Display log. */
7527 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7528 rule->arg.hlua_rule->fcn.name);
7529 goto error;
7530
7531 default:
7532 goto error;
7533 }
7534 }
7535
7536 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007537 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7538 goto done;
7539
Christopher Fauletcc26b132018-12-18 21:20:57 +01007540 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7541 goto error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007542
7543 /* We must send the final chunk. */
7544 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
7545 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
7546
7547 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02007548 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007549
7550 /* critical error. */
7551 if (ret == -2 || ret == -3) {
7552 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
7553 rule->arg.hlua_rule->fcn.name);
7554 goto error;
7555 }
7556
7557 /* no enough space error. */
7558 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01007559 si_rx_room_blk(si);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007560 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007561 }
7562
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007563 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7564 ctx->ctx.hlua_apphttp.flags |= (APPLET_LAST_CHK|APPLET_RSP_SENT);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007565 }
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007566 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007567
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007568 done:
7569 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
7570 if (!(res->flags & CF_SHUTR)) {
7571 res->flags |= CF_READ_NULL;
7572 si_shutr(si);
7573 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007574
7575 /* eat the whole request */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007576 if (co_data(req))
7577 co_skip(req, co_data(req));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007578 }
7579
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007580 out:
7581 return;
7582
7583 error:
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007584
7585 /* If we are in HTTP mode, and we are not send any
7586 * data, return a 500 server error in best effort:
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007587 * if there is no room available in the buffer,
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007588 * just close the connection.
7589 */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007590 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
7591 channel_erase(res);
7592 ci_putblk(res, error_500, strlen(error_500));
7593 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007594 if (!(strm->flags & SF_ERR_MASK))
7595 strm->flags |= SF_ERR_RESOURCE;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007596 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007597 goto done;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007598}
7599
7600static void hlua_applet_http_release(struct appctx *ctx)
7601{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007602 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007603 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007604 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007605 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007606}
7607
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007608/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
7609 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007610 *
7611 * This function can fail with an abort() due to an Lua critical error.
7612 * We are in the configuration parsing process of HAProxy, this abort() is
7613 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007614 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007615static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
7616 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007617{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007618 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007619 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007620
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007621 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007622 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007623 if (!rule->arg.hlua_rule) {
7624 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007625 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007626 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007627
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007628 /* Memory for arguments. */
7629 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
7630 if (!rule->arg.hlua_rule->args) {
7631 memprintf(err, "out of memory error");
7632 return ACT_RET_PRS_ERR;
7633 }
7634
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007635 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007636 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007637
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007638 /* Expect some arguments */
7639 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007640 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007641 memprintf(err, "expect %d arguments", fcn->nargs);
7642 return ACT_RET_PRS_ERR;
7643 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007644 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007645 if (!rule->arg.hlua_rule->args[i]) {
7646 memprintf(err, "out of memory error");
7647 return ACT_RET_PRS_ERR;
7648 }
7649 (*cur_arg)++;
7650 }
7651 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007652
Thierry FOURNIER42148732015-09-02 17:17:33 +02007653 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007654 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007655 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007656}
7657
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007658static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
7659 struct act_rule *rule, char **err)
7660{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007661 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007662
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007663 /* HTTP applets are forbidden in tcp-request rules.
7664 * HTTP applet request requires everything initilized by
7665 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
7666 * The applet will be immediately initilized, but its before
7667 * the call of this analyzer.
7668 */
7669 if (rule->from != ACT_F_HTTP_REQ) {
7670 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
7671 return ACT_RET_PRS_ERR;
7672 }
7673
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007674 /* Memory for the rule. */
7675 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7676 if (!rule->arg.hlua_rule) {
7677 memprintf(err, "out of memory error");
7678 return ACT_RET_PRS_ERR;
7679 }
7680
7681 /* Reference the Lua function and store the reference. */
7682 rule->arg.hlua_rule->fcn = *fcn;
7683
7684 /* TODO: later accept arguments. */
7685 rule->arg.hlua_rule->args = NULL;
7686
7687 /* Add applet pointer in the rule. */
7688 rule->applet.obj_type = OBJ_TYPE_APPLET;
7689 rule->applet.name = fcn->name;
7690 rule->applet.init = hlua_applet_http_init;
7691 rule->applet.fct = hlua_applet_http_fct;
7692 rule->applet.release = hlua_applet_http_release;
7693 rule->applet.timeout = hlua_timeout_applet;
7694
7695 return ACT_RET_PRS_OK;
7696}
7697
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007698/* This function is an LUA binding used for registering
7699 * "sample-conv" functions. It expects a converter name used
7700 * in the haproxy configuration file, and an LUA function.
7701 */
7702__LJMP static int hlua_register_action(lua_State *L)
7703{
7704 struct action_kw_list *akl;
7705 const char *name;
7706 int ref;
7707 int len;
7708 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007709 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007710
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007711 /* Initialise the number of expected arguments at 0. */
7712 nargs = 0;
7713
7714 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7715 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007716
7717 /* First argument : converter name. */
7718 name = MAY_LJMP(luaL_checkstring(L, 1));
7719
7720 /* Second argument : environment. */
7721 if (lua_type(L, 2) != LUA_TTABLE)
7722 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7723
7724 /* Third argument : lua function. */
7725 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7726
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007727 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007728 if (lua_gettop(L) >= 4)
7729 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
7730
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007731 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007732 lua_pushnil(L);
7733 while (lua_next(L, 2) != 0) {
7734 if (lua_type(L, -1) != LUA_TSTRING)
7735 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7736
7737 /* Check required environment. Only accepted "http" or "tcp". */
7738 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007739 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007740 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007741 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007742 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007743 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007744 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007745
7746 /* Fill fcn. */
7747 fcn->name = strdup(name);
7748 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007749 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007750 fcn->function_ref = ref;
7751
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007752 /* Set the expected number od arguments. */
7753 fcn->nargs = nargs;
7754
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007755 /* List head */
7756 akl->list.n = akl->list.p = NULL;
7757
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007758 /* action keyword. */
7759 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007760 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007761 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007762 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007763
7764 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7765
7766 akl->kw[0].match_pfx = 0;
7767 akl->kw[0].private = fcn;
7768 akl->kw[0].parse = action_register_lua;
7769
7770 /* select the action registering point. */
7771 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
7772 tcp_req_cont_keywords_register(akl);
7773 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
7774 tcp_res_cont_keywords_register(akl);
7775 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
7776 http_req_keywords_register(akl);
7777 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
7778 http_res_keywords_register(akl);
7779 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007780 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007781 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
7782 "are expected.", lua_tostring(L, -1)));
7783
7784 /* pop the environment string. */
7785 lua_pop(L, 1);
7786 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007787 return ACT_RET_PRS_OK;
7788}
7789
7790static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7791 struct act_rule *rule, char **err)
7792{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007793 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007794
Christopher Fauleteb709802019-04-11 22:04:08 +02007795 if (px->mode == PR_MODE_HTTP && (px->options2 & PR_O2_USE_HTX)) {
Christopher Fauletafd8f102018-11-08 11:34:21 +01007796 memprintf(err, "Lua services cannot be used when the HTX internal representation is enabled");
7797 return ACT_RET_PRS_ERR;
7798 }
7799
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007800 /* Memory for the rule. */
7801 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7802 if (!rule->arg.hlua_rule) {
7803 memprintf(err, "out of memory error");
7804 return ACT_RET_PRS_ERR;
7805 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007806
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007807 /* Reference the Lua function and store the reference. */
7808 rule->arg.hlua_rule->fcn = *fcn;
7809
7810 /* TODO: later accept arguments. */
7811 rule->arg.hlua_rule->args = NULL;
7812
7813 /* Add applet pointer in the rule. */
7814 rule->applet.obj_type = OBJ_TYPE_APPLET;
7815 rule->applet.name = fcn->name;
7816 rule->applet.init = hlua_applet_tcp_init;
7817 rule->applet.fct = hlua_applet_tcp_fct;
7818 rule->applet.release = hlua_applet_tcp_release;
7819 rule->applet.timeout = hlua_timeout_applet;
7820
7821 return 0;
7822}
7823
7824/* This function is an LUA binding used for registering
7825 * "sample-conv" functions. It expects a converter name used
7826 * in the haproxy configuration file, and an LUA function.
7827 */
7828__LJMP static int hlua_register_service(lua_State *L)
7829{
7830 struct action_kw_list *akl;
7831 const char *name;
7832 const char *env;
7833 int ref;
7834 int len;
7835 struct hlua_function *fcn;
7836
7837 MAY_LJMP(check_args(L, 3, "register_service"));
7838
7839 /* First argument : converter name. */
7840 name = MAY_LJMP(luaL_checkstring(L, 1));
7841
7842 /* Second argument : environment. */
7843 env = MAY_LJMP(luaL_checkstring(L, 2));
7844
7845 /* Third argument : lua function. */
7846 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7847
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007848 /* Allocate and fill the sample fetch keyword struct. */
7849 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7850 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007851 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007852 fcn = calloc(1, sizeof(*fcn));
7853 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007854 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007855
7856 /* Fill fcn. */
7857 len = strlen("<lua.>") + strlen(name) + 1;
7858 fcn->name = calloc(1, len);
7859 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007860 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007861 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7862 fcn->function_ref = ref;
7863
7864 /* List head */
7865 akl->list.n = akl->list.p = NULL;
7866
7867 /* converter keyword. */
7868 len = strlen("lua.") + strlen(name) + 1;
7869 akl->kw[0].kw = calloc(1, len);
7870 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007871 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007872
7873 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7874
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007875 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007876 if (strcmp(env, "tcp") == 0)
7877 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007878 else if (strcmp(env, "http") == 0)
7879 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007880 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007881 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007882 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007883
7884 akl->kw[0].match_pfx = 0;
7885 akl->kw[0].private = fcn;
7886
7887 /* End of array. */
7888 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7889
7890 /* Register this new converter */
7891 service_keywords_register(akl);
7892
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007893 return 0;
7894}
7895
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007896/* This function initialises Lua cli handler. It copies the
7897 * arguments in the Lua stack and create channel IO objects.
7898 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007899static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007900{
7901 struct hlua *hlua;
7902 struct hlua_function *fcn;
7903 int i;
7904 const char *error;
7905
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007906 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007907 appctx->ctx.hlua_cli.fcn = private;
7908
Willy Tarreaubafbe012017-11-24 17:34:44 +01007909 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007910 if (!hlua) {
7911 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007912 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007913 }
7914 HLUA_INIT(hlua);
7915 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007916
7917 /* Create task used by signal to wakeup applets.
7918 * We use the same wakeup fonction than the Lua applet_tcp and
7919 * applet_http. It is absolutely compatible.
7920 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007921 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007922 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007923 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007924 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007925 }
7926 appctx->ctx.hlua_cli.task->nice = 0;
7927 appctx->ctx.hlua_cli.task->context = appctx;
7928 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7929
7930 /* Initialises the Lua context */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007931 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007932 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007933 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007934 }
7935
7936 /* The following Lua calls can fail. */
7937 if (!SET_SAFE_LJMP(hlua->T)) {
7938 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7939 error = lua_tostring(hlua->T, -1);
7940 else
7941 error = "critical error";
7942 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7943 goto error;
7944 }
7945
7946 /* Check stack available size. */
7947 if (!lua_checkstack(hlua->T, 2)) {
7948 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7949 goto error;
7950 }
7951
7952 /* Restore the function in the stack. */
7953 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7954
7955 /* Once the arguments parsed, the CLI is like an AppletTCP,
7956 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007957 */
7958 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7959 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7960 goto error;
7961 }
7962 hlua->nargs = 1;
7963
7964 /* push keywords in the stack. */
7965 for (i = 0; *args[i]; i++) {
7966 /* Check stack available size. */
7967 if (!lua_checkstack(hlua->T, 1)) {
7968 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7969 goto error;
7970 }
7971 lua_pushstring(hlua->T, args[i]);
7972 hlua->nargs++;
7973 }
7974
7975 /* We must initialize the execution timeouts. */
7976 hlua->max_time = hlua_timeout_session;
7977
7978 /* At this point the execution is safe. */
7979 RESET_SAFE_LJMP(hlua->T);
7980
7981 /* It's ok */
7982 return 0;
7983
7984 /* It's not ok. */
7985error:
7986 RESET_SAFE_LJMP(hlua->T);
7987 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007988 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007989 return 1;
7990}
7991
7992static int hlua_cli_io_handler_fct(struct appctx *appctx)
7993{
7994 struct hlua *hlua;
7995 struct stream_interface *si;
7996 struct hlua_function *fcn;
7997
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007998 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007999 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01008000 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008001
8002 /* If the stream is disconnect or closed, ldo nothing. */
8003 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8004 return 1;
8005
8006 /* Execute the function. */
8007 switch (hlua_ctx_resume(hlua, 1)) {
8008
8009 /* finished. */
8010 case HLUA_E_OK:
8011 return 1;
8012
8013 /* yield. */
8014 case HLUA_E_AGAIN:
8015 /* We want write. */
8016 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01008017 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008018 /* Set the timeout. */
8019 if (hlua->wake_time != TICK_ETERNITY)
8020 task_schedule(hlua->task, hlua->wake_time);
8021 return 0;
8022
8023 /* finished with error. */
8024 case HLUA_E_ERRMSG:
8025 /* Display log. */
8026 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
8027 fcn->name, lua_tostring(hlua->T, -1));
8028 lua_pop(hlua->T, 1);
8029 return 1;
8030
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008031 case HLUA_E_ETMOUT:
8032 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
8033 fcn->name);
8034 return 1;
8035
8036 case HLUA_E_NOMEM:
8037 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
8038 fcn->name);
8039 return 1;
8040
8041 case HLUA_E_YIELD: /* unexpected */
8042 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
8043 fcn->name);
8044 return 1;
8045
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008046 case HLUA_E_ERR:
8047 /* Display log. */
8048 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
8049 fcn->name);
8050 return 1;
8051
8052 default:
8053 return 1;
8054 }
8055
8056 return 1;
8057}
8058
8059static void hlua_cli_io_release_fct(struct appctx *appctx)
8060{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008061 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008062 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008063}
8064
8065/* This function is an LUA binding used for registering
8066 * new keywords in the cli. It expects a list of keywords
8067 * which are the "path". It is limited to 5 keywords. A
8068 * description of the command, a function to be executed
8069 * for the parsing and a function for io handlers.
8070 */
8071__LJMP static int hlua_register_cli(lua_State *L)
8072{
8073 struct cli_kw_list *cli_kws;
8074 const char *message;
8075 int ref_io;
8076 int len;
8077 struct hlua_function *fcn;
8078 int index;
8079 int i;
8080
8081 MAY_LJMP(check_args(L, 3, "register_cli"));
8082
8083 /* First argument : an array of maximum 5 keywords. */
8084 if (!lua_istable(L, 1))
8085 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
8086
8087 /* Second argument : string with contextual message. */
8088 message = MAY_LJMP(luaL_checkstring(L, 2));
8089
8090 /* Third and fourth argument : lua function. */
8091 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
8092
8093 /* Allocate and fill the sample fetch keyword struct. */
8094 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
8095 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008096 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008097 fcn = calloc(1, sizeof(*fcn));
8098 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008099 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008100
8101 /* Fill path. */
8102 index = 0;
8103 lua_pushnil(L);
8104 while(lua_next(L, 1) != 0) {
8105 if (index >= 5)
8106 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
8107 if (lua_type(L, -1) != LUA_TSTRING)
8108 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
8109 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
8110 if (!cli_kws->kw[0].str_kw[index])
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 index++;
8113 lua_pop(L, 1);
8114 }
8115
8116 /* Copy help message. */
8117 cli_kws->kw[0].usage = strdup(message);
8118 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008119 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008120
8121 /* Fill fcn io handler. */
8122 len = strlen("<lua.cli>") + 1;
8123 for (i = 0; i < index; i++)
8124 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
8125 fcn->name = calloc(1, len);
8126 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008127 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008128 strncat((char *)fcn->name, "<lua.cli", len);
8129 for (i = 0; i < index; i++) {
8130 strncat((char *)fcn->name, ".", len);
8131 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
8132 }
8133 strncat((char *)fcn->name, ">", len);
8134 fcn->function_ref = ref_io;
8135
8136 /* Fill last entries. */
8137 cli_kws->kw[0].private = fcn;
8138 cli_kws->kw[0].parse = hlua_cli_parse_fct;
8139 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
8140 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
8141
8142 /* Register this new converter */
8143 cli_register_kw(cli_kws);
8144
8145 return 0;
8146}
8147
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008148static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
8149 struct proxy *defpx, const char *file, int line,
8150 char **err, unsigned int *timeout)
8151{
8152 const char *error;
8153
8154 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +02008155 if (error == PARSE_TIME_OVER) {
8156 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
8157 args[1], args[0]);
8158 return -1;
8159 }
8160 else if (error == PARSE_TIME_UNDER) {
8161 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
8162 args[1], args[0]);
8163 return -1;
8164 }
8165 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008166 memprintf(err, "%s: invalid timeout", args[0]);
8167 return -1;
8168 }
8169 return 0;
8170}
8171
8172static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
8173 struct proxy *defpx, const char *file, int line,
8174 char **err)
8175{
8176 return hlua_read_timeout(args, section_type, curpx, defpx,
8177 file, line, err, &hlua_timeout_session);
8178}
8179
8180static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
8181 struct proxy *defpx, const char *file, int line,
8182 char **err)
8183{
8184 return hlua_read_timeout(args, section_type, curpx, defpx,
8185 file, line, err, &hlua_timeout_task);
8186}
8187
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008188static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
8189 struct proxy *defpx, const char *file, int line,
8190 char **err)
8191{
8192 return hlua_read_timeout(args, section_type, curpx, defpx,
8193 file, line, err, &hlua_timeout_applet);
8194}
8195
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008196static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
8197 struct proxy *defpx, const char *file, int line,
8198 char **err)
8199{
8200 char *error;
8201
8202 hlua_nb_instruction = strtoll(args[1], &error, 10);
8203 if (*error != '\0') {
8204 memprintf(err, "%s: invalid number", args[0]);
8205 return -1;
8206 }
8207 return 0;
8208}
8209
Willy Tarreau32f61e22015-03-18 17:54:59 +01008210static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
8211 struct proxy *defpx, const char *file, int line,
8212 char **err)
8213{
8214 char *error;
8215
8216 if (*(args[1]) == 0) {
8217 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
8218 return -1;
8219 }
8220 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
8221 if (*error != '\0') {
8222 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
8223 return -1;
8224 }
8225 return 0;
8226}
8227
8228
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008229/* This function is called by the main configuration key "lua-load". It loads and
8230 * execute an lua file during the parsing of the HAProxy configuration file. It is
8231 * the main lua entry point.
8232 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008233 * This function runs with the HAProxy keywords API. It returns -1 if an error
8234 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008235 *
8236 * In some error case, LUA set an error message in top of the stack. This function
8237 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008238 *
8239 * This function can fail with an abort() due to an Lua critical error.
8240 * We are in the configuration parsing process of HAProxy, this abort() is
8241 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008242 */
8243static int hlua_load(char **args, int section_type, struct proxy *curpx,
8244 struct proxy *defpx, const char *file, int line,
8245 char **err)
8246{
8247 int error;
8248
8249 /* Just load and compile the file. */
8250 error = luaL_loadfile(gL.T, args[1]);
8251 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008252 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008253 lua_pop(gL.T, 1);
8254 return -1;
8255 }
8256
8257 /* If no syntax error where detected, execute the code. */
8258 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
8259 switch (error) {
8260 case LUA_OK:
8261 break;
8262 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008263 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008264 lua_pop(gL.T, 1);
8265 return -1;
8266 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008267 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008268 return -1;
8269 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008270 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008271 lua_pop(gL.T, 1);
8272 return -1;
8273 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008274 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008275 lua_pop(gL.T, 1);
8276 return -1;
8277 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008278 memprintf(err, "Lua unknonwn 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 }
8282
8283 return 0;
8284}
8285
8286/* configuration keywords declaration */
8287static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008288 { CFG_GLOBAL, "lua-load", hlua_load },
8289 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
8290 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02008291 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008292 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01008293 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008294 { 0, NULL, NULL },
8295}};
8296
Willy Tarreau0108d902018-11-25 19:14:37 +01008297INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
8298
Christopher Fauletafd8f102018-11-08 11:34:21 +01008299
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008300/* This function can fail with an abort() due to an Lua critical error.
8301 * We are in the initialisation process of HAProxy, this abort() is
8302 * tolerated.
8303 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008304int hlua_post_init()
8305{
8306 struct hlua_init_function *init;
8307 const char *msg;
8308 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008309 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008310
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008311 /* Call post initialisation function in safe environement. */
8312 if (!SET_SAFE_LJMP(gL.T)) {
8313 if (lua_type(gL.T, -1) == LUA_TSTRING)
8314 error = lua_tostring(gL.T, -1);
8315 else
8316 error = "critical error";
8317 fprintf(stderr, "Lua post-init: %s.\n", error);
8318 exit(1);
8319 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02008320
8321#if USE_OPENSSL
8322 /* Initialize SSL server. */
8323 if (socket_ssl.xprt->prepare_srv) {
8324 int saved_used_backed = global.ssl_used_backend;
8325 // don't affect maxconn automatic computation
8326 socket_ssl.xprt->prepare_srv(&socket_ssl);
8327 global.ssl_used_backend = saved_used_backed;
8328 }
8329#endif
8330
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008331 hlua_fcn_post_init(gL.T);
8332 RESET_SAFE_LJMP(gL.T);
8333
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008334 list_for_each_entry(init, &hlua_init_functions, l) {
8335 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
8336 ret = hlua_ctx_resume(&gL, 0);
8337 switch (ret) {
8338 case HLUA_E_OK:
8339 lua_pop(gL.T, -1);
8340 return 1;
8341 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008342 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008343 return 0;
8344 case HLUA_E_ERRMSG:
8345 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01008346 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008347 return 0;
8348 case HLUA_E_ERR:
8349 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008350 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008351 return 0;
8352 }
8353 }
8354 return 1;
8355}
8356
Willy Tarreau32f61e22015-03-18 17:54:59 +01008357/* The memory allocator used by the Lua stack. <ud> is a pointer to the
8358 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
8359 * is the previously allocated size or the kind of object in case of a new
8360 * allocation. <nsize> is the requested new size.
8361 */
8362static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
8363{
8364 struct hlua_mem_allocator *zone = ud;
8365
8366 if (nsize == 0) {
8367 /* it's a free */
8368 if (ptr)
8369 zone->allocated -= osize;
8370 free(ptr);
8371 return NULL;
8372 }
8373
8374 if (!ptr) {
8375 /* it's a new allocation */
8376 if (zone->limit && zone->allocated + nsize > zone->limit)
8377 return NULL;
8378
8379 ptr = malloc(nsize);
8380 if (ptr)
8381 zone->allocated += nsize;
8382 return ptr;
8383 }
8384
8385 /* it's a realloc */
8386 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
8387 return NULL;
8388
8389 ptr = realloc(ptr, nsize);
8390 if (ptr)
8391 zone->allocated += nsize - osize;
8392 return ptr;
8393}
8394
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008395/* Ithis function can fail with an abort() due to an Lua critical error.
8396 * We are in the initialisation process of HAProxy, this abort() is
8397 * tolerated.
8398 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008399void hlua_init(void)
8400{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008401 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008402 int idx;
8403 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008404 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008405 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008406 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008407#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008408 struct srv_kw *kw;
8409 int tmp_error;
8410 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008411 char *args[] = { /* SSL client configuration. */
8412 "ssl",
8413 "verify",
8414 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008415 NULL
8416 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008417#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008418
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008419 /* Init main lua stack. */
8420 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01008421 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01008422 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02008423 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008424 hlua_sethlua(&gL);
8425 gL.Tref = LUA_REFNIL;
8426 gL.task = NULL;
8427
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008428 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008429 * the Lua function can fail with an abort. We are in the initialisation
8430 * process of HAProxy, this abort() is tolerated.
8431 */
8432
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008433 /* Initialise lua. */
8434 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008435
Thierry Fournier75933d42016-01-21 09:30:18 +01008436 /* Set safe environment for the initialisation. */
8437 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008438 if (lua_type(gL.T, -1) == LUA_TSTRING)
8439 error_msg = lua_tostring(gL.T, -1);
8440 else
8441 error_msg = "critical error";
8442 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01008443 exit(1);
8444 }
8445
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008446 /*
8447 *
8448 * Create "core" object.
8449 *
8450 */
8451
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01008452 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008453 lua_newtable(gL.T);
8454
8455 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008456 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008457 hlua_class_const_int(gL.T, log_levels[i], i);
8458
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008459 /* Register special functions. */
8460 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008461 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008462 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008463 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008464 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008465 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008466 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008467 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01008468 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008469 hlua_class_function(gL.T, "sleep", hlua_sleep);
8470 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01008471 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
8472 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
8473 hlua_class_function(gL.T, "set_map", hlua_set_map);
8474 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008475 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008476 hlua_class_function(gL.T, "log", hlua_log);
8477 hlua_class_function(gL.T, "Debug", hlua_log_debug);
8478 hlua_class_function(gL.T, "Info", hlua_log_info);
8479 hlua_class_function(gL.T, "Warning", hlua_log_warning);
8480 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02008481 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01008482 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008483
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008484 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008485
8486 /*
8487 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008488 * Register class Map
8489 *
8490 */
8491
8492 /* This table entry is the object "Map" base. */
8493 lua_newtable(gL.T);
8494
8495 /* register pattern types. */
8496 for (i=0; i<PAT_MATCH_NUM; i++)
8497 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008498 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008499 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
8500 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008501 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008502
8503 /* register constructor. */
8504 hlua_class_function(gL.T, "new", hlua_map_new);
8505
8506 /* Create and fill the metatable. */
8507 lua_newtable(gL.T);
8508
8509 /* Create and fille the __index entry. */
8510 lua_pushstring(gL.T, "__index");
8511 lua_newtable(gL.T);
8512
8513 /* Register . */
8514 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
8515 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
8516
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008517 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008518
Thierry Fournier45e78d72016-02-19 18:34:46 +01008519 /* Register previous table in the registry with reference and named entry.
8520 * The function hlua_register_metatable() pops the stack, so we
8521 * previously create a copy of the table.
8522 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008523 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008524 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008525
8526 /* Assign the metatable to the mai Map object. */
8527 lua_setmetatable(gL.T, -2);
8528
8529 /* Set a name to the table. */
8530 lua_setglobal(gL.T, "Map");
8531
8532 /*
8533 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008534 * Register class Channel
8535 *
8536 */
8537
8538 /* Create and fill the metatable. */
8539 lua_newtable(gL.T);
8540
8541 /* Create and fille the __index entry. */
8542 lua_pushstring(gL.T, "__index");
8543 lua_newtable(gL.T);
8544
8545 /* Register . */
8546 hlua_class_function(gL.T, "get", hlua_channel_get);
8547 hlua_class_function(gL.T, "dup", hlua_channel_dup);
8548 hlua_class_function(gL.T, "getline", hlua_channel_getline);
8549 hlua_class_function(gL.T, "set", hlua_channel_set);
8550 hlua_class_function(gL.T, "append", hlua_channel_append);
8551 hlua_class_function(gL.T, "send", hlua_channel_send);
8552 hlua_class_function(gL.T, "forward", hlua_channel_forward);
8553 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
8554 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01008555 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008556
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008557 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008558
8559 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008560 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008561
8562 /*
8563 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008564 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008565 *
8566 */
8567
8568 /* Create and fill the metatable. */
8569 lua_newtable(gL.T);
8570
8571 /* Create and fille the __index entry. */
8572 lua_pushstring(gL.T, "__index");
8573 lua_newtable(gL.T);
8574
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008575 /* Browse existing fetches and create the associated
8576 * object method.
8577 */
8578 sf = NULL;
8579 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
8580
8581 /* Dont register the keywork if the arguments check function are
8582 * not safe during the runtime.
8583 */
8584 if ((sf->val_args != NULL) &&
8585 (sf->val_args != val_payload_lv) &&
8586 (sf->val_args != val_hdr))
8587 continue;
8588
8589 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8590 * by an underscore.
8591 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008592 strncpy(trash.area, sf->kw, trash.size);
8593 trash.area[trash.size - 1] = '\0';
8594 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008595 if (*p == '.' || *p == '-' || *p == '+')
8596 *p = '_';
8597
8598 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008599 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01008600 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008601 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008602 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008603 }
8604
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008605 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008606
8607 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008608 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008609
8610 /*
8611 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008612 * Register class Converters
8613 *
8614 */
8615
8616 /* Create and fill the metatable. */
8617 lua_newtable(gL.T);
8618
8619 /* Create and fill the __index entry. */
8620 lua_pushstring(gL.T, "__index");
8621 lua_newtable(gL.T);
8622
8623 /* Browse existing converters and create the associated
8624 * object method.
8625 */
8626 sc = NULL;
8627 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
8628 /* Dont register the keywork if the arguments check function are
8629 * not safe during the runtime.
8630 */
8631 if (sc->val_args != NULL)
8632 continue;
8633
8634 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8635 * by an underscore.
8636 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008637 strncpy(trash.area, sc->kw, trash.size);
8638 trash.area[trash.size - 1] = '\0';
8639 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008640 if (*p == '.' || *p == '-' || *p == '+')
8641 *p = '_';
8642
8643 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008644 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008645 lua_pushlightuserdata(gL.T, sc);
8646 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008647 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008648 }
8649
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008650 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008651
8652 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008653 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008654
8655 /*
8656 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008657 * Register class HTTP
8658 *
8659 */
8660
8661 /* Create and fill the metatable. */
8662 lua_newtable(gL.T);
8663
8664 /* Create and fille the __index entry. */
8665 lua_pushstring(gL.T, "__index");
8666 lua_newtable(gL.T);
8667
8668 /* Register Lua functions. */
8669 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
8670 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
8671 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
8672 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
8673 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
8674 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
8675 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
8676 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
8677 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
8678 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
8679
8680 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
8681 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
8682 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
8683 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
8684 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
8685 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02008686 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008687
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008688 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008689
8690 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008691 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008692
8693 /*
8694 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008695 * Register class AppletTCP
8696 *
8697 */
8698
8699 /* Create and fill the metatable. */
8700 lua_newtable(gL.T);
8701
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008702 /* Create and fille the __index entry. */
8703 lua_pushstring(gL.T, "__index");
8704 lua_newtable(gL.T);
8705
8706 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01008707 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
8708 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
8709 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
8710 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
8711 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008712 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
8713 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
8714 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008715
8716 lua_settable(gL.T, -3);
8717
8718 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008719 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008720
8721 /*
8722 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008723 * Register class AppletHTTP
8724 *
8725 */
8726
8727 /* Create and fill the metatable. */
8728 lua_newtable(gL.T);
8729
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008730 /* Create and fille the __index entry. */
8731 lua_pushstring(gL.T, "__index");
8732 lua_newtable(gL.T);
8733
8734 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01008735 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
8736 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008737 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
8738 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
8739 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008740 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
8741 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
8742 hlua_class_function(gL.T, "send", hlua_applet_http_send);
8743 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
8744 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
8745 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
8746
8747 lua_settable(gL.T, -3);
8748
8749 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008750 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008751
8752 /*
8753 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008754 * Register class TXN
8755 *
8756 */
8757
8758 /* Create and fill the metatable. */
8759 lua_newtable(gL.T);
8760
8761 /* Create and fille the __index entry. */
8762 lua_pushstring(gL.T, "__index");
8763 lua_newtable(gL.T);
8764
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008765 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04008766 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
8767 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
8768 hlua_class_function(gL.T, "set_var", hlua_set_var);
8769 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
8770 hlua_class_function(gL.T, "get_var", hlua_get_var);
8771 hlua_class_function(gL.T, "done", hlua_txn_done);
8772 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
8773 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
8774 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
8775 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
8776 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
8777 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
8778 hlua_class_function(gL.T, "log", hlua_txn_log);
8779 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
8780 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
8781 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
8782 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008783
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008784 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008785
8786 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008787 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008788
8789 /*
8790 *
8791 * Register class Socket
8792 *
8793 */
8794
8795 /* Create and fill the metatable. */
8796 lua_newtable(gL.T);
8797
8798 /* Create and fille the __index entry. */
8799 lua_pushstring(gL.T, "__index");
8800 lua_newtable(gL.T);
8801
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008802#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008803 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008804#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008805 hlua_class_function(gL.T, "connect", hlua_socket_connect);
8806 hlua_class_function(gL.T, "send", hlua_socket_send);
8807 hlua_class_function(gL.T, "receive", hlua_socket_receive);
8808 hlua_class_function(gL.T, "close", hlua_socket_close);
8809 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
8810 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8811 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8812 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8813
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008814 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008815
8816 /* Register the garbage collector entry. */
8817 lua_pushstring(gL.T, "__gc");
8818 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008819 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008820
8821 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008822 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008823
8824 /* Proxy and server configuration initialisation. */
8825 memset(&socket_proxy, 0, sizeof(socket_proxy));
8826 init_new_proxy(&socket_proxy);
8827 socket_proxy.parent = NULL;
8828 socket_proxy.last_change = now.tv_sec;
8829 socket_proxy.id = "LUA-SOCKET";
8830 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8831 socket_proxy.maxconn = 0;
8832 socket_proxy.accept = NULL;
8833 socket_proxy.options2 |= PR_O2_INDEPSTR;
8834 socket_proxy.srv = NULL;
8835 socket_proxy.conn_retries = 0;
8836 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8837
8838 /* Init TCP server: unchanged parameters */
8839 memset(&socket_tcp, 0, sizeof(socket_tcp));
8840 socket_tcp.next = NULL;
8841 socket_tcp.proxy = &socket_proxy;
8842 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8843 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008844 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008845 socket_tcp.priv_conns = NULL;
8846 socket_tcp.idle_conns = NULL;
8847 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008848 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008849 socket_tcp.last_change = 0;
8850 socket_tcp.id = "LUA-TCP-CONN";
8851 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8852 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8853 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
8854
8855 /* XXX: Copy default parameter from default server,
8856 * but the default server is not initialized.
8857 */
8858 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
8859 socket_tcp.minconn = socket_proxy.defsrv.minconn;
8860 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
8861 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
8862 socket_tcp.onerror = socket_proxy.defsrv.onerror;
8863 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8864 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
8865 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8866 socket_tcp.uweight = socket_proxy.defsrv.iweight;
8867 socket_tcp.iweight = socket_proxy.defsrv.iweight;
8868
8869 socket_tcp.check.status = HCHK_STATUS_INI;
8870 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
8871 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
8872 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
8873 socket_tcp.check.server = &socket_tcp;
8874
8875 socket_tcp.agent.status = HCHK_STATUS_INI;
8876 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
8877 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
8878 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
8879 socket_tcp.agent.server = &socket_tcp;
8880
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008881 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008882
8883#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008884 /* Init TCP server: unchanged parameters */
8885 memset(&socket_ssl, 0, sizeof(socket_ssl));
8886 socket_ssl.next = NULL;
8887 socket_ssl.proxy = &socket_proxy;
8888 socket_ssl.obj_type = OBJ_TYPE_SERVER;
8889 LIST_INIT(&socket_ssl.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008890 socket_ssl.pendconns = EB_ROOT;
Willy Tarreaub784b352019-02-07 14:48:24 +01008891 socket_ssl.priv_conns = NULL;
8892 socket_ssl.idle_conns = NULL;
8893 socket_ssl.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008894 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008895 socket_ssl.last_change = 0;
8896 socket_ssl.id = "LUA-SSL-CONN";
8897 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8898 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8899 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8900
8901 /* XXX: Copy default parameter from default server,
8902 * but the default server is not initialized.
8903 */
8904 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8905 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8906 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8907 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8908 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8909 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8910 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8911 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8912 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8913 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8914
8915 socket_ssl.check.status = HCHK_STATUS_INI;
8916 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8917 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8918 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8919 socket_ssl.check.server = &socket_ssl;
8920
8921 socket_ssl.agent.status = HCHK_STATUS_INI;
8922 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8923 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8924 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8925 socket_ssl.agent.server = &socket_ssl;
8926
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008927 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008928 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008929
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008930 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008931 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8932 /*
8933 *
8934 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008935 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008936 * features like client certificates and ssl_verify.
8937 *
8938 */
8939 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8940 if (tmp_error != 0) {
8941 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8942 abort(); /* This must be never arrives because the command line
8943 not editable by the user. */
8944 }
8945 idx += kw->skip;
8946 }
8947 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008948#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008949
8950 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008951}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008952
Willy Tarreau80713382018-11-26 10:19:54 +01008953static void hlua_register_build_options(void)
8954{
Willy Tarreaubb57d942016-12-21 19:04:56 +01008955 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +01008956
Willy Tarreaubb57d942016-12-21 19:04:56 +01008957 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8958 hap_register_build_opts(ptr, 1);
8959}
Willy Tarreau80713382018-11-26 10:19:54 +01008960
8961INITCALL0(STG_REGISTER, hlua_register_build_options);