blob: a2dde4b59fe6e9798822c64fad1fee2e92763731 [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;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003216
3217 MAY_LJMP(check_args(L, 1, "is_full"));
3218 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0136ebb2020-02-26 11:59:19 +01003219 /* ignore the reserve, we are not on a producer side (ie in an
3220 * applet).
3221 */
3222 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003223 return 1;
3224}
3225
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003226/* Just returns the number of bytes available in the output
3227 * side of the buffer. This function never fails.
3228 */
3229__LJMP static int hlua_channel_get_out_len(lua_State *L)
3230{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003231 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003232
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003233 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003234 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003235 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003236 return 1;
3237}
3238
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003239/*
3240 *
3241 *
3242 * Class Fetches
3243 *
3244 *
3245 */
3246
3247/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003248 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003249 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003250__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003251{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003252 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003253}
3254
3255/* This function creates and push in the stack a fetch object according
3256 * with a current TXN.
3257 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003258static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003259{
Willy Tarreau7073c472015-04-06 11:15:40 +02003260 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003261
3262 /* Check stack size. */
3263 if (!lua_checkstack(L, 3))
3264 return 0;
3265
3266 /* Create the object: obj[0] = userdata.
3267 * Note that the base of the Fetches object is the
3268 * transaction object.
3269 */
3270 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003271 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003272 lua_rawseti(L, -2, 0);
3273
Willy Tarreau7073c472015-04-06 11:15:40 +02003274 hsmp->s = txn->s;
3275 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003276 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003277 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003278
3279 /* Pop a class sesison metatable and affect it to the userdata. */
3280 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3281 lua_setmetatable(L, -2);
3282
3283 return 1;
3284}
3285
3286/* This function is an LUA binding. It is called with each sample-fetch.
3287 * It uses closure argument to store the associated sample-fetch. It
3288 * returns only one argument or throws an error. An error is thrown
3289 * only if an error is encountered during the argument parsing. If
3290 * the "sample-fetch" function fails, nil is returned.
3291 */
3292__LJMP static int hlua_run_sample_fetch(lua_State *L)
3293{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003294 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003295 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003296 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003297 int i;
3298 struct sample smp;
3299
3300 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003301 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003302
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003303 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003304 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003305
Thierry FOURNIERca988662015-12-20 18:43:03 +01003306 /* Check execution authorization. */
3307 if (f->use & SMP_USE_HTTP_ANY &&
3308 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3309 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3310 "is not available in Lua services", f->kw);
3311 WILL_LJMP(lua_error(L));
3312 }
3313
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003314 /* Get extra arguments. */
3315 for (i = 0; i < lua_gettop(L) - 1; i++) {
3316 if (i >= ARGM_NBARGS)
3317 break;
3318 hlua_lua2arg(L, i + 2, &args[i]);
3319 }
3320 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003321 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003322
3323 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003324 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003325
3326 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003327 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003328 lua_pushfstring(L, "error in arguments");
3329 WILL_LJMP(lua_error(L));
3330 }
3331
3332 /* Initialise the sample. */
3333 memset(&smp, 0, sizeof(smp));
3334
3335 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003336 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003337 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003338 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003339 lua_pushstring(L, "");
3340 else
3341 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003342 return 1;
3343 }
3344
3345 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003346 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003347 hlua_smp2lua_str(L, &smp);
3348 else
3349 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003350 return 1;
3351}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003352
3353/*
3354 *
3355 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003356 * Class Converters
3357 *
3358 *
3359 */
3360
3361/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003362 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003363 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003364__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003365{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003366 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003367}
3368
3369/* This function creates and push in the stack a Converters object
3370 * according with a current TXN.
3371 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003372static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003373{
Willy Tarreau7073c472015-04-06 11:15:40 +02003374 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003375
3376 /* Check stack size. */
3377 if (!lua_checkstack(L, 3))
3378 return 0;
3379
3380 /* Create the object: obj[0] = userdata.
3381 * Note that the base of the Converters object is the
3382 * same than the TXN object.
3383 */
3384 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003385 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003386 lua_rawseti(L, -2, 0);
3387
Willy Tarreau7073c472015-04-06 11:15:40 +02003388 hsmp->s = txn->s;
3389 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003390 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003391 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003392
Willy Tarreau87b09662015-04-03 00:22:06 +02003393 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003394 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3395 lua_setmetatable(L, -2);
3396
3397 return 1;
3398}
3399
3400/* This function is an LUA binding. It is called with each converter.
3401 * It uses closure argument to store the associated converter. It
3402 * returns only one argument or throws an error. An error is thrown
3403 * only if an error is encountered during the argument parsing. If
3404 * the converter function function fails, nil is returned.
3405 */
3406__LJMP static int hlua_run_sample_conv(lua_State *L)
3407{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003408 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003409 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003410 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003411 int i;
3412 struct sample smp;
3413
3414 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003415 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003416
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003417 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003418 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003419
3420 /* Get extra arguments. */
3421 for (i = 0; i < lua_gettop(L) - 2; i++) {
3422 if (i >= ARGM_NBARGS)
3423 break;
3424 hlua_lua2arg(L, i + 3, &args[i]);
3425 }
3426 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003427 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003428
3429 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003430 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003431
3432 /* Run the special args checker. */
3433 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3434 hlua_pusherror(L, "error in arguments");
3435 WILL_LJMP(lua_error(L));
3436 }
3437
3438 /* Initialise the sample. */
3439 if (!hlua_lua2smp(L, 2, &smp)) {
3440 hlua_pusherror(L, "error in the input argument");
3441 WILL_LJMP(lua_error(L));
3442 }
3443
Willy Tarreau1777ea62016-03-10 16:15:46 +01003444 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3445
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003446 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003447 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003448 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003449 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003450 WILL_LJMP(lua_error(L));
3451 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003452 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3453 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003454 hlua_pusherror(L, "error during the input argument casting");
3455 WILL_LJMP(lua_error(L));
3456 }
3457
3458 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003459 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003460 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003461 lua_pushstring(L, "");
3462 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003463 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003464 return 1;
3465 }
3466
3467 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003468 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003469 hlua_smp2lua_str(L, &smp);
3470 else
3471 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003472 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003473}
3474
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003475/*
3476 *
3477 *
3478 * Class AppletTCP
3479 *
3480 *
3481 */
3482
3483/* Returns a struct hlua_txn if the stack entry "ud" is
3484 * a class stream, otherwise it throws an error.
3485 */
3486__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3487{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003488 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003489}
3490
3491/* This function creates and push in the stack an Applet object
3492 * according with a current TXN.
3493 */
3494static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3495{
3496 struct hlua_appctx *appctx;
3497 struct stream_interface *si = ctx->owner;
3498 struct stream *s = si_strm(si);
3499 struct proxy *p = s->be;
3500
3501 /* Check stack size. */
3502 if (!lua_checkstack(L, 3))
3503 return 0;
3504
3505 /* Create the object: obj[0] = userdata.
3506 * Note that the base of the Converters object is the
3507 * same than the TXN object.
3508 */
3509 lua_newtable(L);
3510 appctx = lua_newuserdata(L, sizeof(*appctx));
3511 lua_rawseti(L, -2, 0);
3512 appctx->appctx = ctx;
3513 appctx->htxn.s = s;
3514 appctx->htxn.p = p;
3515
3516 /* Create the "f" field that contains a list of fetches. */
3517 lua_pushstring(L, "f");
3518 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3519 return 0;
3520 lua_settable(L, -3);
3521
3522 /* Create the "sf" field that contains a list of stringsafe fetches. */
3523 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003524 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003525 return 0;
3526 lua_settable(L, -3);
3527
3528 /* Create the "c" field that contains a list of converters. */
3529 lua_pushstring(L, "c");
3530 if (!hlua_converters_new(L, &appctx->htxn, 0))
3531 return 0;
3532 lua_settable(L, -3);
3533
3534 /* Create the "sc" field that contains a list of stringsafe converters. */
3535 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003536 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003537 return 0;
3538 lua_settable(L, -3);
3539
3540 /* Pop a class stream metatable and affect it to the table. */
3541 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3542 lua_setmetatable(L, -2);
3543
3544 return 1;
3545}
3546
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003547__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3548{
3549 struct hlua_appctx *appctx;
3550 struct stream *s;
3551 const char *name;
3552 size_t len;
3553 struct sample smp;
3554
3555 MAY_LJMP(check_args(L, 3, "set_var"));
3556
3557 /* It is useles to retrieve the stream, but this function
3558 * runs only in a stream context.
3559 */
3560 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3561 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3562 s = appctx->htxn.s;
3563
3564 /* Converts the third argument in a sample. */
3565 hlua_lua2smp(L, 3, &smp);
3566
3567 /* Store the sample in a variable. */
3568 smp_set_owner(&smp, s->be, s->sess, s, 0);
3569 vars_set_by_name(name, len, &smp);
3570 return 0;
3571}
3572
3573__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3574{
3575 struct hlua_appctx *appctx;
3576 struct stream *s;
3577 const char *name;
3578 size_t len;
3579 struct sample smp;
3580
3581 MAY_LJMP(check_args(L, 2, "unset_var"));
3582
3583 /* It is useles to retrieve the stream, but this function
3584 * runs only in a stream context.
3585 */
3586 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3587 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3588 s = appctx->htxn.s;
3589
3590 /* Unset the variable. */
3591 smp_set_owner(&smp, s->be, s->sess, s, 0);
3592 vars_unset_by_name(name, len, &smp);
3593 return 0;
3594}
3595
3596__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3597{
3598 struct hlua_appctx *appctx;
3599 struct stream *s;
3600 const char *name;
3601 size_t len;
3602 struct sample smp;
3603
3604 MAY_LJMP(check_args(L, 2, "get_var"));
3605
3606 /* It is useles to retrieve the stream, but this function
3607 * runs only in a stream context.
3608 */
3609 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3610 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3611 s = appctx->htxn.s;
3612
3613 smp_set_owner(&smp, s->be, s->sess, s, 0);
3614 if (!vars_get_by_name(name, len, &smp)) {
3615 lua_pushnil(L);
3616 return 1;
3617 }
3618
3619 return hlua_smp2lua(L, &smp);
3620}
3621
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003622__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3623{
3624 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3625 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003626 struct hlua *hlua;
3627
3628 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003629 if (!s->hlua)
3630 return 0;
3631 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003632
3633 MAY_LJMP(check_args(L, 2, "set_priv"));
3634
3635 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003636 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003637
3638 /* Get and store new value. */
3639 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3640 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3641
3642 return 0;
3643}
3644
3645__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3646{
3647 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3648 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003649 struct hlua *hlua;
3650
3651 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003652 if (!s->hlua) {
3653 lua_pushnil(L);
3654 return 1;
3655 }
3656 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003657
3658 /* Push configuration index in the stack. */
3659 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3660
3661 return 1;
3662}
3663
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003664/* If expected data not yet available, it returns a yield. This function
3665 * consumes the data in the buffer. It returns a string containing the
3666 * data. This string can be empty.
3667 */
3668__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3669{
3670 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3671 struct stream_interface *si = appctx->appctx->owner;
3672 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003673 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003674 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003675 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003676 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003677
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003678 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003679 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003680
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003681 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003682 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003683 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003684 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003685 }
3686
3687 /* End of data: commit the total strings and return. */
3688 if (ret < 0) {
3689 luaL_pushresult(&appctx->b);
3690 return 1;
3691 }
3692
3693 /* Ensure that the block 2 length is usable. */
3694 if (ret == 1)
3695 len2 = 0;
3696
3697 /* dont check the max length read and dont check. */
3698 luaL_addlstring(&appctx->b, blk1, len1);
3699 luaL_addlstring(&appctx->b, blk2, len2);
3700
3701 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003702 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003703 luaL_pushresult(&appctx->b);
3704 return 1;
3705}
3706
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003707/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003708__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3709{
3710 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3711
3712 /* Initialise the string catenation. */
3713 luaL_buffinit(L, &appctx->b);
3714
3715 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3716}
3717
3718/* If expected data not yet available, it returns a yield. This function
3719 * consumes the data in the buffer. It returns a string containing the
3720 * data. This string can be empty.
3721 */
3722__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3723{
3724 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3725 struct stream_interface *si = appctx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003726 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003727 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003728 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003729 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003730 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003731 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003732
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003733 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003734 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003735
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003736 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003737 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003738 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003739 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003740 }
3741
3742 /* End of data: commit the total strings and return. */
3743 if (ret < 0) {
3744 luaL_pushresult(&appctx->b);
3745 return 1;
3746 }
3747
3748 /* Ensure that the block 2 length is usable. */
3749 if (ret == 1)
3750 len2 = 0;
3751
3752 if (len == -1) {
3753
3754 /* If len == -1, catenate all the data avalaile and
3755 * yield because we want to get all the data until
3756 * the end of data stream.
3757 */
3758 luaL_addlstring(&appctx->b, blk1, len1);
3759 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003760 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003761 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003762 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003763
3764 } else {
3765
3766 /* Copy the fisrt block caping to the length required. */
3767 if (len1 > len)
3768 len1 = len;
3769 luaL_addlstring(&appctx->b, blk1, len1);
3770 len -= len1;
3771
3772 /* Copy the second block. */
3773 if (len2 > len)
3774 len2 = len;
3775 luaL_addlstring(&appctx->b, blk2, len2);
3776 len -= len2;
3777
3778 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003779 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003780
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003781 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003782 if (len > 0) {
3783 lua_pushinteger(L, len);
3784 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003785 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003786 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003787 }
3788
3789 /* return the result. */
3790 luaL_pushresult(&appctx->b);
3791 return 1;
3792 }
3793
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003794 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003795 hlua_pusherror(L, "Lua: internal error");
3796 WILL_LJMP(lua_error(L));
3797 return 0;
3798}
3799
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003800/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003801__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3802{
3803 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3804 int len = -1;
3805
3806 if (lua_gettop(L) > 2)
3807 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3808 if (lua_gettop(L) >= 2) {
3809 len = MAY_LJMP(luaL_checkinteger(L, 2));
3810 lua_pop(L, 1);
3811 }
3812
3813 /* Confirm or set the required length */
3814 lua_pushinteger(L, len);
3815
3816 /* Initialise the string catenation. */
3817 luaL_buffinit(L, &appctx->b);
3818
3819 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3820}
3821
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003822/* Append data in the output side of the buffer. This data is immediately
3823 * sent. The function returns the amount of data written. If the buffer
3824 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003825 * if the channel is closed.
3826 */
3827__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3828{
3829 size_t len;
3830 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3831 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3832 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3833 struct stream_interface *si = appctx->appctx->owner;
3834 struct channel *chn = si_ic(si);
3835 int max;
3836
3837 /* Get the max amount of data which can write as input in the channel. */
3838 max = channel_recv_max(chn);
3839 if (max > (len - l))
3840 max = len - l;
3841
3842 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003843 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003844
3845 /* update counters. */
3846 l += max;
3847 lua_pop(L, 1);
3848 lua_pushinteger(L, l);
3849
3850 /* If some data is not send, declares the situation to the
3851 * applet, and returns a yield.
3852 */
3853 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01003854 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003855 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003856 }
3857
3858 return 1;
3859}
3860
3861/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3862 * yield the LUA process, and resume it without checking the
3863 * input arguments.
3864 */
3865__LJMP static int hlua_applet_tcp_send(lua_State *L)
3866{
3867 MAY_LJMP(check_args(L, 2, "send"));
3868 lua_pushinteger(L, 0);
3869
3870 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3871}
3872
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003873/*
3874 *
3875 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003876 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003877 *
3878 *
3879 */
3880
3881/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003882 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003883 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003884__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003885{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003886 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003887}
3888
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003889/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003890 * according with a current TXN.
3891 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003892static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003893{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003894 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003895 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003896 struct stream_interface *si = ctx->owner;
3897 struct stream *s = si_strm(si);
3898 struct proxy *px = s->be;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003899
3900 /* Check stack size. */
3901 if (!lua_checkstack(L, 3))
3902 return 0;
3903
3904 /* Create the object: obj[0] = userdata.
3905 * Note that the base of the Converters object is the
3906 * same than the TXN object.
3907 */
3908 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003909 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003910 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003911 appctx->appctx = ctx;
3912 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003913 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003914 appctx->htxn.s = s;
3915 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003916
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003917 /* Create the "f" field that contains a list of fetches. */
3918 lua_pushstring(L, "f");
3919 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3920 return 0;
3921 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003922
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003923 /* Create the "sf" field that contains a list of stringsafe fetches. */
3924 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003925 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003926 return 0;
3927 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003928
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003929 /* Create the "c" field that contains a list of converters. */
3930 lua_pushstring(L, "c");
3931 if (!hlua_converters_new(L, &appctx->htxn, 0))
3932 return 0;
3933 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003934
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003935 /* Create the "sc" field that contains a list of stringsafe converters. */
3936 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003937 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003938 return 0;
3939 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003940
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003941 if (IS_HTX_STRM(s)) {
3942 /* HTX version */
3943 struct htx *htx = htxbuf(&s->req.buf);
Christopher Faulet29f17582019-05-23 11:03:26 +02003944 struct htx_blk *blk;
3945 struct htx_sl *sl;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003946 struct ist path;
3947 unsigned long long len = 0;
3948 int32_t pos;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003949
Christopher Faulet29f17582019-05-23 11:03:26 +02003950 blk = htx_get_first_blk(htx);
Christopher Faulet43a686d2019-11-18 15:50:25 +01003951 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Faulet29f17582019-05-23 11:03:26 +02003952 sl = htx_get_blk_ptr(htx, blk);
3953
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003954 /* Stores the request method. */
3955 lua_pushstring(L, "method");
3956 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
3957 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003958
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003959 /* Stores the http version. */
3960 lua_pushstring(L, "version");
3961 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
3962 lua_settable(L, -3);
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003963
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003964 /* creates an array of headers. hlua_http_get_headers() crates and push
3965 * the array on the top of the stack.
3966 */
3967 lua_pushstring(L, "headers");
3968 htxn.s = s;
3969 htxn.p = px;
3970 htxn.dir = SMP_OPT_DIR_REQ;
3971 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3972 return 0;
3973 lua_settable(L, -3);
3974
3975 path = http_get_path(htx_sl_req_uri(sl));
3976 if (path.ptr) {
3977 char *p, *q, *end;
3978
3979 p = path.ptr;
3980 end = path.ptr + path.len;
3981 q = p;
3982 while (q < end && *q != '?')
3983 q++;
3984
3985 /* Stores the request path. */
3986 lua_pushstring(L, "path");
3987 lua_pushlstring(L, p, q - p);
3988 lua_settable(L, -3);
3989
3990 /* Stores the query string. */
3991 lua_pushstring(L, "qs");
3992 if (*q == '?')
3993 q++;
3994 lua_pushlstring(L, q, end - q);
3995 lua_settable(L, -3);
3996 }
3997
Christopher Fauleta3f15502019-05-13 15:27:23 +02003998 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003999 struct htx_blk *blk = htx_get_blk(htx, pos);
4000 enum htx_blk_type type = htx_get_blk_type(blk);
4001
Christopher Faulet54b5e212019-06-04 10:08:28 +02004002 if (type == HTX_BLK_EOM || type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004003 break;
4004 if (type == HTX_BLK_DATA)
4005 len += htx_get_blksz(blk);
4006 }
4007 if (htx->extra != ULLONG_MAX)
4008 len += htx->extra;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004009
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004010 /* Stores the request path. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004011 lua_pushstring(L, "length");
4012 lua_pushinteger(L, len);
4013 lua_settable(L, -3);
4014 }
4015 else {
4016 /* Legacy HTTP version */
4017 struct http_txn *txn = s->txn;
4018 const char *path;
4019 const char *end;
4020 const char *p;
4021
4022 /* Stores the request method. */
4023 lua_pushstring(L, "method");
4024 lua_pushlstring(L, ci_head(txn->req.chn), txn->req.sl.rq.m_l);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004025 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004026
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004027 /* Stores the http version. */
4028 lua_pushstring(L, "version");
4029 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 +01004030 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004031
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004032 /* creates an array of headers. hlua_http_get_headers() crates and push
4033 * the array on the top of the stack.
4034 */
4035 lua_pushstring(L, "headers");
4036 htxn.s = s;
4037 htxn.p = px;
4038 htxn.dir = SMP_OPT_DIR_REQ;
4039 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
4040 return 0;
4041 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004042
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004043 /* Get path and qs */
4044 path = http_txn_get_path(txn);
4045 if (path) {
4046 end = ci_head(txn->req.chn) + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
4047 p = path;
4048 while (p < end && *p != '?')
4049 p++;
4050
4051 /* Stores the request path. */
4052 lua_pushstring(L, "path");
4053 lua_pushlstring(L, path, p - path);
4054 lua_settable(L, -3);
4055
4056 /* Stores the query string. */
4057 lua_pushstring(L, "qs");
4058 if (*p == '?')
4059 p++;
4060 lua_pushlstring(L, p, end - p);
4061 lua_settable(L, -3);
4062 }
4063
4064 /* Stores the request path. */
4065 lua_pushstring(L, "length");
4066 lua_pushinteger(L, txn->req.body_len);
4067 lua_settable(L, -3);
4068 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004069
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004070 /* Create an empty array of HTTP request headers. */
4071 lua_pushstring(L, "response");
4072 lua_newtable(L);
4073 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004074
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004075 /* Pop a class stream metatable and affect it to the table. */
4076 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4077 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004078
4079 return 1;
4080}
4081
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004082__LJMP static int hlua_applet_http_set_var(lua_State *L)
4083{
4084 struct hlua_appctx *appctx;
4085 struct stream *s;
4086 const char *name;
4087 size_t len;
4088 struct sample smp;
4089
4090 MAY_LJMP(check_args(L, 3, "set_var"));
4091
4092 /* It is useles to retrieve the stream, but this function
4093 * runs only in a stream context.
4094 */
4095 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4096 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4097 s = appctx->htxn.s;
4098
4099 /* Converts the third argument in a sample. */
4100 hlua_lua2smp(L, 3, &smp);
4101
4102 /* Store the sample in a variable. */
4103 smp_set_owner(&smp, s->be, s->sess, s, 0);
4104 vars_set_by_name(name, len, &smp);
4105 return 0;
4106}
4107
4108__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4109{
4110 struct hlua_appctx *appctx;
4111 struct stream *s;
4112 const char *name;
4113 size_t len;
4114 struct sample smp;
4115
4116 MAY_LJMP(check_args(L, 2, "unset_var"));
4117
4118 /* It is useles to retrieve the stream, but this function
4119 * runs only in a stream context.
4120 */
4121 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4122 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4123 s = appctx->htxn.s;
4124
4125 /* Unset the variable. */
4126 smp_set_owner(&smp, s->be, s->sess, s, 0);
4127 vars_unset_by_name(name, len, &smp);
4128 return 0;
4129}
4130
4131__LJMP static int hlua_applet_http_get_var(lua_State *L)
4132{
4133 struct hlua_appctx *appctx;
4134 struct stream *s;
4135 const char *name;
4136 size_t len;
4137 struct sample smp;
4138
4139 MAY_LJMP(check_args(L, 2, "get_var"));
4140
4141 /* It is useles to retrieve the stream, but this function
4142 * runs only in a stream context.
4143 */
4144 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4145 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4146 s = appctx->htxn.s;
4147
4148 smp_set_owner(&smp, s->be, s->sess, s, 0);
4149 if (!vars_get_by_name(name, len, &smp)) {
4150 lua_pushnil(L);
4151 return 1;
4152 }
4153
4154 return hlua_smp2lua(L, &smp);
4155}
4156
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004157__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4158{
4159 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4160 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004161 struct hlua *hlua;
4162
4163 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004164 if (!s->hlua)
4165 return 0;
4166 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004167
4168 MAY_LJMP(check_args(L, 2, "set_priv"));
4169
4170 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004171 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004172
4173 /* Get and store new value. */
4174 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4175 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4176
4177 return 0;
4178}
4179
4180__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4181{
4182 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4183 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004184 struct hlua *hlua;
4185
4186 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004187 if (!s->hlua) {
4188 lua_pushnil(L);
4189 return 1;
4190 }
4191 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004192
4193 /* Push configuration index in the stack. */
4194 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4195
4196 return 1;
4197}
4198
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004199/* If expected data not yet available, it returns a yield. This function
4200 * consumes the data in the buffer. It returns a string containing the
4201 * data. This string can be empty.
4202 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004203__LJMP static int hlua_applet_htx_getline_yield(lua_State *L, int status, lua_KContext ctx)
4204{
4205 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4206 struct stream_interface *si = appctx->appctx->owner;
4207 struct channel *req = si_oc(si);
4208 struct htx *htx;
4209 struct htx_blk *blk;
4210 size_t count;
4211 int stop = 0;
4212
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004213 htx = htx_from_buf(&req->buf);
4214 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004215 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004216
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004217 while (count && !stop && blk) {
4218 enum htx_blk_type type = htx_get_blk_type(blk);
4219 uint32_t sz = htx_get_blksz(blk);
4220 struct ist v;
4221 uint32_t vlen;
4222 char *nl;
4223
Christopher Faulete461e342018-12-18 16:43:35 +01004224 if (type == HTX_BLK_EOM) {
4225 stop = 1;
4226 break;
4227 }
4228
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004229 vlen = sz;
4230 if (vlen > count) {
4231 if (type != HTX_BLK_DATA)
4232 break;
4233 vlen = count;
4234 }
4235
4236 switch (type) {
4237 case HTX_BLK_UNUSED:
4238 break;
4239
4240 case HTX_BLK_DATA:
4241 v = htx_get_blk_value(htx, blk);
4242 v.len = vlen;
4243 nl = istchr(v, '\n');
4244 if (nl != NULL) {
4245 stop = 1;
4246 vlen = nl - v.ptr + 1;
4247 }
4248 luaL_addlstring(&appctx->b, v.ptr, vlen);
4249 break;
4250
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004251 case HTX_BLK_TLR:
4252 case HTX_BLK_EOM:
4253 stop = 1;
4254 break;
4255
4256 default:
4257 break;
4258 }
4259
4260 co_set_data(req, co_data(req) - vlen);
4261 count -= vlen;
4262 if (sz == vlen)
4263 blk = htx_remove_blk(htx, blk);
4264 else {
4265 htx_cut_data_blk(htx, blk, vlen);
4266 break;
4267 }
4268 }
4269
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004270 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004271 if (!stop) {
4272 si_cant_get(si);
4273 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_getline_yield, TICK_ETERNITY, 0));
4274 }
4275
4276 /* return the result. */
4277 luaL_pushresult(&appctx->b);
4278 return 1;
4279}
4280
4281
4282/* If expected data not yet available, it returns a yield. This function
4283 * consumes the data in the buffer. It returns a string containing the
4284 * data. This string can be empty.
4285 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004286__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004287{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004288 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4289 struct stream_interface *si = appctx->appctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004290 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004291 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004292 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004293 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004294 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004295
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004296 /* Check for the end of the data. */
4297 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4298 luaL_pushresult(&appctx->b);
4299 return 1;
4300 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004301
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004302 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004303 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004304
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004305 /* Data not yet available. return yield. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004306 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004307 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004308 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004309 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004310
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004311 /* End of data: commit the total strings and return. */
4312 if (ret < 0) {
4313 luaL_pushresult(&appctx->b);
4314 return 1;
4315 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004316
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004317 /* Ensure that the block 2 length is usable. */
4318 if (ret == 1)
4319 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004320
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004321 /* Copy the fisrt block caping to the length required. */
4322 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4323 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4324 luaL_addlstring(&appctx->b, blk1, len1);
4325 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004326
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004327 /* Copy the second block. */
4328 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4329 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4330 luaL_addlstring(&appctx->b, blk2, len2);
4331 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004332
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004333 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004334 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004335 luaL_pushresult(&appctx->b);
4336 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004337}
4338
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004339/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004340__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004341{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004342 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004343
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004344 /* Initialise the string catenation. */
4345 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004346
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004347 if (IS_HTX_STRM(si_strm(appctx->appctx->owner)))
4348 return MAY_LJMP(hlua_applet_htx_getline_yield(L, 0, 0));
4349 else
4350 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004351}
4352
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004353/* If expected data not yet available, it returns a yield. This function
4354 * consumes the data in the buffer. It returns a string containing the
4355 * data. This string can be empty.
4356 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004357__LJMP static int hlua_applet_htx_recv_yield(lua_State *L, int status, lua_KContext ctx)
4358{
4359 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4360 struct stream_interface *si = appctx->appctx->owner;
4361 struct channel *req = si_oc(si);
4362 struct htx *htx;
4363 struct htx_blk *blk;
4364 size_t count;
4365 int len;
4366
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004367 htx = htx_from_buf(&req->buf);
4368 len = MAY_LJMP(luaL_checkinteger(L, 2));
4369 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02004370 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004371 while (count && len && blk) {
4372 enum htx_blk_type type = htx_get_blk_type(blk);
4373 uint32_t sz = htx_get_blksz(blk);
4374 struct ist v;
4375 uint32_t vlen;
4376
Christopher Faulete461e342018-12-18 16:43:35 +01004377 if (type == HTX_BLK_EOM) {
4378 len = 0;
4379 break;
4380 }
4381
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004382 vlen = sz;
4383 if (len > 0 && vlen > len)
4384 vlen = len;
4385 if (vlen > count) {
4386 if (type != HTX_BLK_DATA)
4387 break;
4388 vlen = count;
4389 }
4390
4391 switch (type) {
4392 case HTX_BLK_UNUSED:
4393 break;
4394
4395 case HTX_BLK_DATA:
4396 v = htx_get_blk_value(htx, blk);
4397 luaL_addlstring(&appctx->b, v.ptr, vlen);
4398 break;
4399
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004400 case HTX_BLK_TLR:
4401 case HTX_BLK_EOM:
4402 len = 0;
4403 break;
4404
4405 default:
4406 break;
4407 }
4408
4409 co_set_data(req, co_data(req) - vlen);
4410 count -= vlen;
4411 if (len > 0)
4412 len -= vlen;
4413 if (sz == vlen)
4414 blk = htx_remove_blk(htx, blk);
4415 else {
4416 htx_cut_data_blk(htx, blk, vlen);
4417 break;
4418 }
4419 }
4420
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004421 htx_to_buf(htx, &req->buf);
4422
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004423 /* If we are no other data available, yield waiting for new data. */
4424 if (len) {
4425 if (len > 0) {
4426 lua_pushinteger(L, len);
4427 lua_replace(L, 2);
4428 }
4429 si_cant_get(si);
4430 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_recv_yield, TICK_ETERNITY, 0));
4431 }
4432
4433 /* return the result. */
4434 luaL_pushresult(&appctx->b);
4435 return 1;
4436}
4437
4438/* If expected data not yet available, it returns a yield. This function
4439 * consumes the data in the buffer. It returns a string containing the
4440 * data. This string can be empty.
4441 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004442__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004443{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004444 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4445 struct stream_interface *si = appctx->appctx->owner;
4446 int len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004447 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004448 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004449 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004450 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004451 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004452
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004453 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004454 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004455
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004456 /* Data not yet available. return yield. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004457 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004458 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004459 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004460 }
4461
4462 /* End of data: commit the total strings and return. */
4463 if (ret < 0) {
4464 luaL_pushresult(&appctx->b);
4465 return 1;
4466 }
4467
4468 /* Ensure that the block 2 length is usable. */
4469 if (ret == 1)
4470 len2 = 0;
4471
4472 /* Copy the fisrt block caping to the length required. */
4473 if (len1 > len)
4474 len1 = len;
4475 luaL_addlstring(&appctx->b, blk1, len1);
4476 len -= len1;
4477
4478 /* Copy the second block. */
4479 if (len2 > len)
4480 len2 = len;
4481 luaL_addlstring(&appctx->b, blk2, len2);
4482 len -= len2;
4483
4484 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004485 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004486 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4487 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4488
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004489 /* If we are no other data available, yield waiting for new data. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004490 if (len > 0) {
4491 lua_pushinteger(L, len);
4492 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004493 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004494 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004495 }
4496
4497 /* return the result. */
4498 luaL_pushresult(&appctx->b);
4499 return 1;
4500}
4501
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004502/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004503__LJMP static int hlua_applet_http_recv(lua_State *L)
4504{
4505 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4506 int len = -1;
4507
4508 /* Check arguments. */
4509 if (lua_gettop(L) > 2)
4510 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4511 if (lua_gettop(L) >= 2) {
4512 len = MAY_LJMP(luaL_checkinteger(L, 2));
4513 lua_pop(L, 1);
4514 }
4515
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004516 if (IS_HTX_STRM(si_strm(appctx->appctx->owner))) {
4517 /* HTX version */
4518 lua_pushinteger(L, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004519
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004520 /* Initialise the string catenation. */
4521 luaL_buffinit(L, &appctx->b);
4522
4523 return MAY_LJMP(hlua_applet_htx_recv_yield(L, 0, 0));
4524 }
4525 else {
4526 /* Legacy HTTP version */
4527 /* Check the required length */
4528 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4529 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4530 lua_pushinteger(L, len);
4531
4532 /* Initialise the string catenation. */
4533 luaL_buffinit(L, &appctx->b);
4534
4535 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4536 }
4537}
4538
4539/* Append data in the output side of the buffer. This data is immediately
4540 * sent. The function returns the amount of data written. If the buffer
4541 * cannot contain the data, the function yields. The function returns -1
4542 * if the channel is closed.
4543 */
4544__LJMP static int hlua_applet_htx_send_yield(lua_State *L, int status, lua_KContext ctx)
4545{
4546 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4547 struct stream_interface *si = appctx->appctx->owner;
4548 struct channel *res = si_ic(si);
4549 struct htx *htx = htx_from_buf(&res->buf);
4550 const char *data;
4551 size_t len;
4552 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4553 int max;
4554
Christopher Faulet4e963012019-07-03 11:39:30 +02004555 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004556 if (!max)
4557 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004558
4559 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
4560
4561 /* Get the max amount of data which can write as input in the channel. */
4562 if (max > (len - l))
4563 max = len - l;
4564
4565 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02004566 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004567 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004568
4569 /* update counters. */
4570 l += max;
4571 lua_pop(L, 1);
4572 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004573
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004574 /* If some data is not send, declares the situation to the
4575 * applet, and returns a yield.
4576 */
4577 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004578 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004579 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004580 si_rx_room_blk(si);
4581 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_send_yield, TICK_ETERNITY, 0));
4582 }
4583
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004584 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004585 return 1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004586}
4587
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004588/* Append data in the output side of the buffer. This data is immediately
4589 * sent. The function returns the amount of data written. If the buffer
4590 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004591 * if the channel is closed.
4592 */
4593__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4594{
4595 size_t len;
4596 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4597 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4598 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4599 struct stream_interface *si = appctx->appctx->owner;
4600 struct channel *chn = si_ic(si);
4601 int max;
4602
4603 /* Get the max amount of data which can write as input in the channel. */
4604 max = channel_recv_max(chn);
4605 if (max > (len - l))
4606 max = len - l;
4607
4608 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004609 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004610
4611 /* update counters. */
4612 l += max;
4613 lua_pop(L, 1);
4614 lua_pushinteger(L, l);
4615
4616 /* If some data is not send, declares the situation to the
4617 * applet, and returns a yield.
4618 */
4619 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004620 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004621 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004622 }
4623
4624 return 1;
4625}
4626
4627/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4628 * yield the LUA process, and resume it without checking the
4629 * input arguments.
4630 */
4631__LJMP static int hlua_applet_http_send(lua_State *L)
4632{
4633 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004634
4635 /* We want to send some data. Headers must be sent. */
4636 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4637 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4638 WILL_LJMP(lua_error(L));
4639 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004640
4641 if (IS_HTX_STRM(si_strm(appctx->appctx->owner))) {
4642 /* HTX version */
4643 /* This interger is used for followinf the amount of data sent. */
4644 lua_pushinteger(L, 0);
4645
4646 return MAY_LJMP(hlua_applet_htx_send_yield(L, 0, 0));
4647 }
4648 else {
4649 /* Legacy HTTP version */
4650 size_t len;
4651 char hex[10];
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004652
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004653 MAY_LJMP(luaL_checklstring(L, 2, &len));
4654
4655 /* If transfer encoding chunked is selected, we surround the data
4656 * by chunk data.
4657 */
4658 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4659 snprintf(hex, 9, "%x", (unsigned int)len);
4660 lua_pushfstring(L, "%s\r\n", hex);
4661 lua_insert(L, 2); /* swap the last 2 entries. */
4662 lua_pushstring(L, "\r\n");
4663 lua_concat(L, 3);
4664 }
4665
4666 /* This interger is used for followinf the amount of data sent. */
4667 lua_pushinteger(L, 0);
4668
4669 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4670 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004671}
4672
4673__LJMP static int hlua_applet_http_addheader(lua_State *L)
4674{
4675 const char *name;
4676 int ret;
4677
4678 MAY_LJMP(hlua_checkapplet_http(L, 1));
4679 name = MAY_LJMP(luaL_checkstring(L, 2));
4680 MAY_LJMP(luaL_checkstring(L, 3));
4681
4682 /* Push in the stack the "response" entry. */
4683 ret = lua_getfield(L, 1, "response");
4684 if (ret != LUA_TTABLE) {
4685 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4686 "is expected as an array. %s found", lua_typename(L, ret));
4687 WILL_LJMP(lua_error(L));
4688 }
4689
4690 /* check if the header is already registered if it is not
4691 * the case, register it.
4692 */
4693 ret = lua_getfield(L, -1, name);
4694 if (ret == LUA_TNIL) {
4695
4696 /* Entry not found. */
4697 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4698
4699 /* Insert the new header name in the array in the top of the stack.
4700 * It left the new array in the top of the stack.
4701 */
4702 lua_newtable(L);
4703 lua_pushvalue(L, 2);
4704 lua_pushvalue(L, -2);
4705 lua_settable(L, -4);
4706
4707 } else if (ret != LUA_TTABLE) {
4708
4709 /* corruption error. */
4710 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4711 "is expected as an array. %s found", name, lua_typename(L, ret));
4712 WILL_LJMP(lua_error(L));
4713 }
4714
4715 /* Now the top od thestack is an array of values. We push
4716 * the header value as new entry.
4717 */
4718 lua_pushvalue(L, 3);
4719 ret = lua_rawlen(L, -2);
4720 lua_rawseti(L, -2, ret + 1);
4721 lua_pushboolean(L, 1);
4722 return 1;
4723}
4724
4725__LJMP static int hlua_applet_http_status(lua_State *L)
4726{
4727 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4728 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004729 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004730
4731 if (status < 100 || status > 599) {
4732 lua_pushboolean(L, 0);
4733 return 1;
4734 }
4735
4736 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004737 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004738 lua_pushboolean(L, 1);
4739 return 1;
4740}
4741
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004742
4743__LJMP static int hlua_applet_htx_send_response(lua_State *L)
4744{
4745 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4746 struct stream_interface *si = appctx->appctx->owner;
4747 struct channel *res = si_ic(si);
4748 struct htx *htx;
4749 struct htx_sl *sl;
4750 struct h1m h1m;
4751 const char *status, *reason;
4752 const char *name, *value;
4753 size_t nlen, vlen;
4754 unsigned int flags;
4755
4756 /* Send the message at once. */
4757 htx = htx_from_buf(&res->buf);
4758 h1m_init_res(&h1m);
4759
4760 /* Use the same http version than the request. */
4761 status = ultoa_r(appctx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
4762 reason = appctx->appctx->ctx.hlua_apphttp.reason;
4763 if (reason == NULL)
4764 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
4765 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
4766 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
4767 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
4768 }
4769 else {
4770 flags = HTX_SL_F_IS_RESP;
4771 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
4772 }
4773 if (!sl) {
4774 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
4775 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4776 WILL_LJMP(lua_error(L));
4777 }
4778 sl->info.res.status = appctx->appctx->ctx.hlua_apphttp.status;
4779
4780 /* Get the array associated to the field "response" in the object AppletHTTP. */
4781 lua_pushvalue(L, 0);
4782 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4783 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4784 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4785 WILL_LJMP(lua_error(L));
4786 }
4787
4788 /* Browse the list of headers. */
4789 lua_pushnil(L);
4790 while(lua_next(L, -2) != 0) {
4791 /* We expect a string as -2. */
4792 if (lua_type(L, -2) != LUA_TSTRING) {
4793 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4794 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4795 lua_typename(L, lua_type(L, -2)));
4796 WILL_LJMP(lua_error(L));
4797 }
4798 name = lua_tolstring(L, -2, &nlen);
4799
4800 /* We expect an array as -1. */
4801 if (lua_type(L, -1) != LUA_TTABLE) {
4802 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4803 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4804 name,
4805 lua_typename(L, lua_type(L, -1)));
4806 WILL_LJMP(lua_error(L));
4807 }
4808
4809 /* Browse the table who is on the top of the stack. */
4810 lua_pushnil(L);
4811 while(lua_next(L, -2) != 0) {
4812 int id;
4813
4814 /* We expect a number as -2. */
4815 if (lua_type(L, -2) != LUA_TNUMBER) {
4816 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4817 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4818 name,
4819 lua_typename(L, lua_type(L, -2)));
4820 WILL_LJMP(lua_error(L));
4821 }
4822 id = lua_tointeger(L, -2);
4823
4824 /* We expect a string as -2. */
4825 if (lua_type(L, -1) != LUA_TSTRING) {
4826 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4827 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4828 name, id,
4829 lua_typename(L, lua_type(L, -1)));
4830 WILL_LJMP(lua_error(L));
4831 }
4832 value = lua_tolstring(L, -1, &vlen);
4833
4834 /* Simple Protocol checks. */
4835 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
4836 h1_parse_xfer_enc_header(&h1m, ist2(name, nlen));
4837 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
4838 struct ist v = ist2(value, vlen);
4839 int ret;
4840
4841 ret = h1_parse_cont_len_header(&h1m, &v);
4842 if (ret < 0) {
4843 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
4844 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4845 name);
4846 WILL_LJMP(lua_error(L));
4847 }
4848 else if (ret == 0)
4849 goto next; /* Skip it */
4850 }
4851
4852 /* Add a new header */
4853 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
4854 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
4855 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4856 name);
4857 WILL_LJMP(lua_error(L));
4858 }
4859 next:
4860 /* Remove the array from the stack, and get next element with a remaining string. */
4861 lua_pop(L, 1);
4862 }
4863
4864 /* Remove the array from the stack, and get next element with a remaining string. */
4865 lua_pop(L, 1);
4866 }
4867
4868 if (h1m.flags & H1_MF_CHNK)
4869 h1m.flags &= ~H1_MF_CLEN;
4870 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
4871 h1m.flags |= H1_MF_XFER_LEN;
4872
4873 /* Uset HTX start-line flags */
4874 if (h1m.flags & H1_MF_XFER_ENC)
4875 flags |= HTX_SL_F_XFER_ENC;
4876 if (h1m.flags & H1_MF_XFER_LEN) {
4877 flags |= HTX_SL_F_XFER_LEN;
4878 if (h1m.flags & H1_MF_CHNK)
4879 flags |= HTX_SL_F_CHNK;
4880 else if (h1m.flags & H1_MF_CLEN)
4881 flags |= HTX_SL_F_CLEN;
4882 if (h1m.body_len == 0)
4883 flags |= HTX_SL_F_BODYLESS;
4884 }
4885 sl->flags |= flags;
4886
4887 /* If we dont have a content-length set, and the HTTP version is 1.1
4888 * and the status code implies the presence of a message body, we must
4889 * announce a transfer encoding chunked. This is required by haproxy
4890 * for the keepalive compliance. If the applet annouces a transfer-encoding
4891 * chunked itslef, don't do anything.
4892 */
4893 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
4894 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4895 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4896 appctx->appctx->ctx.hlua_apphttp.status != 304) {
4897 /* Add a new header */
4898 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
4899 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
4900 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
4901 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4902 WILL_LJMP(lua_error(L));
4903 }
4904 }
4905
4906 /* Finalize headers. */
4907 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
4908 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
4909 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4910 WILL_LJMP(lua_error(L));
4911 }
4912
4913 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
4914 b_reset(&res->buf);
4915 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4916 WILL_LJMP(lua_error(L));
4917 }
4918
4919 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004920 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004921
4922 /* Headers sent, set the flag. */
4923 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4924 return 0;
4925
4926}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004927/* We will build the status line and the headers of the HTTP response.
4928 * We will try send at once if its not possible, we give back the hand
4929 * waiting for more room.
4930 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004931__LJMP static int hlua_applet_htx_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4932{
4933 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4934 struct stream_interface *si = appctx->appctx->owner;
4935 struct channel *res = si_ic(si);
4936
4937 if (co_data(res)) {
4938 si_rx_room_blk(si);
4939 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_start_response_yield, TICK_ETERNITY, 0));
4940 }
4941 return MAY_LJMP(hlua_applet_htx_send_response(L));
4942}
4943
4944
4945__LJMP static int hlua_applet_htx_start_response(lua_State *L)
4946{
4947 return MAY_LJMP(hlua_applet_htx_start_response_yield(L, 0, 0));
4948}
4949
4950/* We will build the status line and the headers of the HTTP response.
4951 * We will try send at once if its not possible, we give back the hand
4952 * waiting for more room.
4953 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004954__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4955{
4956 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4957 struct stream_interface *si = appctx->appctx->owner;
4958 struct channel *chn = si_ic(si);
4959 int ret;
4960 size_t len;
4961 const char *msg;
4962
4963 /* Get the message as the first argument on the stack. */
4964 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4965
4966 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004967 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004968
4969 /* if ret == -2 or -3 the channel closed or the message si too
4970 * big for the buffers.
4971 */
4972 if (ret == -2 || ret == -3) {
4973 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4974 WILL_LJMP(lua_error(L));
4975 }
4976
4977 /* If ret is -1, we dont have room in the buffer, so we yield. */
4978 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004979 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004980 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004981 }
4982
4983 /* Headers sent, set the flag. */
4984 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4985 return 0;
4986}
4987
4988__LJMP static int hlua_applet_http_start_response(lua_State *L)
4989{
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004990 struct buffer *tmp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004991 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004992 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02004993 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004994 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02004995 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004996 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004997 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004998 int hdr_chunked = 0;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004999 const char *reason;
5000
5001 if (IS_HTX_STRM(si_strm(appctx->appctx->owner)))
5002 return MAY_LJMP(hlua_applet_htx_start_response(L));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005003
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005004 reason = appctx->appctx->ctx.hlua_apphttp.reason;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005005 if (reason == NULL)
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02005006 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005007
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005008 tmp = get_trash_chunk();
5009
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005010 /* Use the same http version than the request. */
5011 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01005012 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005013 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005014 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005015
5016 /* Get the array associated to the field "response" in the object AppletHTTP. */
5017 lua_pushvalue(L, 0);
5018 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5019 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
5020 appctx->appctx->rule->arg.hlua_rule->fcn.name);
5021 WILL_LJMP(lua_error(L));
5022 }
5023
5024 /* Browse the list of headers. */
5025 lua_pushnil(L);
5026 while(lua_next(L, -2) != 0) {
5027
5028 /* We expect a string as -2. */
5029 if (lua_type(L, -2) != LUA_TSTRING) {
5030 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
5031 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5032 lua_typename(L, lua_type(L, -2)));
5033 WILL_LJMP(lua_error(L));
5034 }
Willy Tarreaua3294632017-08-23 11:24:47 +02005035 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005036
5037 /* We expect an array as -1. */
5038 if (lua_type(L, -1) != LUA_TTABLE) {
5039 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
5040 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5041 name,
5042 lua_typename(L, lua_type(L, -1)));
5043 WILL_LJMP(lua_error(L));
5044 }
5045
5046 /* Browse the table who is on the top of the stack. */
5047 lua_pushnil(L);
5048 while(lua_next(L, -2) != 0) {
5049
5050 /* We expect a number as -2. */
5051 if (lua_type(L, -2) != LUA_TNUMBER) {
5052 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
5053 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5054 name,
5055 lua_typename(L, lua_type(L, -2)));
5056 WILL_LJMP(lua_error(L));
5057 }
5058 id = lua_tointeger(L, -2);
5059
5060 /* We expect a string as -2. */
5061 if (lua_type(L, -1) != LUA_TSTRING) {
5062 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
5063 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5064 name, id,
5065 lua_typename(L, lua_type(L, -1)));
5066 WILL_LJMP(lua_error(L));
5067 }
Willy Tarreaua3294632017-08-23 11:24:47 +02005068 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005069
5070 /* Catenate a new header. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005071 if (tmp->data + name_len + 2 + value_len + 2 < tmp->size) {
5072 memcpy(tmp->area + tmp->data, name, name_len);
5073 tmp->data += name_len;
5074 tmp->area[tmp->data++] = ':';
5075 tmp->area[tmp->data++] = ' ';
Willy Tarreaua3294632017-08-23 11:24:47 +02005076
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005077 memcpy(tmp->area + tmp->data, value,
5078 value_len);
5079 tmp->data += value_len;
5080 tmp->area[tmp->data++] = '\r';
5081 tmp->area[tmp->data++] = '\n';
Willy Tarreaua3294632017-08-23 11:24:47 +02005082 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005083
5084 /* Protocol checks. */
5085
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005086 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005087 * is done without control. If it contains a bad value,
5088 * the content-length remains negative so that we can
5089 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005090 */
Willy Tarreaua3294632017-08-23 11:24:47 +02005091 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005092 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005093
5094 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02005095 if (name_len == 17 && value_len == 7 &&
5096 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005097 strcasecmp("chunked", value) == 0)
5098 hdr_chunked = 1;
5099
5100 /* Remove the array from the stack, and get next element with a remaining string. */
5101 lua_pop(L, 1);
5102 }
5103
5104 /* Remove the array from the stack, and get next element with a remaining string. */
5105 lua_pop(L, 1);
5106 }
5107
Willy Tarreau06c75fe2017-08-23 09:10:38 +02005108 /* If we dont have a content-length set, and the HTTP version is 1.1
5109 * and the status code implies the presence of a message body, we must
5110 * announce a transfer encoding chunked. This is required by haproxy
5111 * for the keepalive compliance. If the applet annouces a transfer-encoding
5112 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005113 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005114 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02005115 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
5116 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
5117 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
5118 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005119 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
5120 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
5121 }
5122
5123 /* Finalize headers. */
5124 chunk_appendf(tmp, "\r\n");
5125
5126 /* Remove the last entry and the array of headers */
5127 lua_pop(L, 2);
5128
5129 /* Push the headers block. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005130 lua_pushlstring(L, tmp->area, tmp->data);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005131
5132 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
5133}
5134
5135/*
5136 *
5137 *
5138 * Class HTTP
5139 *
5140 *
5141 */
5142
5143/* Returns a struct hlua_txn if the stack entry "ud" is
5144 * a class stream, otherwise it throws an error.
5145 */
5146__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
5147{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005148 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005149}
5150
5151/* This function creates and push in the stack a HTTP object
5152 * according with a current TXN.
5153 */
5154static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5155{
5156 struct hlua_txn *htxn;
5157
5158 /* Check stack size. */
5159 if (!lua_checkstack(L, 3))
5160 return 0;
5161
5162 /* Create the object: obj[0] = userdata.
5163 * Note that the base of the Converters object is the
5164 * same than the TXN object.
5165 */
5166 lua_newtable(L);
5167 htxn = lua_newuserdata(L, sizeof(*htxn));
5168 lua_rawseti(L, -2, 0);
5169
5170 htxn->s = txn->s;
5171 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02005172 htxn->dir = txn->dir;
5173 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005174
5175 /* Pop a class stream metatable and affect it to the table. */
5176 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5177 lua_setmetatable(L, -2);
5178
5179 return 1;
5180}
5181
5182/* This function creates ans returns an array of HTTP headers.
5183 * This function does not fails. It is used as wrapper with the
5184 * 2 following functions.
5185 */
5186__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5187{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005188 /* Create the table. */
5189 lua_newtable(L);
5190
5191 if (!htxn->s->txn)
5192 return 1;
5193
Christopher Faulet724a12c2018-12-13 22:12:15 +01005194 if (IS_HTX_STRM(htxn->s)) {
5195 /* HTX version */
5196 struct htx *htx = htxbuf(&msg->chn->buf);
5197 int32_t pos;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005198
Christopher Fauleta3f15502019-05-13 15:27:23 +02005199 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
Christopher Faulet724a12c2018-12-13 22:12:15 +01005200 struct htx_blk *blk = htx_get_blk(htx, pos);
5201 enum htx_blk_type type = htx_get_blk_type(blk);
5202 struct ist n, v;
5203 int len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005204
Christopher Faulet724a12c2018-12-13 22:12:15 +01005205 if (type == HTX_BLK_HDR) {
5206 n = htx_get_blk_name(htx,blk);
5207 v = htx_get_blk_value(htx, blk);
5208 }
5209 else if (type == HTX_BLK_EOH)
5210 break;
5211 else
5212 continue;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005213
Christopher Faulet724a12c2018-12-13 22:12:15 +01005214 /* Check for existing entry:
5215 * assume that the table is on the top of the stack, and
5216 * push the key in the stack, the function lua_gettable()
5217 * perform the lookup.
5218 */
5219 lua_pushlstring(L, n.ptr, n.len);
5220 lua_gettable(L, -2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005221
Christopher Faulet724a12c2018-12-13 22:12:15 +01005222 switch (lua_type(L, -1)) {
5223 case LUA_TNIL:
5224 /* Table not found, create it. */
5225 lua_pop(L, 1); /* remove the nil value. */
5226 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5227 lua_newtable(L); /* create and push empty table. */
5228 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5229 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5230 lua_rawset(L, -3); /* index new table with header name (pop the values). */
5231 break;
5232
5233 case LUA_TTABLE:
5234 /* Entry found: push the value in the table. */
5235 len = lua_rawlen(L, -1);
5236 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5237 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5238 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5239 break;
5240
5241 default:
5242 /* Other cases are errors. */
5243 hlua_pusherror(L, "internal error during the parsing of headers.");
5244 WILL_LJMP(lua_error(L));
5245 }
5246 }
5247 }
5248 else {
5249 /* Legacy HTTP version */
5250 const char *cur_ptr, *cur_next, *p;
5251 int old_idx, cur_idx;
5252 struct hdr_idx_elem *cur_hdr;
5253 const char *hn, *hv;
5254 int hnl, hvl;
5255 const char *in;
5256 char *out;
5257 int len;
5258
5259 /* Build array of headers. */
5260 old_idx = 0;
5261 cur_next = ci_head(msg->chn) + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
5262
5263 while (1) {
5264 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
5265 if (!cur_idx)
5266 break;
5267 old_idx = cur_idx;
5268
5269 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
5270 cur_ptr = cur_next;
5271 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
5272
5273 /* Now we have one full header at cur_ptr of len cur_hdr->len,
5274 * and the next header starts at cur_next. We'll check
5275 * this header in the list as well as against the default
5276 * rule.
5277 */
5278
5279 /* look for ': *'. */
5280 hn = cur_ptr;
5281 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
5282 if (p >= cur_ptr+cur_hdr->len)
5283 continue;
5284 hnl = p - hn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005285 p++;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005286 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
5287 p++;
5288 if (p >= cur_ptr+cur_hdr->len)
5289 continue;
5290 hv = p;
5291 hvl = cur_ptr+cur_hdr->len-p;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005292
Christopher Faulet724a12c2018-12-13 22:12:15 +01005293 /* Lowercase the key. Don't check the size of trash, it have
5294 * the size of one buffer and the input data contains in one
5295 * buffer.
5296 */
5297 out = trash.area;
5298 for (in=hn; in<hn+hnl; in++, out++)
5299 *out = tolower(*in);
5300 *out = '\0';
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005301
Christopher Faulet724a12c2018-12-13 22:12:15 +01005302 /* Check for existing entry:
5303 * assume that the table is on the top of the stack, and
5304 * push the key in the stack, the function lua_gettable()
5305 * perform the lookup.
5306 */
5307 lua_pushlstring(L, trash.area, hnl);
5308 lua_gettable(L, -2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005309
Christopher Faulet724a12c2018-12-13 22:12:15 +01005310 switch (lua_type(L, -1)) {
5311 case LUA_TNIL:
5312 /* Table not found, create it. */
5313 lua_pop(L, 1); /* remove the nil value. */
5314 lua_pushlstring(L, trash.area, hnl); /* push the header name as key. */
5315 lua_newtable(L); /* create and push empty table. */
5316 lua_pushlstring(L, hv, hvl); /* push header value. */
5317 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5318 lua_rawset(L, -3); /* index new table with header name (pop the values). */
5319 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005320
Christopher Faulet724a12c2018-12-13 22:12:15 +01005321 case LUA_TTABLE:
5322 /* Entry found: push the value in the table. */
5323 len = lua_rawlen(L, -1);
5324 lua_pushlstring(L, hv, hvl); /* push header value. */
5325 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5326 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5327 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005328
Christopher Faulet724a12c2018-12-13 22:12:15 +01005329 default:
5330 /* Other cases are errors. */
5331 hlua_pusherror(L, "internal error during the parsing of headers.");
5332 WILL_LJMP(lua_error(L));
5333 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005334 }
5335 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005336 return 1;
5337}
5338
5339__LJMP static int hlua_http_req_get_headers(lua_State *L)
5340{
5341 struct hlua_txn *htxn;
5342
5343 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5344 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5345
Christopher Faulet2351ca22019-07-26 16:31:34 +02005346 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005347 WILL_LJMP(lua_error(L));
5348
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005349 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
5350}
5351
5352__LJMP static int hlua_http_res_get_headers(lua_State *L)
5353{
5354 struct hlua_txn *htxn;
5355
5356 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5357 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5358
Christopher Faulet2351ca22019-07-26 16:31:34 +02005359 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005360 WILL_LJMP(lua_error(L));
5361
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005362 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
5363}
5364
5365/* This function replace full header, or just a value in
5366 * the request or in the response. It is a wrapper fir the
5367 * 4 following functions.
5368 */
5369__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
5370 struct http_msg *msg, int action)
5371{
5372 size_t name_len;
5373 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5374 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5375 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Dragan Dosen26743032019-04-30 15:54:36 +02005376 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005377
Dragan Dosen26743032019-04-30 15:54:36 +02005378 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005379 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5380
Christopher Faulet5a8549e2019-06-17 13:36:06 +02005381 if (IS_HTX_STRM(htxn->s)) {
5382 struct htx *htx = htxbuf(&msg->chn->buf);
5383
5384 htx_transform_header_str(htxn->s, msg->chn, htx, ist2(name, name_len), value, re, action);
5385 }
5386 else
5387 http_transform_header_str(htxn->s, msg, name, name_len, value, re, action);
Dragan Dosen26743032019-04-30 15:54:36 +02005388 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005389 return 0;
5390}
5391
5392__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5393{
5394 struct hlua_txn *htxn;
5395
5396 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5397 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5398
Christopher Faulet2351ca22019-07-26 16:31:34 +02005399 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005400 WILL_LJMP(lua_error(L));
5401
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005402 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
5403}
5404
5405__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5406{
5407 struct hlua_txn *htxn;
5408
5409 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5410 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5411
Christopher Faulet2351ca22019-07-26 16:31:34 +02005412 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005413 WILL_LJMP(lua_error(L));
5414
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005415 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
5416}
5417
5418__LJMP static int hlua_http_req_rep_val(lua_State *L)
5419{
5420 struct hlua_txn *htxn;
5421
5422 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5423 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5424
Christopher Faulet2351ca22019-07-26 16:31:34 +02005425 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005426 WILL_LJMP(lua_error(L));
5427
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005428 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
5429}
5430
5431__LJMP static int hlua_http_res_rep_val(lua_State *L)
5432{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005433 struct hlua_txn *htxn;
5434
5435 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5436 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5437
Christopher Faulet2351ca22019-07-26 16:31:34 +02005438 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005439 WILL_LJMP(lua_error(L));
5440
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02005441 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005442}
5443
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005444/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005445 * It is a wrapper for the 2 following functions.
5446 */
5447__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5448{
5449 size_t len;
5450 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005451
Christopher Faulet724a12c2018-12-13 22:12:15 +01005452 if (IS_HTX_STRM(htxn->s)) {
5453 /* HTX version */
5454 struct htx *htx = htxbuf(&msg->chn->buf);
5455 struct http_hdr_ctx ctx;
5456
5457 ctx.blk = NULL;
5458 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5459 http_remove_header(htx, &ctx);
5460 }
5461 else {
5462 /* Legacy HTTP version */
5463 struct hdr_ctx ctx;
5464 struct http_txn *txn = htxn->s->txn;
5465
5466 ctx.idx = 0;
5467 while (http_find_header2(name, len, ci_head(msg->chn), &txn->hdr_idx, &ctx))
5468 http_remove_header2(msg, &txn->hdr_idx, &ctx);
5469 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005470 return 0;
5471}
5472
5473__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5474{
5475 struct hlua_txn *htxn;
5476
5477 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5478 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5479
Christopher Faulet2351ca22019-07-26 16:31:34 +02005480 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005481 WILL_LJMP(lua_error(L));
5482
Willy Tarreaueee5b512015-04-03 23:46:31 +02005483 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005484}
5485
5486__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5487{
5488 struct hlua_txn *htxn;
5489
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005490 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005491 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5492
Christopher Faulet2351ca22019-07-26 16:31:34 +02005493 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005494 WILL_LJMP(lua_error(L));
5495
Willy Tarreaueee5b512015-04-03 23:46:31 +02005496 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005497}
5498
5499/* This function adds an header. It is a wrapper used by
5500 * the 2 following functions.
5501 */
5502__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5503{
5504 size_t name_len;
5505 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5506 size_t value_len;
5507 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
5508 char *p;
5509
Christopher Faulet724a12c2018-12-13 22:12:15 +01005510 if (IS_HTX_STRM(htxn->s)) {
5511 /* HTX version */
5512 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005513
Christopher Faulet724a12c2018-12-13 22:12:15 +01005514 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5515 ist2(value, value_len)));
5516 }
5517 else {
5518 /* Legacy HTTP version */
5519 /* Check length. */
5520 trash.data = value_len + name_len + 2;
5521 if (trash.data > trash.size)
5522 return 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005523
Christopher Faulet724a12c2018-12-13 22:12:15 +01005524 /* Creates the header string. */
5525 p = trash.area;
5526 memcpy(p, name, name_len);
5527 p += name_len;
5528 *p = ':';
5529 p++;
5530 *p = ' ';
5531 p++;
5532 memcpy(p, value, value_len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005533
Christopher Faulet724a12c2018-12-13 22:12:15 +01005534 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
5535 trash.area, trash.data) != 0);
5536 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005537 return 0;
5538}
5539
5540__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5541{
5542 struct hlua_txn *htxn;
5543
5544 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5545 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5546
Christopher Faulet2351ca22019-07-26 16:31:34 +02005547 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005548 WILL_LJMP(lua_error(L));
5549
Willy Tarreaueee5b512015-04-03 23:46:31 +02005550 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005551}
5552
5553__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5554{
5555 struct hlua_txn *htxn;
5556
5557 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5558 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5559
Christopher Faulet2351ca22019-07-26 16:31:34 +02005560 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005561 WILL_LJMP(lua_error(L));
5562
Willy Tarreaueee5b512015-04-03 23:46:31 +02005563 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005564}
5565
5566static int hlua_http_req_set_hdr(lua_State *L)
5567{
5568 struct hlua_txn *htxn;
5569
5570 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5571 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5572
Christopher Faulet2351ca22019-07-26 16:31:34 +02005573 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005574 WILL_LJMP(lua_error(L));
5575
Willy Tarreaueee5b512015-04-03 23:46:31 +02005576 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
5577 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005578}
5579
5580static int hlua_http_res_set_hdr(lua_State *L)
5581{
5582 struct hlua_txn *htxn;
5583
5584 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5585 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5586
Christopher Faulet2351ca22019-07-26 16:31:34 +02005587 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005588 WILL_LJMP(lua_error(L));
5589
Willy Tarreaueee5b512015-04-03 23:46:31 +02005590 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
5591 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005592}
5593
5594/* This function set the method. */
5595static int hlua_http_req_set_meth(lua_State *L)
5596{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005597 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005598 size_t name_len;
5599 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005600
Christopher Faulet2351ca22019-07-26 16:31:34 +02005601 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005602 WILL_LJMP(lua_error(L));
5603
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005604 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005605 return 1;
5606}
5607
5608/* This function set the method. */
5609static int hlua_http_req_set_path(lua_State *L)
5610{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005611 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005612 size_t name_len;
5613 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005614
Christopher Faulet2351ca22019-07-26 16:31:34 +02005615 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005616 WILL_LJMP(lua_error(L));
5617
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005618 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005619 return 1;
5620}
5621
5622/* This function set the query-string. */
5623static int hlua_http_req_set_query(lua_State *L)
5624{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005625 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005626 size_t name_len;
5627 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005628
Christopher Faulet2351ca22019-07-26 16:31:34 +02005629 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005630 WILL_LJMP(lua_error(L));
5631
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005632 /* Check length. */
5633 if (name_len > trash.size - 1) {
5634 lua_pushboolean(L, 0);
5635 return 1;
5636 }
5637
5638 /* Add the mark question as prefix. */
5639 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005640 trash.area[trash.data++] = '?';
5641 memcpy(trash.area + trash.data, name, name_len);
5642 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005643
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005644 lua_pushboolean(L,
5645 http_replace_req_line(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005646 return 1;
5647}
5648
5649/* This function set the uri. */
5650static int hlua_http_req_set_uri(lua_State *L)
5651{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005652 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005653 size_t name_len;
5654 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005655
Christopher Faulet2351ca22019-07-26 16:31:34 +02005656 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005657 WILL_LJMP(lua_error(L));
5658
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005659 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005660 return 1;
5661}
5662
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005663/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005664static int hlua_http_res_set_status(lua_State *L)
5665{
5666 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5667 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005668 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005669
Christopher Faulet2351ca22019-07-26 16:31:34 +02005670 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Fauletdc2ee272019-07-26 16:17:01 +02005671 WILL_LJMP(lua_error(L));
5672
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005673 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005674 return 0;
5675}
5676
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005677/*
5678 *
5679 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005680 * Class TXN
5681 *
5682 *
5683 */
5684
5685/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005686 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005687 */
5688__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5689{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005690 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005691}
5692
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005693__LJMP static int hlua_set_var(lua_State *L)
5694{
5695 struct hlua_txn *htxn;
5696 const char *name;
5697 size_t len;
5698 struct sample smp;
5699
5700 MAY_LJMP(check_args(L, 3, "set_var"));
5701
5702 /* It is useles to retrieve the stream, but this function
5703 * runs only in a stream context.
5704 */
5705 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5706 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5707
5708 /* Converts the third argument in a sample. */
5709 hlua_lua2smp(L, 3, &smp);
5710
5711 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005712 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005713 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005714 return 0;
5715}
5716
Christopher Faulet85d79c92016-11-09 16:54:56 +01005717__LJMP static int hlua_unset_var(lua_State *L)
5718{
5719 struct hlua_txn *htxn;
5720 const char *name;
5721 size_t len;
5722 struct sample smp;
5723
5724 MAY_LJMP(check_args(L, 2, "unset_var"));
5725
5726 /* It is useles to retrieve the stream, but this function
5727 * runs only in a stream context.
5728 */
5729 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5730 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5731
5732 /* Unset the variable. */
5733 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5734 vars_unset_by_name(name, len, &smp);
5735 return 0;
5736}
5737
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005738__LJMP static int hlua_get_var(lua_State *L)
5739{
5740 struct hlua_txn *htxn;
5741 const char *name;
5742 size_t len;
5743 struct sample smp;
5744
5745 MAY_LJMP(check_args(L, 2, "get_var"));
5746
5747 /* It is useles to retrieve the stream, but this function
5748 * runs only in a stream context.
5749 */
5750 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5751 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5752
Willy Tarreau7560dd42016-03-10 16:28:58 +01005753 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005754 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005755 lua_pushnil(L);
5756 return 1;
5757 }
5758
5759 return hlua_smp2lua(L, &smp);
5760}
5761
Willy Tarreau59551662015-03-10 14:23:13 +01005762__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005763{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005764 struct hlua *hlua;
5765
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005766 MAY_LJMP(check_args(L, 2, "set_priv"));
5767
Willy Tarreau87b09662015-04-03 00:22:06 +02005768 /* It is useles to retrieve the stream, but this function
5769 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005770 */
5771 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005772 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005773
5774 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005775 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005776
5777 /* Get and store new value. */
5778 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5779 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5780
5781 return 0;
5782}
5783
Willy Tarreau59551662015-03-10 14:23:13 +01005784__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005785{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005786 struct hlua *hlua;
5787
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005788 MAY_LJMP(check_args(L, 1, "get_priv"));
5789
Willy Tarreau87b09662015-04-03 00:22:06 +02005790 /* It is useles to retrieve the stream, but this function
5791 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005792 */
5793 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005794 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005795
5796 /* Push configuration index in the stack. */
5797 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5798
5799 return 1;
5800}
5801
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005802/* Create stack entry containing a class TXN. This function
5803 * return 0 if the stack does not contains free slots,
5804 * otherwise it returns 1.
5805 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005806static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005807{
Willy Tarreaude491382015-04-06 11:04:28 +02005808 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005809
5810 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005811 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005812 return 0;
5813
5814 /* NOTE: The allocation never fails. The failure
5815 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005816 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005817 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005818 /* Create the object: obj[0] = userdata. */
5819 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005820 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005821 lua_rawseti(L, -2, 0);
5822
Willy Tarreaude491382015-04-06 11:04:28 +02005823 htxn->s = s;
5824 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005825 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005826 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005827
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005828 /* Create the "f" field that contains a list of fetches. */
5829 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005830 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005831 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005832 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005833
5834 /* Create the "sf" field that contains a list of stringsafe fetches. */
5835 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005836 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005837 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005838 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005839
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005840 /* Create the "c" field that contains a list of converters. */
5841 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005842 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005843 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005844 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005845
5846 /* Create the "sc" field that contains a list of stringsafe converters. */
5847 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005848 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005849 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005850 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005851
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005852 /* Create the "req" field that contains the request channel object. */
5853 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005854 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005855 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005856 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005857
5858 /* Create the "res" field that contains the response channel object. */
5859 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005860 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005861 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005862 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005863
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005864 /* Creates the HTTP object is the current proxy allows http. */
5865 lua_pushstring(L, "http");
5866 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005867 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005868 return 0;
5869 }
5870 else
5871 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005872 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005873
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005874 /* Pop a class sesison metatable and affect it to the userdata. */
5875 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5876 lua_setmetatable(L, -2);
5877
5878 return 1;
5879}
5880
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005881__LJMP static int hlua_txn_deflog(lua_State *L)
5882{
5883 const char *msg;
5884 struct hlua_txn *htxn;
5885
5886 MAY_LJMP(check_args(L, 2, "deflog"));
5887 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5888 msg = MAY_LJMP(luaL_checkstring(L, 2));
5889
5890 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5891 return 0;
5892}
5893
5894__LJMP static int hlua_txn_log(lua_State *L)
5895{
5896 int level;
5897 const char *msg;
5898 struct hlua_txn *htxn;
5899
5900 MAY_LJMP(check_args(L, 3, "log"));
5901 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5902 level = MAY_LJMP(luaL_checkinteger(L, 2));
5903 msg = MAY_LJMP(luaL_checkstring(L, 3));
5904
5905 if (level < 0 || level >= NB_LOG_LEVELS)
5906 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5907
5908 hlua_sendlog(htxn->s->be, level, msg);
5909 return 0;
5910}
5911
5912__LJMP static int hlua_txn_log_debug(lua_State *L)
5913{
5914 const char *msg;
5915 struct hlua_txn *htxn;
5916
5917 MAY_LJMP(check_args(L, 2, "Debug"));
5918 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5919 msg = MAY_LJMP(luaL_checkstring(L, 2));
5920 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5921 return 0;
5922}
5923
5924__LJMP static int hlua_txn_log_info(lua_State *L)
5925{
5926 const char *msg;
5927 struct hlua_txn *htxn;
5928
5929 MAY_LJMP(check_args(L, 2, "Info"));
5930 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5931 msg = MAY_LJMP(luaL_checkstring(L, 2));
5932 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5933 return 0;
5934}
5935
5936__LJMP static int hlua_txn_log_warning(lua_State *L)
5937{
5938 const char *msg;
5939 struct hlua_txn *htxn;
5940
5941 MAY_LJMP(check_args(L, 2, "Warning"));
5942 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5943 msg = MAY_LJMP(luaL_checkstring(L, 2));
5944 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5945 return 0;
5946}
5947
5948__LJMP static int hlua_txn_log_alert(lua_State *L)
5949{
5950 const char *msg;
5951 struct hlua_txn *htxn;
5952
5953 MAY_LJMP(check_args(L, 2, "Alert"));
5954 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5955 msg = MAY_LJMP(luaL_checkstring(L, 2));
5956 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5957 return 0;
5958}
5959
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005960__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5961{
5962 struct hlua_txn *htxn;
5963 int ll;
5964
5965 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5966 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5967 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5968
5969 if (ll < 0 || ll > 7)
5970 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5971
5972 htxn->s->logs.level = ll;
5973 return 0;
5974}
5975
5976__LJMP static int hlua_txn_set_tos(lua_State *L)
5977{
5978 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005979 int tos;
5980
5981 MAY_LJMP(check_args(L, 2, "set_tos"));
5982 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5983 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5984
Willy Tarreau1a18b542018-12-11 16:37:42 +01005985 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005986 return 0;
5987}
5988
5989__LJMP static int hlua_txn_set_mark(lua_State *L)
5990{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005991 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005992 int mark;
5993
5994 MAY_LJMP(check_args(L, 2, "set_mark"));
5995 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5996 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5997
Lukas Tribusb59291a2019-08-11 18:03:45 +02005998 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005999 return 0;
6000}
6001
Patrick Hemmer268a7072018-05-11 12:52:31 -04006002__LJMP static int hlua_txn_set_priority_class(lua_State *L)
6003{
6004 struct hlua_txn *htxn;
6005
6006 MAY_LJMP(check_args(L, 2, "set_priority_class"));
6007 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6008 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
6009 return 0;
6010}
6011
6012__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
6013{
6014 struct hlua_txn *htxn;
6015
6016 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
6017 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6018 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
6019 return 0;
6020}
6021
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006022/* This function is an Lua binding that send pending data
6023 * to the client, and close the stream interface.
6024 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006025__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006026{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006027 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006028 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01006029 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006030
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006031 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006032 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006033 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006034
Thierry FOURNIERab00df62016-07-14 11:42:37 +02006035 /* If the flags NOTERM is set, we cannot terminate the http
6036 * session, so we just end the execution of the current
6037 * lua code.
6038 */
6039 if (htxn->flags & HLUA_TXN_NOTERM) {
6040 WILL_LJMP(hlua_done(L));
6041 return 0;
6042 }
6043
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006044 ic = &htxn->s->req;
6045 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01006046
Christopher Faulet72c69272019-07-26 16:40:24 +02006047 if (IS_HTX_STRM(htxn->s)) {
6048 htxn->s->txn->status = 0;
6049 http_reply_and_close(htxn->s, 0, NULL);
6050 ic->analysers &= AN_REQ_FLT_END;
6051 oc->analysers &= AN_RES_FLT_END;
6052 }
Christopher Fauletb58fb792019-07-16 10:52:40 +02006053 else {
6054 if (htxn->s->txn) {
6055 /* HTTP mode, let's stay in sync with the stream */
6056 b_del(&ic->buf, htxn->s->txn->req.sov);
6057 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
6058 htxn->s->txn->req.sov = 0;
6059
6060 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
6061 oc->analysers = AN_RES_HTTP_XFER_BODY;
6062 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
6063 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
Willy Tarreau630ef452015-08-28 10:06:15 +02006064
Willy Tarreau630ef452015-08-28 10:06:15 +02006065 /* Note that if we want to support keep-alive, we need
6066 * to bypass the close/shutr_now calls below, but that
6067 * may only be done if the HTTP request was already
6068 * processed and the connection header is known (ie
6069 * not during TCP rules).
6070 */
Christopher Fauletb58fb792019-07-16 10:52:40 +02006071 }
Willy Tarreau630ef452015-08-28 10:06:15 +02006072
Christopher Fauletb58fb792019-07-16 10:52:40 +02006073 channel_auto_read(ic);
6074 channel_abort(ic);
6075 channel_auto_close(ic);
6076 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02006077
Christopher Fauletb58fb792019-07-16 10:52:40 +02006078 oc->wex = tick_add_ifset(now_ms, oc->wto);
6079 channel_auto_read(oc);
6080 channel_auto_close(oc);
6081 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006082
Christopher Fauletb58fb792019-07-16 10:52:40 +02006083 ic->analysers = 0;
6084 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006085
Christopher Faulet72c69272019-07-26 16:40:24 +02006086 if (!(htxn->s->flags & SF_ERR_MASK)) // this is not really an error but it is
6087 htxn->s->flags |= SF_ERR_LOCAL; // to mark that it comes from the proxy
6088
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006089 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006090 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006091 return 0;
6092}
6093
6094__LJMP static int hlua_log(lua_State *L)
6095{
6096 int level;
6097 const char *msg;
6098
6099 MAY_LJMP(check_args(L, 2, "log"));
6100 level = MAY_LJMP(luaL_checkinteger(L, 1));
6101 msg = MAY_LJMP(luaL_checkstring(L, 2));
6102
6103 if (level < 0 || level >= NB_LOG_LEVELS)
6104 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
6105
6106 hlua_sendlog(NULL, level, msg);
6107 return 0;
6108}
6109
6110__LJMP static int hlua_log_debug(lua_State *L)
6111{
6112 const char *msg;
6113
6114 MAY_LJMP(check_args(L, 1, "debug"));
6115 msg = MAY_LJMP(luaL_checkstring(L, 1));
6116 hlua_sendlog(NULL, LOG_DEBUG, msg);
6117 return 0;
6118}
6119
6120__LJMP static int hlua_log_info(lua_State *L)
6121{
6122 const char *msg;
6123
6124 MAY_LJMP(check_args(L, 1, "info"));
6125 msg = MAY_LJMP(luaL_checkstring(L, 1));
6126 hlua_sendlog(NULL, LOG_INFO, msg);
6127 return 0;
6128}
6129
6130__LJMP static int hlua_log_warning(lua_State *L)
6131{
6132 const char *msg;
6133
6134 MAY_LJMP(check_args(L, 1, "warning"));
6135 msg = MAY_LJMP(luaL_checkstring(L, 1));
6136 hlua_sendlog(NULL, LOG_WARNING, msg);
6137 return 0;
6138}
6139
6140__LJMP static int hlua_log_alert(lua_State *L)
6141{
6142 const char *msg;
6143
6144 MAY_LJMP(check_args(L, 1, "alert"));
6145 msg = MAY_LJMP(luaL_checkstring(L, 1));
6146 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006147 return 0;
6148}
6149
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006150__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006151{
6152 int wakeup_ms = lua_tointeger(L, -1);
6153 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02006154 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006155 return 0;
6156}
6157
6158__LJMP static int hlua_sleep(lua_State *L)
6159{
6160 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006161 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006162
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006163 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006164
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006165 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006166 wakeup_ms = tick_add(now_ms, delay);
6167 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006168
Willy Tarreau9635e032018-10-16 17:52:55 +02006169 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006170 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006171}
6172
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006173__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006174{
6175 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006176 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006177
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006178 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006179
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006180 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006181 wakeup_ms = tick_add(now_ms, delay);
6182 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006183
Willy Tarreau9635e032018-10-16 17:52:55 +02006184 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006185 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006186}
6187
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006188/* This functionis an LUA binding. it permits to give back
6189 * the hand at the HAProxy scheduler. It is used when the
6190 * LUA processing consumes a lot of time.
6191 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006192__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006193{
6194 return 0;
6195}
6196
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006197__LJMP static int hlua_yield(lua_State *L)
6198{
Willy Tarreau9635e032018-10-16 17:52:55 +02006199 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006200 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006201}
6202
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006203/* This function change the nice of the currently executed
6204 * task. It is used set low or high priority at the current
6205 * task.
6206 */
Willy Tarreau59551662015-03-10 14:23:13 +01006207__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006208{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006209 struct hlua *hlua;
6210 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006211
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006212 MAY_LJMP(check_args(L, 1, "set_nice"));
6213 hlua = hlua_gethlua(L);
6214 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006215
6216 /* If he task is not set, I'm in a start mode. */
6217 if (!hlua || !hlua->task)
6218 return 0;
6219
6220 if (nice < -1024)
6221 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006222 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006223 nice = 1024;
6224
6225 hlua->task->nice = nice;
6226 return 0;
6227}
6228
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006229/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006230 * HAProxy task subsystem when the task is awaked. The LUA runtime can
6231 * return an E_AGAIN signal, the emmiter of this signal must set a
6232 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006233 *
6234 * Task wrapper are longjmp safe because the only one Lua code
6235 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006236 */
Willy Tarreau83a5ff42019-08-21 14:14:50 +02006237struct task *hlua_process_task(struct task *task, void *context, unsigned short state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006238{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006239 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006240 enum hlua_exec status;
6241
Christopher Faulet5bc99722018-04-25 10:34:45 +02006242 if (task->thread_mask == MAX_THREADS_MASK)
6243 task_set_affinity(task, tid_bit);
6244
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006245 /* If it is the first call to the task, we must initialize the
6246 * execution timeouts.
6247 */
6248 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006249 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006250
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006251 /* Execute the Lua code. */
6252 status = hlua_ctx_resume(hlua, 1);
6253
6254 switch (status) {
6255 /* finished or yield */
6256 case HLUA_E_OK:
6257 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006258 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02006259 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006260 break;
6261
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006262 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01006263 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02006264 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006265 break;
6266
6267 /* finished with error. */
6268 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006269 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006270 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006271 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006272 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006273 break;
6274
6275 case HLUA_E_ERR:
6276 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006277 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006278 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006279 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006280 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006281 break;
6282 }
Emeric Brun253e53e2017-10-17 18:58:40 +02006283 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006284}
6285
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006286/* This function is an LUA binding that register LUA function to be
6287 * executed after the HAProxy configuration parsing and before the
6288 * HAProxy scheduler starts. This function expect only one LUA
6289 * argument that is a function. This function returns nothing, but
6290 * throws if an error is encountered.
6291 */
6292__LJMP static int hlua_register_init(lua_State *L)
6293{
6294 struct hlua_init_function *init;
6295 int ref;
6296
6297 MAY_LJMP(check_args(L, 1, "register_init"));
6298
6299 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6300
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006301 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006302 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006303 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006304
6305 init->function_ref = ref;
6306 LIST_ADDQ(&hlua_init_functions, &init->l);
6307 return 0;
6308}
6309
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006310/* This functio is an LUA binding. It permits to register a task
6311 * executed in parallel of the main HAroxy activity. The task is
6312 * created and it is set in the HAProxy scheduler. It can be called
6313 * from the "init" section, "post init" or during the runtime.
6314 *
6315 * Lua prototype:
6316 *
6317 * <none> core.register_task(<function>)
6318 */
6319static int hlua_register_task(lua_State *L)
6320{
6321 struct hlua *hlua;
6322 struct task *task;
6323 int ref;
6324
6325 MAY_LJMP(check_args(L, 1, "register_task"));
6326
6327 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6328
Willy Tarreaubafbe012017-11-24 17:34:44 +01006329 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006330 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006331 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006332
Emeric Brunc60def82017-09-27 14:59:38 +02006333 task = task_new(MAX_THREADS_MASK);
Willy Tarreaue09101e2018-10-16 17:37:12 +02006334 if (!task)
6335 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
6336
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006337 task->context = hlua;
6338 task->process = hlua_process_task;
6339
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006340 if (!hlua_ctx_init(hlua, task, 1))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006341 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006342
6343 /* Restore the function in the stack. */
6344 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
6345 hlua->nargs = 0;
6346
6347 /* Schedule task. */
6348 task_schedule(task, now_ms);
6349
6350 return 0;
6351}
6352
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006353/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
6354 * doesn't allow "yield" functions because the HAProxy engine cannot
6355 * resume converters.
6356 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006357static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006358{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006359 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006360 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006361 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006362
Willy Tarreaube508f12016-03-10 11:47:01 +01006363 if (!stream)
6364 return 0;
6365
Willy Tarreau87b09662015-04-03 00:22:06 +02006366 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006367 * Lua context can be not initialized. This behavior
6368 * permits to save performances because a systematic
6369 * Lua initialization cause 5% performances loss.
6370 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006371 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006372 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006373 if (!stream->hlua) {
6374 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6375 return 0;
6376 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006377 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006378 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6379 return 0;
6380 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006381 }
6382
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006383 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006384 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006385
6386 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006387 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6388 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6389 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006390 else
6391 error = "critical error";
6392 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006393 return 0;
6394 }
6395
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006396 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006397 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006398 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006399 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006400 return 0;
6401 }
6402
6403 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006404 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006405
6406 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006407 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006408 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006409 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006410 return 0;
6411 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006412 hlua_smp2lua(stream->hlua->T, smp);
6413 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006414
6415 /* push keywords in the stack. */
6416 if (arg_p) {
6417 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006418 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006419 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006420 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006421 return 0;
6422 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006423 hlua_arg2lua(stream->hlua->T, arg_p);
6424 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006425 }
6426 }
6427
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006428 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006429 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006430
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006431 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006432 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006433 }
6434
6435 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006436 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006437 /* finished. */
6438 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006439 /* If the stack is empty, the function fails. */
6440 if (lua_gettop(stream->hlua->T) <= 0)
6441 return 0;
6442
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006443 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006444 hlua_lua2smp(stream->hlua->T, -1, smp);
6445 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006446 return 1;
6447
6448 /* yield. */
6449 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006450 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006451 return 0;
6452
6453 /* finished with error. */
6454 case HLUA_E_ERRMSG:
6455 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006456 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006457 fcn->name, lua_tostring(stream->hlua->T, -1));
6458 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006459 return 0;
6460
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006461 case HLUA_E_ETMOUT:
6462 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
6463 return 0;
6464
6465 case HLUA_E_NOMEM:
6466 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
6467 return 0;
6468
6469 case HLUA_E_YIELD:
6470 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
6471 return 0;
6472
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006473 case HLUA_E_ERR:
6474 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006475 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006476
6477 default:
6478 return 0;
6479 }
6480}
6481
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006482/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
6483 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01006484 * resume sample-fetches. This function will be called by the sample
6485 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006486 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02006487static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
6488 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006489{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006490 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006491 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006492 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006493 const struct buffer msg = { };
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006494 unsigned int hflags = HLUA_TXN_NOTERM;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006495
Willy Tarreaube508f12016-03-10 11:47:01 +01006496 if (!stream)
6497 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01006498
Willy Tarreau87b09662015-04-03 00:22:06 +02006499 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006500 * Lua context can be not initialized. This behavior
6501 * permits to save performances because a systematic
6502 * Lua initialization cause 5% performances loss.
6503 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006504 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006505 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006506 if (!stream->hlua) {
6507 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6508 return 0;
6509 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006510 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006511 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6512 return 0;
6513 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006514 }
6515
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006516 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006517
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006518 if (stream->be->mode == PR_MODE_HTTP) {
6519 if ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ)
6520 hflags |= ((stream->txn->req.msg_state < HTTP_MSG_BODY) ? 0 : HLUA_TXN_HTTP_RDY);
6521 else
6522 hflags |= ((stream->txn->rsp.msg_state < HTTP_MSG_BODY) ? 0 : HLUA_TXN_HTTP_RDY);
6523 }
6524
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006525 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006526 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006527
6528 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006529 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6530 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6531 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006532 else
6533 error = "critical error";
6534 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006535 return 0;
6536 }
6537
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006538 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006539 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006540 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006541 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006542 return 0;
6543 }
6544
6545 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006546 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006547
6548 /* push arguments in the stack. */
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006549 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006550 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006551 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006552 return 0;
6553 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006554 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006555
6556 /* push keywords in the stack. */
6557 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
6558 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006559 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006560 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006561 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006562 return 0;
6563 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006564 hlua_arg2lua(stream->hlua->T, arg_p);
6565 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006566 }
6567
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006568 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006569 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006570
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006571 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006572 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006573 }
6574
6575 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006576 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006577 /* finished. */
6578 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006579 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006580 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006581 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006582 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006583 /* If the stack is empty, the function fails. */
6584 if (lua_gettop(stream->hlua->T) <= 0)
6585 return 0;
6586
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006587 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006588 hlua_lua2smp(stream->hlua->T, -1, smp);
6589 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006590
6591 /* Set the end of execution flag. */
6592 smp->flags &= ~SMP_F_MAY_CHANGE;
6593 return 1;
6594
6595 /* yield. */
6596 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006597 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006598 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006599 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006600 return 0;
6601
6602 /* finished with error. */
6603 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006604 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006605 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006606 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006607 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006608 fcn->name, lua_tostring(stream->hlua->T, -1));
6609 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006610 return 0;
6611
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006612 case HLUA_E_ETMOUT:
6613 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006614 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006615 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
6616 return 0;
6617
6618 case HLUA_E_NOMEM:
6619 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006620 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006621 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
6622 return 0;
6623
6624 case HLUA_E_YIELD:
6625 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006626 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006627 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
6628 return 0;
6629
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006630 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006631 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006632 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006633 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006634 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006635
6636 default:
6637 return 0;
6638 }
6639}
6640
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006641/* This function is an LUA binding used for registering
6642 * "sample-conv" functions. It expects a converter name used
6643 * in the haproxy configuration file, and an LUA function.
6644 */
6645__LJMP static int hlua_register_converters(lua_State *L)
6646{
6647 struct sample_conv_kw_list *sck;
6648 const char *name;
6649 int ref;
6650 int len;
6651 struct hlua_function *fcn;
6652
6653 MAY_LJMP(check_args(L, 2, "register_converters"));
6654
6655 /* First argument : converter name. */
6656 name = MAY_LJMP(luaL_checkstring(L, 1));
6657
6658 /* Second argument : lua function. */
6659 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6660
6661 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006662 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006663 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006664 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006665 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006666 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006667 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006668
6669 /* Fill fcn. */
6670 fcn->name = strdup(name);
6671 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006672 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006673 fcn->function_ref = ref;
6674
6675 /* List head */
6676 sck->list.n = sck->list.p = NULL;
6677
6678 /* converter keyword. */
6679 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006680 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006681 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006682 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006683
6684 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6685 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006686 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 +01006687 sck->kw[0].val_args = NULL;
6688 sck->kw[0].in_type = SMP_T_STR;
6689 sck->kw[0].out_type = SMP_T_STR;
6690 sck->kw[0].private = fcn;
6691
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006692 /* Register this new converter */
6693 sample_register_convs(sck);
6694
6695 return 0;
6696}
6697
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006698/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006699 * "sample-fetch" functions. It expects a converter name used
6700 * in the haproxy configuration file, and an LUA function.
6701 */
6702__LJMP static int hlua_register_fetches(lua_State *L)
6703{
6704 const char *name;
6705 int ref;
6706 int len;
6707 struct sample_fetch_kw_list *sfk;
6708 struct hlua_function *fcn;
6709
6710 MAY_LJMP(check_args(L, 2, "register_fetches"));
6711
6712 /* First argument : sample-fetch name. */
6713 name = MAY_LJMP(luaL_checkstring(L, 1));
6714
6715 /* Second argument : lua function. */
6716 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6717
6718 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006719 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006720 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006721 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006722 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006723 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006724 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006725
6726 /* Fill fcn. */
6727 fcn->name = strdup(name);
6728 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006729 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006730 fcn->function_ref = ref;
6731
6732 /* List head */
6733 sfk->list.n = sfk->list.p = NULL;
6734
6735 /* sample-fetch keyword. */
6736 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006737 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006738 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006739 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006740
6741 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6742 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006743 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 +01006744 sfk->kw[0].val_args = NULL;
6745 sfk->kw[0].out_type = SMP_T_STR;
6746 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6747 sfk->kw[0].val = 0;
6748 sfk->kw[0].private = fcn;
6749
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006750 /* Register this new fetch. */
6751 sample_register_fetches(sfk);
6752
6753 return 0;
6754}
6755
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006756/* This function is a wrapper to execute each LUA function declared
6757 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006758 * return ACT_RET_CONT if the processing is finished (with or without
6759 * error) and return ACT_RET_YIELD if the function must be called again
6760 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006761 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006762static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006763 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006764{
6765 char **arg;
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006766 unsigned int hflags = 0;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006767 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006768 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006769 const struct buffer msg = { };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006770
6771 switch (rule->from) {
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006772 case ACT_F_TCP_REQ_CNT: ; dir = SMP_OPT_DIR_REQ; break;
6773 case ACT_F_TCP_RES_CNT: ; dir = SMP_OPT_DIR_RES; break;
6774 case ACT_F_HTTP_REQ: hflags = HLUA_TXN_HTTP_RDY ; dir = SMP_OPT_DIR_REQ; break;
6775 case ACT_F_HTTP_RES: hflags = HLUA_TXN_HTTP_RDY ; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006776 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006777 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006778 return ACT_RET_CONT;
6779 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006780
Willy Tarreau87b09662015-04-03 00:22:06 +02006781 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006782 * Lua context can be not initialized. This behavior
6783 * permits to save performances because a systematic
6784 * Lua initialization cause 5% performances loss.
6785 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006786 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006787 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006788 if (!s->hlua) {
6789 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6790 rule->arg.hlua_rule->fcn.name);
6791 return ACT_RET_CONT;
6792 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006793 if (!hlua_ctx_init(s->hlua, s->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006794 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6795 rule->arg.hlua_rule->fcn.name);
6796 return ACT_RET_CONT;
6797 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006798 }
6799
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006800 consistency_set(s, dir, &s->hlua->cons);
6801
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006802 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006803 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006804
6805 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006806 if (!SET_SAFE_LJMP(s->hlua->T)) {
6807 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6808 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006809 else
6810 error = "critical error";
6811 SEND_ERR(px, "Lua function '%s': %s.\n",
6812 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006813 return ACT_RET_CONT;
6814 }
6815
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006816 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006817 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006818 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006819 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006820 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006821 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006822 }
6823
6824 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006825 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006826
Willy Tarreau87b09662015-04-03 00:22:06 +02006827 /* Create and and push object stream in the stack. */
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006828 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006829 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006830 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006831 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006832 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006833 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006834 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006835
6836 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006837 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006838 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006839 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006840 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006841 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006842 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006843 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006844 lua_pushstring(s->hlua->T, *arg);
6845 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006846 }
6847
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006848 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006849 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006850
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006851 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006852 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006853 }
6854
6855 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006856 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006857 /* finished. */
6858 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006859 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006860 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006861 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006862 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006863 if (s->hlua->flags & HLUA_STOP)
Christopher Faulet4629d082019-07-04 11:27:15 +02006864 return ACT_RET_DONE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006865 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006866
6867 /* yield. */
6868 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006869 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006870 if (s->hlua->wake_time != TICK_ETERNITY) {
Christopher Fauletea0b0e22019-08-14 23:19:45 +02006871 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006872 s->req.analyse_exp = s->hlua->wake_time;
Christopher Fauletff96b8b2019-07-26 15:09:53 +02006873 else
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006874 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006875 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006876 /* Some actions can be wake up when a "write" event
6877 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006878 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006879 */
Christopher Fauletb22f6502019-07-26 14:54:52 +02006880 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006881 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006882 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006883 s->req.flags |= CF_WAKE_WRITE;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006884 /* We can quit the function without consistency check
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006885 * because HAProxy is not able to manipulate data, it
6886 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006887 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006888
6889 /* finished with error. */
6890 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006891 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006892 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006893 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006894 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006895 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006896 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006897 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6898 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006899 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006900
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006901 case HLUA_E_ETMOUT:
6902 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006903 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006904 return ACT_RET_ERR;
6905 }
6906 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
6907 return 0;
6908
6909 case HLUA_E_NOMEM:
6910 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006911 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006912 return ACT_RET_ERR;
6913 }
6914 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
6915 return 0;
6916
6917 case HLUA_E_YIELD:
6918 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006919 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006920 return ACT_RET_ERR;
6921 }
6922 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6923 rule->arg.hlua_rule->fcn.name);
6924 return 0;
6925
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006926 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006927 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006928 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006929 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006930 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006931 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006932 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006933 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006934
6935 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006936 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006937 }
6938}
6939
Olivier Houchard9f6af332018-05-25 14:04:04 +02006940struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006941{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006942 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006943
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006944 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006945 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006946 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006947}
6948
6949static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6950{
6951 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006952 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006953 struct task *task;
6954 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006955 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006956
Willy Tarreaubafbe012017-11-24 17:34:44 +01006957 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006958 if (!hlua) {
6959 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6960 ctx->rule->arg.hlua_rule->fcn.name);
6961 return 0;
6962 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006963 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006964 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006965 ctx->ctx.hlua_apptcp.flags = 0;
6966
6967 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006968 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006969 if (!task) {
6970 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6971 ctx->rule->arg.hlua_rule->fcn.name);
6972 return 0;
6973 }
6974 task->nice = 0;
6975 task->context = ctx;
6976 task->process = hlua_applet_wakeup;
6977 ctx->ctx.hlua_apptcp.task = task;
6978
6979 /* In the execution wrappers linked with a stream, the
6980 * Lua context can be not initialized. This behavior
6981 * permits to save performances because a systematic
6982 * Lua initialization cause 5% performances loss.
6983 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006984 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006985 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6986 ctx->rule->arg.hlua_rule->fcn.name);
6987 return 0;
6988 }
6989
6990 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006991 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006992
6993 /* The following Lua calls can fail. */
6994 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006995 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6996 error = lua_tostring(hlua->T, -1);
6997 else
6998 error = "critical error";
6999 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
7000 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007001 return 0;
7002 }
7003
7004 /* Check stack available size. */
7005 if (!lua_checkstack(hlua->T, 1)) {
7006 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7007 ctx->rule->arg.hlua_rule->fcn.name);
7008 RESET_SAFE_LJMP(hlua->T);
7009 return 0;
7010 }
7011
7012 /* Restore the function in the stack. */
7013 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7014
7015 /* Create and and push object stream in the stack. */
7016 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
7017 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7018 ctx->rule->arg.hlua_rule->fcn.name);
7019 RESET_SAFE_LJMP(hlua->T);
7020 return 0;
7021 }
7022 hlua->nargs = 1;
7023
7024 /* push keywords in the stack. */
7025 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7026 if (!lua_checkstack(hlua->T, 1)) {
7027 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7028 ctx->rule->arg.hlua_rule->fcn.name);
7029 RESET_SAFE_LJMP(hlua->T);
7030 return 0;
7031 }
7032 lua_pushstring(hlua->T, *arg);
7033 hlua->nargs++;
7034 }
7035
7036 RESET_SAFE_LJMP(hlua->T);
7037
7038 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007039 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01007040 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007041
7042 return 1;
7043}
7044
Willy Tarreau83a5ff42019-08-21 14:14:50 +02007045void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007046{
7047 struct stream_interface *si = ctx->owner;
7048 struct stream *strm = si_strm(si);
7049 struct channel *res = si_ic(si);
7050 struct act_rule *rule = ctx->rule;
7051 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007052 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007053
7054 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02007055 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
7056 /* eat the whole request */
7057 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007058 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02007059 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007060
7061 /* If the stream is disconnect or closed, ldo nothing. */
7062 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7063 return;
7064
7065 /* Execute the function. */
7066 switch (hlua_ctx_resume(hlua, 1)) {
7067 /* finished. */
7068 case HLUA_E_OK:
7069 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7070
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007071 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02007072 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007073 res->flags |= CF_READ_NULL;
7074 si_shutr(si);
7075 return;
7076
7077 /* yield. */
7078 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007079 if (hlua->wake_time != TICK_ETERNITY)
7080 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007081 return;
7082
7083 /* finished with error. */
7084 case HLUA_E_ERRMSG:
7085 /* Display log. */
7086 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
7087 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7088 lua_pop(hlua->T, 1);
7089 goto error;
7090
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007091 case HLUA_E_ETMOUT:
7092 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
7093 rule->arg.hlua_rule->fcn.name);
7094 goto error;
7095
7096 case HLUA_E_NOMEM:
7097 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
7098 rule->arg.hlua_rule->fcn.name);
7099 goto error;
7100
7101 case HLUA_E_YIELD: /* unexpected */
7102 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
7103 rule->arg.hlua_rule->fcn.name);
7104 goto error;
7105
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007106 case HLUA_E_ERR:
7107 /* Display log. */
7108 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
7109 rule->arg.hlua_rule->fcn.name);
7110 goto error;
7111
7112 default:
7113 goto error;
7114 }
7115
7116error:
7117
7118 /* For all other cases, just close the stream. */
7119 si_shutw(si);
7120 si_shutr(si);
7121 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7122}
7123
7124static void hlua_applet_tcp_release(struct appctx *ctx)
7125{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007126 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007127 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007128 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007129 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007130}
7131
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007132/* The function returns 1 if the initialisation is complete, 0 if
7133 * an errors occurs and -1 if more data are required for initializing
7134 * the applet.
7135 */
7136static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
7137{
7138 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007139 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007140 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007141 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007142 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007143 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007144
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007145 txn = strm->txn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007146
Willy Tarreau0078bfc2015-10-07 20:20:28 +02007147 /* We want two things in HTTP mode :
7148 * - enforce server-close mode if we were in keep-alive, so that the
7149 * applet is released after each response ;
7150 * - enable request body transfer to the applet in order to resync
7151 * with the response body.
7152 */
7153 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
7154 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02007155
Willy Tarreaubafbe012017-11-24 17:34:44 +01007156 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007157 if (!hlua) {
7158 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7159 ctx->rule->arg.hlua_rule->fcn.name);
7160 return 0;
7161 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007162 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007163 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007164 ctx->ctx.hlua_apphttp.left_bytes = -1;
7165 ctx->ctx.hlua_apphttp.flags = 0;
7166
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01007167 if (txn->req.flags & HTTP_MSGF_VER_11)
7168 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
7169
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007170 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007171 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007172 if (!task) {
7173 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7174 ctx->rule->arg.hlua_rule->fcn.name);
7175 return 0;
7176 }
7177 task->nice = 0;
7178 task->context = ctx;
7179 task->process = hlua_applet_wakeup;
7180 ctx->ctx.hlua_apphttp.task = task;
7181
7182 /* In the execution wrappers linked with a stream, the
7183 * Lua context can be not initialized. This behavior
7184 * permits to save performances because a systematic
7185 * Lua initialization cause 5% performances loss.
7186 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007187 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007188 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
7189 ctx->rule->arg.hlua_rule->fcn.name);
7190 return 0;
7191 }
7192
7193 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007194 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007195
7196 /* The following Lua calls can fail. */
7197 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007198 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7199 error = lua_tostring(hlua->T, -1);
7200 else
7201 error = "critical error";
7202 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7203 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007204 return 0;
7205 }
7206
7207 /* Check stack available size. */
7208 if (!lua_checkstack(hlua->T, 1)) {
7209 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7210 ctx->rule->arg.hlua_rule->fcn.name);
7211 RESET_SAFE_LJMP(hlua->T);
7212 return 0;
7213 }
7214
7215 /* Restore the function in the stack. */
7216 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7217
7218 /* Create and and push object stream in the stack. */
7219 if (!hlua_applet_http_new(hlua->T, ctx)) {
7220 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7221 ctx->rule->arg.hlua_rule->fcn.name);
7222 RESET_SAFE_LJMP(hlua->T);
7223 return 0;
7224 }
7225 hlua->nargs = 1;
7226
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007227 /* push keywords in the stack. */
7228 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7229 if (!lua_checkstack(hlua->T, 1)) {
7230 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7231 ctx->rule->arg.hlua_rule->fcn.name);
7232 RESET_SAFE_LJMP(hlua->T);
7233 return 0;
7234 }
7235 lua_pushstring(hlua->T, *arg);
7236 hlua->nargs++;
7237 }
7238
7239 RESET_SAFE_LJMP(hlua->T);
7240
7241 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007242 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007243
7244 return 1;
7245}
7246
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007247static void hlua_applet_htx_fct(struct appctx *ctx)
7248{
7249 struct stream_interface *si = ctx->owner;
7250 struct stream *strm = si_strm(si);
7251 struct channel *req = si_oc(si);
7252 struct channel *res = si_ic(si);
7253 struct act_rule *rule = ctx->rule;
7254 struct proxy *px = strm->be;
7255 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
7256 struct htx *req_htx, *res_htx;
7257
7258 res_htx = htx_from_buf(&res->buf);
7259
7260 /* If the stream is disconnect or closed, ldo nothing. */
7261 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7262 goto out;
7263
7264 /* Check if the input buffer is avalaible. */
7265 if (!b_size(&res->buf)) {
7266 si_rx_room_blk(si);
7267 goto out;
7268 }
7269 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007270 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007271 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7272
7273 /* Set the currently running flag. */
7274 if (!HLUA_IS_RUNNING(hlua) &&
7275 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7276 struct htx_blk *blk;
7277 size_t count = co_data(req);
7278
7279 if (!count) {
7280 si_cant_get(si);
7281 goto out;
7282 }
7283
7284 /* We need to flush the request header. This left the body for
7285 * the Lua.
7286 */
7287 req_htx = htx_from_buf(&req->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02007288 blk = htx_get_first_blk(req_htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007289 while (count && blk) {
7290 enum htx_blk_type type = htx_get_blk_type(blk);
7291 uint32_t sz = htx_get_blksz(blk);
7292
7293 if (sz > count) {
7294 si_cant_get(si);
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007295 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007296 goto out;
7297 }
7298
7299 count -= sz;
7300 co_set_data(req, co_data(req) - sz);
7301 blk = htx_remove_blk(req_htx, blk);
7302
7303 if (type == HTX_BLK_EOH)
7304 break;
7305 }
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007306 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007307 }
7308
7309 /* Executes The applet if it is not done. */
7310 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7311
7312 /* Execute the function. */
7313 switch (hlua_ctx_resume(hlua, 1)) {
7314 /* finished. */
7315 case HLUA_E_OK:
7316 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7317 break;
7318
7319 /* yield. */
7320 case HLUA_E_AGAIN:
7321 if (hlua->wake_time != TICK_ETERNITY)
7322 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007323 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007324
7325 /* finished with error. */
7326 case HLUA_E_ERRMSG:
7327 /* Display log. */
7328 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7329 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7330 lua_pop(hlua->T, 1);
7331 goto error;
7332
7333 case HLUA_E_ETMOUT:
7334 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7335 rule->arg.hlua_rule->fcn.name);
7336 goto error;
7337
7338 case HLUA_E_NOMEM:
7339 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7340 rule->arg.hlua_rule->fcn.name);
7341 goto error;
7342
7343 case HLUA_E_YIELD: /* unexpected */
7344 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7345 rule->arg.hlua_rule->fcn.name);
7346 goto error;
7347
7348 case HLUA_E_ERR:
7349 /* Display log. */
7350 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7351 rule->arg.hlua_rule->fcn.name);
7352 goto error;
7353
7354 default:
7355 goto error;
7356 }
7357 }
7358
7359 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007360 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7361 goto done;
7362
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007363 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7364 goto error;
7365
Christopher Faulet54b5e212019-06-04 10:08:28 +02007366 /* Don't add TLR because mux-h1 will take care of it */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007367 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
7368 si_rx_room_blk(si);
7369 goto out;
7370 }
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007371 channel_add_input(res, 1);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007372 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7373 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007374 }
7375
7376 done:
7377 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007378 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007379 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007380 si_shutr(si);
7381 }
7382
7383 /* eat the whole request */
7384 if (co_data(req)) {
7385 req_htx = htx_from_buf(&req->buf);
7386 co_htx_skip(req, req_htx, co_data(req));
7387 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007388 }
7389 }
7390
7391 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007392 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007393 return;
7394
7395 error:
7396
7397 /* If we are in HTTP mode, and we are not send any
7398 * data, return a 500 server error in best effort:
7399 * if there is no room available in the buffer,
7400 * just close the connection.
7401 */
7402 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
7403 struct buffer *err = &htx_err_chunks[HTTP_ERR_500];
7404
7405 channel_erase(res);
7406 res->buf.data = b_data(err);
7407 memcpy(res->buf.area, b_head(err), b_data(err));
7408 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007409 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007410 }
7411 if (!(strm->flags & SF_ERR_MASK))
7412 strm->flags |= SF_ERR_RESOURCE;
7413 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7414 goto done;
7415}
7416
Willy Tarreau83a5ff42019-08-21 14:14:50 +02007417void hlua_applet_http_fct(struct appctx *ctx)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007418{
7419 struct stream_interface *si = ctx->owner;
7420 struct stream *strm = si_strm(si);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007421 struct channel *req = si_oc(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007422 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007423 struct act_rule *rule = ctx->rule;
7424 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007425 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Willy Tarreau206ba832018-06-14 15:27:31 +02007426 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02007427 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02007428 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02007429 size_t len2;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007430 int ret;
7431
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007432 if (IS_HTX_STRM(strm))
7433 return hlua_applet_htx_fct(ctx);
7434
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007435 /* If the stream is disconnect or closed, ldo nothing. */
7436 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007437 goto out;
7438
7439 /* Check if the input buffer is avalaible. */
7440 if (!b_size(&res->buf)) {
7441 si_rx_room_blk(si);
7442 goto out;
7443 }
7444 /* check that the output is not closed */
7445 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
7446 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007447
7448 /* Set the currently running flag. */
7449 if (!HLUA_IS_RUNNING(hlua) &&
7450 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007451 /* Store the max amount of bytes that we can read. */
7452 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
7453
7454 /* We need to flush the request header. This left the body
7455 * for the Lua.
7456 */
7457
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007458 /* Read the maximum amount of data available. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007459 ret = co_getblk_nc(req, &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007460 if (ret == -1)
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007461 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007462
7463 /* No data available, ask for more data. */
7464 if (ret == 1)
7465 len2 = 0;
7466 if (ret == 0)
7467 len1 = 0;
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02007468 if (len1 + len2 < strm->txn->req.eoh + strm->txn->req.eol) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007469 si_cant_get(si);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007470 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007471 }
7472
7473 /* skip the requests bytes. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007474 co_skip(req, strm->txn->req.eoh + strm->txn->req.eol);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007475 }
7476
7477 /* Executes The applet if it is not done. */
7478 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7479
7480 /* Execute the function. */
7481 switch (hlua_ctx_resume(hlua, 1)) {
7482 /* finished. */
7483 case HLUA_E_OK:
7484 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7485 break;
7486
7487 /* yield. */
7488 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007489 if (hlua->wake_time != TICK_ETERNITY)
7490 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007491 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007492
7493 /* finished with error. */
7494 case HLUA_E_ERRMSG:
7495 /* Display log. */
7496 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7497 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7498 lua_pop(hlua->T, 1);
7499 goto error;
7500
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007501 case HLUA_E_ETMOUT:
7502 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7503 rule->arg.hlua_rule->fcn.name);
7504 goto error;
7505
7506 case HLUA_E_NOMEM:
7507 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7508 rule->arg.hlua_rule->fcn.name);
7509 goto error;
7510
7511 case HLUA_E_YIELD: /* unexpected */
7512 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7513 rule->arg.hlua_rule->fcn.name);
7514 goto error;
7515
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007516 case HLUA_E_ERR:
7517 /* Display log. */
7518 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7519 rule->arg.hlua_rule->fcn.name);
7520 goto error;
7521
7522 default:
7523 goto error;
7524 }
7525 }
7526
7527 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007528 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7529 goto done;
7530
Christopher Fauletcc26b132018-12-18 21:20:57 +01007531 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7532 goto error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007533
7534 /* We must send the final chunk. */
7535 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
7536 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
7537
7538 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02007539 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007540
7541 /* critical error. */
7542 if (ret == -2 || ret == -3) {
7543 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
7544 rule->arg.hlua_rule->fcn.name);
7545 goto error;
7546 }
7547
7548 /* no enough space error. */
7549 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01007550 si_rx_room_blk(si);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007551 goto out;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007552 }
7553
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007554 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7555 ctx->ctx.hlua_apphttp.flags |= (APPLET_LAST_CHK|APPLET_RSP_SENT);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007556 }
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007557 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007558
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007559 done:
7560 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
7561 if (!(res->flags & CF_SHUTR)) {
7562 res->flags |= CF_READ_NULL;
7563 si_shutr(si);
7564 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007565
7566 /* eat the whole request */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007567 if (co_data(req))
7568 co_skip(req, co_data(req));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007569 }
7570
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007571 out:
7572 return;
7573
7574 error:
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007575
7576 /* If we are in HTTP mode, and we are not send any
7577 * data, return a 500 server error in best effort:
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007578 * if there is no room available in the buffer,
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007579 * just close the connection.
7580 */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007581 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
7582 channel_erase(res);
7583 ci_putblk(res, error_500, strlen(error_500));
7584 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007585 if (!(strm->flags & SF_ERR_MASK))
7586 strm->flags |= SF_ERR_RESOURCE;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007587 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007588 goto done;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007589}
7590
7591static void hlua_applet_http_release(struct appctx *ctx)
7592{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007593 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007594 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007595 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007596 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007597}
7598
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007599/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
7600 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007601 *
7602 * This function can fail with an abort() due to an Lua critical error.
7603 * We are in the configuration parsing process of HAProxy, this abort() is
7604 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007605 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007606static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
7607 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007608{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007609 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007610 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007611
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007612 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007613 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007614 if (!rule->arg.hlua_rule) {
7615 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007616 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007617 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007618
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007619 /* Memory for arguments. */
7620 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
7621 if (!rule->arg.hlua_rule->args) {
7622 memprintf(err, "out of memory error");
7623 return ACT_RET_PRS_ERR;
7624 }
7625
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007626 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007627 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007628
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007629 /* Expect some arguments */
7630 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007631 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007632 memprintf(err, "expect %d arguments", fcn->nargs);
7633 return ACT_RET_PRS_ERR;
7634 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007635 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007636 if (!rule->arg.hlua_rule->args[i]) {
7637 memprintf(err, "out of memory error");
7638 return ACT_RET_PRS_ERR;
7639 }
7640 (*cur_arg)++;
7641 }
7642 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007643
Thierry FOURNIER42148732015-09-02 17:17:33 +02007644 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007645 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007646 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007647}
7648
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007649static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
7650 struct act_rule *rule, char **err)
7651{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007652 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007653
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007654 /* HTTP applets are forbidden in tcp-request rules.
7655 * HTTP applet request requires everything initilized by
7656 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
7657 * The applet will be immediately initilized, but its before
7658 * the call of this analyzer.
7659 */
7660 if (rule->from != ACT_F_HTTP_REQ) {
7661 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
7662 return ACT_RET_PRS_ERR;
7663 }
7664
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007665 /* Memory for the rule. */
7666 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7667 if (!rule->arg.hlua_rule) {
7668 memprintf(err, "out of memory error");
7669 return ACT_RET_PRS_ERR;
7670 }
7671
7672 /* Reference the Lua function and store the reference. */
7673 rule->arg.hlua_rule->fcn = *fcn;
7674
7675 /* TODO: later accept arguments. */
7676 rule->arg.hlua_rule->args = NULL;
7677
7678 /* Add applet pointer in the rule. */
7679 rule->applet.obj_type = OBJ_TYPE_APPLET;
7680 rule->applet.name = fcn->name;
7681 rule->applet.init = hlua_applet_http_init;
7682 rule->applet.fct = hlua_applet_http_fct;
7683 rule->applet.release = hlua_applet_http_release;
7684 rule->applet.timeout = hlua_timeout_applet;
7685
7686 return ACT_RET_PRS_OK;
7687}
7688
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007689/* This function is an LUA binding used for registering
7690 * "sample-conv" functions. It expects a converter name used
7691 * in the haproxy configuration file, and an LUA function.
7692 */
7693__LJMP static int hlua_register_action(lua_State *L)
7694{
7695 struct action_kw_list *akl;
7696 const char *name;
7697 int ref;
7698 int len;
7699 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007700 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007701
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007702 /* Initialise the number of expected arguments at 0. */
7703 nargs = 0;
7704
7705 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7706 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007707
7708 /* First argument : converter name. */
7709 name = MAY_LJMP(luaL_checkstring(L, 1));
7710
7711 /* Second argument : environment. */
7712 if (lua_type(L, 2) != LUA_TTABLE)
7713 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7714
7715 /* Third argument : lua function. */
7716 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7717
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007718 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007719 if (lua_gettop(L) >= 4)
7720 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
7721
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007722 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007723 lua_pushnil(L);
7724 while (lua_next(L, 2) != 0) {
7725 if (lua_type(L, -1) != LUA_TSTRING)
7726 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7727
7728 /* Check required environment. Only accepted "http" or "tcp". */
7729 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007730 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007731 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007732 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007733 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007734 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007735 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007736
7737 /* Fill fcn. */
7738 fcn->name = strdup(name);
7739 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007740 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007741 fcn->function_ref = ref;
7742
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007743 /* Set the expected number od arguments. */
7744 fcn->nargs = nargs;
7745
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007746 /* List head */
7747 akl->list.n = akl->list.p = NULL;
7748
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007749 /* action keyword. */
7750 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007751 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007752 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007753 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007754
7755 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7756
7757 akl->kw[0].match_pfx = 0;
7758 akl->kw[0].private = fcn;
7759 akl->kw[0].parse = action_register_lua;
7760
7761 /* select the action registering point. */
7762 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
7763 tcp_req_cont_keywords_register(akl);
7764 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
7765 tcp_res_cont_keywords_register(akl);
7766 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
7767 http_req_keywords_register(akl);
7768 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
7769 http_res_keywords_register(akl);
7770 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007771 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007772 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
7773 "are expected.", lua_tostring(L, -1)));
7774
7775 /* pop the environment string. */
7776 lua_pop(L, 1);
7777 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007778 return ACT_RET_PRS_OK;
7779}
7780
7781static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7782 struct act_rule *rule, char **err)
7783{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007784 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007785
Christopher Fauleteb709802019-04-11 22:04:08 +02007786 if (px->mode == PR_MODE_HTTP && (px->options2 & PR_O2_USE_HTX)) {
Christopher Fauletafd8f102018-11-08 11:34:21 +01007787 memprintf(err, "Lua services cannot be used when the HTX internal representation is enabled");
7788 return ACT_RET_PRS_ERR;
7789 }
7790
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007791 /* Memory for the rule. */
7792 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7793 if (!rule->arg.hlua_rule) {
7794 memprintf(err, "out of memory error");
7795 return ACT_RET_PRS_ERR;
7796 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007797
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007798 /* Reference the Lua function and store the reference. */
7799 rule->arg.hlua_rule->fcn = *fcn;
7800
7801 /* TODO: later accept arguments. */
7802 rule->arg.hlua_rule->args = NULL;
7803
7804 /* Add applet pointer in the rule. */
7805 rule->applet.obj_type = OBJ_TYPE_APPLET;
7806 rule->applet.name = fcn->name;
7807 rule->applet.init = hlua_applet_tcp_init;
7808 rule->applet.fct = hlua_applet_tcp_fct;
7809 rule->applet.release = hlua_applet_tcp_release;
7810 rule->applet.timeout = hlua_timeout_applet;
7811
7812 return 0;
7813}
7814
7815/* This function is an LUA binding used for registering
7816 * "sample-conv" functions. It expects a converter name used
7817 * in the haproxy configuration file, and an LUA function.
7818 */
7819__LJMP static int hlua_register_service(lua_State *L)
7820{
7821 struct action_kw_list *akl;
7822 const char *name;
7823 const char *env;
7824 int ref;
7825 int len;
7826 struct hlua_function *fcn;
7827
7828 MAY_LJMP(check_args(L, 3, "register_service"));
7829
7830 /* First argument : converter name. */
7831 name = MAY_LJMP(luaL_checkstring(L, 1));
7832
7833 /* Second argument : environment. */
7834 env = MAY_LJMP(luaL_checkstring(L, 2));
7835
7836 /* Third argument : lua function. */
7837 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7838
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007839 /* Allocate and fill the sample fetch keyword struct. */
7840 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7841 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007842 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007843 fcn = calloc(1, sizeof(*fcn));
7844 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007845 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007846
7847 /* Fill fcn. */
7848 len = strlen("<lua.>") + strlen(name) + 1;
7849 fcn->name = calloc(1, len);
7850 if (!fcn->name)
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 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7853 fcn->function_ref = ref;
7854
7855 /* List head */
7856 akl->list.n = akl->list.p = NULL;
7857
7858 /* converter keyword. */
7859 len = strlen("lua.") + strlen(name) + 1;
7860 akl->kw[0].kw = calloc(1, len);
7861 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007862 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007863
7864 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7865
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007866 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007867 if (strcmp(env, "tcp") == 0)
7868 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007869 else if (strcmp(env, "http") == 0)
7870 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007871 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007872 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007873 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007874
7875 akl->kw[0].match_pfx = 0;
7876 akl->kw[0].private = fcn;
7877
7878 /* End of array. */
7879 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7880
7881 /* Register this new converter */
7882 service_keywords_register(akl);
7883
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007884 return 0;
7885}
7886
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007887/* This function initialises Lua cli handler. It copies the
7888 * arguments in the Lua stack and create channel IO objects.
7889 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007890static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007891{
7892 struct hlua *hlua;
7893 struct hlua_function *fcn;
7894 int i;
7895 const char *error;
7896
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007897 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007898 appctx->ctx.hlua_cli.fcn = private;
7899
Willy Tarreaubafbe012017-11-24 17:34:44 +01007900 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007901 if (!hlua) {
7902 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007903 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007904 }
7905 HLUA_INIT(hlua);
7906 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007907
7908 /* Create task used by signal to wakeup applets.
7909 * We use the same wakeup fonction than the Lua applet_tcp and
7910 * applet_http. It is absolutely compatible.
7911 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007912 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007913 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007914 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007915 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007916 }
7917 appctx->ctx.hlua_cli.task->nice = 0;
7918 appctx->ctx.hlua_cli.task->context = appctx;
7919 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7920
7921 /* Initialises the Lua context */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007922 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007923 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007924 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007925 }
7926
7927 /* The following Lua calls can fail. */
7928 if (!SET_SAFE_LJMP(hlua->T)) {
7929 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7930 error = lua_tostring(hlua->T, -1);
7931 else
7932 error = "critical error";
7933 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7934 goto error;
7935 }
7936
7937 /* Check stack available size. */
7938 if (!lua_checkstack(hlua->T, 2)) {
7939 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7940 goto error;
7941 }
7942
7943 /* Restore the function in the stack. */
7944 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7945
7946 /* Once the arguments parsed, the CLI is like an AppletTCP,
7947 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007948 */
7949 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7950 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7951 goto error;
7952 }
7953 hlua->nargs = 1;
7954
7955 /* push keywords in the stack. */
7956 for (i = 0; *args[i]; i++) {
7957 /* Check stack available size. */
7958 if (!lua_checkstack(hlua->T, 1)) {
7959 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7960 goto error;
7961 }
7962 lua_pushstring(hlua->T, args[i]);
7963 hlua->nargs++;
7964 }
7965
7966 /* We must initialize the execution timeouts. */
7967 hlua->max_time = hlua_timeout_session;
7968
7969 /* At this point the execution is safe. */
7970 RESET_SAFE_LJMP(hlua->T);
7971
7972 /* It's ok */
7973 return 0;
7974
7975 /* It's not ok. */
7976error:
7977 RESET_SAFE_LJMP(hlua->T);
7978 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007979 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007980 return 1;
7981}
7982
7983static int hlua_cli_io_handler_fct(struct appctx *appctx)
7984{
7985 struct hlua *hlua;
7986 struct stream_interface *si;
7987 struct hlua_function *fcn;
7988
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007989 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007990 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007991 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007992
7993 /* If the stream is disconnect or closed, ldo nothing. */
7994 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7995 return 1;
7996
7997 /* Execute the function. */
7998 switch (hlua_ctx_resume(hlua, 1)) {
7999
8000 /* finished. */
8001 case HLUA_E_OK:
8002 return 1;
8003
8004 /* yield. */
8005 case HLUA_E_AGAIN:
8006 /* We want write. */
8007 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01008008 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008009 /* Set the timeout. */
8010 if (hlua->wake_time != TICK_ETERNITY)
8011 task_schedule(hlua->task, hlua->wake_time);
8012 return 0;
8013
8014 /* finished with error. */
8015 case HLUA_E_ERRMSG:
8016 /* Display log. */
8017 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
8018 fcn->name, lua_tostring(hlua->T, -1));
8019 lua_pop(hlua->T, 1);
8020 return 1;
8021
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008022 case HLUA_E_ETMOUT:
8023 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
8024 fcn->name);
8025 return 1;
8026
8027 case HLUA_E_NOMEM:
8028 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
8029 fcn->name);
8030 return 1;
8031
8032 case HLUA_E_YIELD: /* unexpected */
8033 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
8034 fcn->name);
8035 return 1;
8036
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008037 case HLUA_E_ERR:
8038 /* Display log. */
8039 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
8040 fcn->name);
8041 return 1;
8042
8043 default:
8044 return 1;
8045 }
8046
8047 return 1;
8048}
8049
8050static void hlua_cli_io_release_fct(struct appctx *appctx)
8051{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008052 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008053 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008054}
8055
8056/* This function is an LUA binding used for registering
8057 * new keywords in the cli. It expects a list of keywords
8058 * which are the "path". It is limited to 5 keywords. A
8059 * description of the command, a function to be executed
8060 * for the parsing and a function for io handlers.
8061 */
8062__LJMP static int hlua_register_cli(lua_State *L)
8063{
8064 struct cli_kw_list *cli_kws;
8065 const char *message;
8066 int ref_io;
8067 int len;
8068 struct hlua_function *fcn;
8069 int index;
8070 int i;
8071
8072 MAY_LJMP(check_args(L, 3, "register_cli"));
8073
8074 /* First argument : an array of maximum 5 keywords. */
8075 if (!lua_istable(L, 1))
8076 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
8077
8078 /* Second argument : string with contextual message. */
8079 message = MAY_LJMP(luaL_checkstring(L, 2));
8080
8081 /* Third and fourth argument : lua function. */
8082 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
8083
8084 /* Allocate and fill the sample fetch keyword struct. */
8085 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
8086 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008087 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008088 fcn = calloc(1, sizeof(*fcn));
8089 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008090 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008091
8092 /* Fill path. */
8093 index = 0;
8094 lua_pushnil(L);
8095 while(lua_next(L, 1) != 0) {
8096 if (index >= 5)
8097 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
8098 if (lua_type(L, -1) != LUA_TSTRING)
8099 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
8100 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
8101 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008102 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008103 index++;
8104 lua_pop(L, 1);
8105 }
8106
8107 /* Copy help message. */
8108 cli_kws->kw[0].usage = strdup(message);
8109 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008110 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008111
8112 /* Fill fcn io handler. */
8113 len = strlen("<lua.cli>") + 1;
8114 for (i = 0; i < index; i++)
8115 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
8116 fcn->name = calloc(1, len);
8117 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008118 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008119 strncat((char *)fcn->name, "<lua.cli", len);
8120 for (i = 0; i < index; i++) {
8121 strncat((char *)fcn->name, ".", len);
8122 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
8123 }
8124 strncat((char *)fcn->name, ">", len);
8125 fcn->function_ref = ref_io;
8126
8127 /* Fill last entries. */
8128 cli_kws->kw[0].private = fcn;
8129 cli_kws->kw[0].parse = hlua_cli_parse_fct;
8130 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
8131 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
8132
8133 /* Register this new converter */
8134 cli_register_kw(cli_kws);
8135
8136 return 0;
8137}
8138
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008139static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
8140 struct proxy *defpx, const char *file, int line,
8141 char **err, unsigned int *timeout)
8142{
8143 const char *error;
8144
8145 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +02008146 if (error == PARSE_TIME_OVER) {
8147 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
8148 args[1], args[0]);
8149 return -1;
8150 }
8151 else if (error == PARSE_TIME_UNDER) {
8152 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
8153 args[1], args[0]);
8154 return -1;
8155 }
8156 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008157 memprintf(err, "%s: invalid timeout", args[0]);
8158 return -1;
8159 }
8160 return 0;
8161}
8162
8163static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
8164 struct proxy *defpx, const char *file, int line,
8165 char **err)
8166{
8167 return hlua_read_timeout(args, section_type, curpx, defpx,
8168 file, line, err, &hlua_timeout_session);
8169}
8170
8171static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
8172 struct proxy *defpx, const char *file, int line,
8173 char **err)
8174{
8175 return hlua_read_timeout(args, section_type, curpx, defpx,
8176 file, line, err, &hlua_timeout_task);
8177}
8178
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008179static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
8180 struct proxy *defpx, const char *file, int line,
8181 char **err)
8182{
8183 return hlua_read_timeout(args, section_type, curpx, defpx,
8184 file, line, err, &hlua_timeout_applet);
8185}
8186
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008187static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
8188 struct proxy *defpx, const char *file, int line,
8189 char **err)
8190{
8191 char *error;
8192
8193 hlua_nb_instruction = strtoll(args[1], &error, 10);
8194 if (*error != '\0') {
8195 memprintf(err, "%s: invalid number", args[0]);
8196 return -1;
8197 }
8198 return 0;
8199}
8200
Willy Tarreau32f61e22015-03-18 17:54:59 +01008201static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
8202 struct proxy *defpx, const char *file, int line,
8203 char **err)
8204{
8205 char *error;
8206
8207 if (*(args[1]) == 0) {
8208 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
8209 return -1;
8210 }
8211 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
8212 if (*error != '\0') {
8213 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
8214 return -1;
8215 }
8216 return 0;
8217}
8218
8219
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008220/* This function is called by the main configuration key "lua-load". It loads and
8221 * execute an lua file during the parsing of the HAProxy configuration file. It is
8222 * the main lua entry point.
8223 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008224 * This function runs with the HAProxy keywords API. It returns -1 if an error
8225 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008226 *
8227 * In some error case, LUA set an error message in top of the stack. This function
8228 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008229 *
8230 * This function can fail with an abort() due to an Lua critical error.
8231 * We are in the configuration parsing process of HAProxy, this abort() is
8232 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008233 */
8234static int hlua_load(char **args, int section_type, struct proxy *curpx,
8235 struct proxy *defpx, const char *file, int line,
8236 char **err)
8237{
8238 int error;
8239
8240 /* Just load and compile the file. */
8241 error = luaL_loadfile(gL.T, args[1]);
8242 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008243 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008244 lua_pop(gL.T, 1);
8245 return -1;
8246 }
8247
8248 /* If no syntax error where detected, execute the code. */
8249 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
8250 switch (error) {
8251 case LUA_OK:
8252 break;
8253 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008254 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008255 lua_pop(gL.T, 1);
8256 return -1;
8257 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008258 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008259 return -1;
8260 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008261 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008262 lua_pop(gL.T, 1);
8263 return -1;
8264 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008265 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008266 lua_pop(gL.T, 1);
8267 return -1;
8268 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008269 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008270 lua_pop(gL.T, 1);
8271 return -1;
8272 }
8273
8274 return 0;
8275}
8276
8277/* configuration keywords declaration */
8278static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008279 { CFG_GLOBAL, "lua-load", hlua_load },
8280 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
8281 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02008282 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008283 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01008284 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008285 { 0, NULL, NULL },
8286}};
8287
Willy Tarreau0108d902018-11-25 19:14:37 +01008288INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
8289
Christopher Fauletafd8f102018-11-08 11:34:21 +01008290
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008291/* This function can fail with an abort() due to an Lua critical error.
8292 * We are in the initialisation process of HAProxy, this abort() is
8293 * tolerated.
8294 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008295int hlua_post_init()
8296{
8297 struct hlua_init_function *init;
8298 const char *msg;
8299 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008300 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008301
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008302 /* Call post initialisation function in safe environement. */
8303 if (!SET_SAFE_LJMP(gL.T)) {
8304 if (lua_type(gL.T, -1) == LUA_TSTRING)
8305 error = lua_tostring(gL.T, -1);
8306 else
8307 error = "critical error";
8308 fprintf(stderr, "Lua post-init: %s.\n", error);
8309 exit(1);
8310 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02008311
8312#if USE_OPENSSL
8313 /* Initialize SSL server. */
8314 if (socket_ssl.xprt->prepare_srv) {
8315 int saved_used_backed = global.ssl_used_backend;
8316 // don't affect maxconn automatic computation
8317 socket_ssl.xprt->prepare_srv(&socket_ssl);
8318 global.ssl_used_backend = saved_used_backed;
8319 }
8320#endif
8321
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008322 hlua_fcn_post_init(gL.T);
8323 RESET_SAFE_LJMP(gL.T);
8324
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008325 list_for_each_entry(init, &hlua_init_functions, l) {
8326 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
8327 ret = hlua_ctx_resume(&gL, 0);
8328 switch (ret) {
8329 case HLUA_E_OK:
8330 lua_pop(gL.T, -1);
8331 return 1;
8332 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008333 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008334 return 0;
8335 case HLUA_E_ERRMSG:
8336 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01008337 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008338 return 0;
8339 case HLUA_E_ERR:
8340 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008341 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008342 return 0;
8343 }
8344 }
8345 return 1;
8346}
8347
Willy Tarreau32f61e22015-03-18 17:54:59 +01008348/* The memory allocator used by the Lua stack. <ud> is a pointer to the
8349 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
8350 * is the previously allocated size or the kind of object in case of a new
8351 * allocation. <nsize> is the requested new size.
8352 */
8353static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
8354{
8355 struct hlua_mem_allocator *zone = ud;
8356
8357 if (nsize == 0) {
8358 /* it's a free */
8359 if (ptr)
8360 zone->allocated -= osize;
8361 free(ptr);
8362 return NULL;
8363 }
8364
8365 if (!ptr) {
8366 /* it's a new allocation */
8367 if (zone->limit && zone->allocated + nsize > zone->limit)
8368 return NULL;
8369
8370 ptr = malloc(nsize);
8371 if (ptr)
8372 zone->allocated += nsize;
8373 return ptr;
8374 }
8375
8376 /* it's a realloc */
8377 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
8378 return NULL;
8379
8380 ptr = realloc(ptr, nsize);
8381 if (ptr)
8382 zone->allocated += nsize - osize;
8383 return ptr;
8384}
8385
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008386/* Ithis function can fail with an abort() due to an Lua critical error.
8387 * We are in the initialisation process of HAProxy, this abort() is
8388 * tolerated.
8389 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008390void hlua_init(void)
8391{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008392 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008393 int idx;
8394 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008395 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008396 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008397 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008398#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008399 struct srv_kw *kw;
8400 int tmp_error;
8401 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008402 char *args[] = { /* SSL client configuration. */
8403 "ssl",
8404 "verify",
8405 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008406 NULL
8407 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008408#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008409
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008410 /* Init main lua stack. */
8411 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01008412 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01008413 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02008414 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008415 hlua_sethlua(&gL);
8416 gL.Tref = LUA_REFNIL;
8417 gL.task = NULL;
8418
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008419 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008420 * the Lua function can fail with an abort. We are in the initialisation
8421 * process of HAProxy, this abort() is tolerated.
8422 */
8423
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008424 /* Initialise lua. */
8425 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008426
Thierry Fournier75933d42016-01-21 09:30:18 +01008427 /* Set safe environment for the initialisation. */
8428 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008429 if (lua_type(gL.T, -1) == LUA_TSTRING)
8430 error_msg = lua_tostring(gL.T, -1);
8431 else
8432 error_msg = "critical error";
8433 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01008434 exit(1);
8435 }
8436
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008437 /*
8438 *
8439 * Create "core" object.
8440 *
8441 */
8442
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01008443 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008444 lua_newtable(gL.T);
8445
8446 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008447 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008448 hlua_class_const_int(gL.T, log_levels[i], i);
8449
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008450 /* Register special functions. */
8451 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008452 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008453 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008454 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008455 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008456 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008457 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008458 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01008459 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008460 hlua_class_function(gL.T, "sleep", hlua_sleep);
8461 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01008462 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
8463 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
8464 hlua_class_function(gL.T, "set_map", hlua_set_map);
8465 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008466 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008467 hlua_class_function(gL.T, "log", hlua_log);
8468 hlua_class_function(gL.T, "Debug", hlua_log_debug);
8469 hlua_class_function(gL.T, "Info", hlua_log_info);
8470 hlua_class_function(gL.T, "Warning", hlua_log_warning);
8471 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02008472 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01008473 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008474
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008475 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008476
8477 /*
8478 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008479 * Register class Map
8480 *
8481 */
8482
8483 /* This table entry is the object "Map" base. */
8484 lua_newtable(gL.T);
8485
8486 /* register pattern types. */
8487 for (i=0; i<PAT_MATCH_NUM; i++)
8488 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008489 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008490 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
8491 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008492 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008493
8494 /* register constructor. */
8495 hlua_class_function(gL.T, "new", hlua_map_new);
8496
8497 /* Create and fill the metatable. */
8498 lua_newtable(gL.T);
8499
8500 /* Create and fille the __index entry. */
8501 lua_pushstring(gL.T, "__index");
8502 lua_newtable(gL.T);
8503
8504 /* Register . */
8505 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
8506 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
8507
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008508 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008509
Thierry Fournier45e78d72016-02-19 18:34:46 +01008510 /* Register previous table in the registry with reference and named entry.
8511 * The function hlua_register_metatable() pops the stack, so we
8512 * previously create a copy of the table.
8513 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008514 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008515 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008516
8517 /* Assign the metatable to the mai Map object. */
8518 lua_setmetatable(gL.T, -2);
8519
8520 /* Set a name to the table. */
8521 lua_setglobal(gL.T, "Map");
8522
8523 /*
8524 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008525 * Register class Channel
8526 *
8527 */
8528
8529 /* Create and fill the metatable. */
8530 lua_newtable(gL.T);
8531
8532 /* Create and fille the __index entry. */
8533 lua_pushstring(gL.T, "__index");
8534 lua_newtable(gL.T);
8535
8536 /* Register . */
8537 hlua_class_function(gL.T, "get", hlua_channel_get);
8538 hlua_class_function(gL.T, "dup", hlua_channel_dup);
8539 hlua_class_function(gL.T, "getline", hlua_channel_getline);
8540 hlua_class_function(gL.T, "set", hlua_channel_set);
8541 hlua_class_function(gL.T, "append", hlua_channel_append);
8542 hlua_class_function(gL.T, "send", hlua_channel_send);
8543 hlua_class_function(gL.T, "forward", hlua_channel_forward);
8544 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
8545 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01008546 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008547
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008548 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008549
8550 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008551 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008552
8553 /*
8554 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008555 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008556 *
8557 */
8558
8559 /* Create and fill the metatable. */
8560 lua_newtable(gL.T);
8561
8562 /* Create and fille the __index entry. */
8563 lua_pushstring(gL.T, "__index");
8564 lua_newtable(gL.T);
8565
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008566 /* Browse existing fetches and create the associated
8567 * object method.
8568 */
8569 sf = NULL;
8570 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
8571
8572 /* Dont register the keywork if the arguments check function are
8573 * not safe during the runtime.
8574 */
8575 if ((sf->val_args != NULL) &&
8576 (sf->val_args != val_payload_lv) &&
8577 (sf->val_args != val_hdr))
8578 continue;
8579
8580 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8581 * by an underscore.
8582 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008583 strncpy(trash.area, sf->kw, trash.size);
8584 trash.area[trash.size - 1] = '\0';
8585 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008586 if (*p == '.' || *p == '-' || *p == '+')
8587 *p = '_';
8588
8589 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008590 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01008591 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008592 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008593 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008594 }
8595
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008596 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008597
8598 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008599 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008600
8601 /*
8602 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008603 * Register class Converters
8604 *
8605 */
8606
8607 /* Create and fill the metatable. */
8608 lua_newtable(gL.T);
8609
8610 /* Create and fill the __index entry. */
8611 lua_pushstring(gL.T, "__index");
8612 lua_newtable(gL.T);
8613
8614 /* Browse existing converters and create the associated
8615 * object method.
8616 */
8617 sc = NULL;
8618 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
8619 /* Dont register the keywork if the arguments check function are
8620 * not safe during the runtime.
8621 */
8622 if (sc->val_args != NULL)
8623 continue;
8624
8625 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8626 * by an underscore.
8627 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008628 strncpy(trash.area, sc->kw, trash.size);
8629 trash.area[trash.size - 1] = '\0';
8630 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008631 if (*p == '.' || *p == '-' || *p == '+')
8632 *p = '_';
8633
8634 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008635 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008636 lua_pushlightuserdata(gL.T, sc);
8637 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008638 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008639 }
8640
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008641 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008642
8643 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008644 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008645
8646 /*
8647 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008648 * Register class HTTP
8649 *
8650 */
8651
8652 /* Create and fill the metatable. */
8653 lua_newtable(gL.T);
8654
8655 /* Create and fille the __index entry. */
8656 lua_pushstring(gL.T, "__index");
8657 lua_newtable(gL.T);
8658
8659 /* Register Lua functions. */
8660 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
8661 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
8662 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
8663 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
8664 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
8665 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
8666 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
8667 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
8668 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
8669 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
8670
8671 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
8672 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
8673 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
8674 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
8675 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
8676 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02008677 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008678
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008679 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008680
8681 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008682 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008683
8684 /*
8685 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008686 * Register class AppletTCP
8687 *
8688 */
8689
8690 /* Create and fill the metatable. */
8691 lua_newtable(gL.T);
8692
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008693 /* Create and fille the __index entry. */
8694 lua_pushstring(gL.T, "__index");
8695 lua_newtable(gL.T);
8696
8697 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01008698 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
8699 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
8700 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
8701 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
8702 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008703 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
8704 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
8705 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008706
8707 lua_settable(gL.T, -3);
8708
8709 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008710 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008711
8712 /*
8713 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008714 * Register class AppletHTTP
8715 *
8716 */
8717
8718 /* Create and fill the metatable. */
8719 lua_newtable(gL.T);
8720
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008721 /* Create and fille the __index entry. */
8722 lua_pushstring(gL.T, "__index");
8723 lua_newtable(gL.T);
8724
8725 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01008726 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
8727 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008728 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
8729 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
8730 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008731 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
8732 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
8733 hlua_class_function(gL.T, "send", hlua_applet_http_send);
8734 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
8735 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
8736 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
8737
8738 lua_settable(gL.T, -3);
8739
8740 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008741 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008742
8743 /*
8744 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008745 * Register class TXN
8746 *
8747 */
8748
8749 /* Create and fill the metatable. */
8750 lua_newtable(gL.T);
8751
8752 /* Create and fille the __index entry. */
8753 lua_pushstring(gL.T, "__index");
8754 lua_newtable(gL.T);
8755
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008756 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04008757 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
8758 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
8759 hlua_class_function(gL.T, "set_var", hlua_set_var);
8760 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
8761 hlua_class_function(gL.T, "get_var", hlua_get_var);
8762 hlua_class_function(gL.T, "done", hlua_txn_done);
8763 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
8764 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
8765 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
8766 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
8767 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
8768 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
8769 hlua_class_function(gL.T, "log", hlua_txn_log);
8770 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
8771 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
8772 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
8773 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008774
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008775 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008776
8777 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008778 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008779
8780 /*
8781 *
8782 * Register class Socket
8783 *
8784 */
8785
8786 /* Create and fill the metatable. */
8787 lua_newtable(gL.T);
8788
8789 /* Create and fille the __index entry. */
8790 lua_pushstring(gL.T, "__index");
8791 lua_newtable(gL.T);
8792
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008793#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008794 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008795#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008796 hlua_class_function(gL.T, "connect", hlua_socket_connect);
8797 hlua_class_function(gL.T, "send", hlua_socket_send);
8798 hlua_class_function(gL.T, "receive", hlua_socket_receive);
8799 hlua_class_function(gL.T, "close", hlua_socket_close);
8800 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
8801 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8802 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8803 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8804
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008805 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008806
8807 /* Register the garbage collector entry. */
8808 lua_pushstring(gL.T, "__gc");
8809 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008810 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008811
8812 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008813 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008814
8815 /* Proxy and server configuration initialisation. */
8816 memset(&socket_proxy, 0, sizeof(socket_proxy));
8817 init_new_proxy(&socket_proxy);
8818 socket_proxy.parent = NULL;
8819 socket_proxy.last_change = now.tv_sec;
8820 socket_proxy.id = "LUA-SOCKET";
8821 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8822 socket_proxy.maxconn = 0;
8823 socket_proxy.accept = NULL;
8824 socket_proxy.options2 |= PR_O2_INDEPSTR;
8825 socket_proxy.srv = NULL;
8826 socket_proxy.conn_retries = 0;
8827 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8828
8829 /* Init TCP server: unchanged parameters */
8830 memset(&socket_tcp, 0, sizeof(socket_tcp));
8831 socket_tcp.next = NULL;
8832 socket_tcp.proxy = &socket_proxy;
8833 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8834 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008835 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008836 socket_tcp.priv_conns = NULL;
8837 socket_tcp.idle_conns = NULL;
8838 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008839 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008840 socket_tcp.last_change = 0;
8841 socket_tcp.id = "LUA-TCP-CONN";
8842 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8843 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8844 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
8845
8846 /* XXX: Copy default parameter from default server,
8847 * but the default server is not initialized.
8848 */
8849 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
8850 socket_tcp.minconn = socket_proxy.defsrv.minconn;
8851 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
8852 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
8853 socket_tcp.onerror = socket_proxy.defsrv.onerror;
8854 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8855 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
8856 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8857 socket_tcp.uweight = socket_proxy.defsrv.iweight;
8858 socket_tcp.iweight = socket_proxy.defsrv.iweight;
8859
8860 socket_tcp.check.status = HCHK_STATUS_INI;
8861 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
8862 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
8863 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
8864 socket_tcp.check.server = &socket_tcp;
8865
8866 socket_tcp.agent.status = HCHK_STATUS_INI;
8867 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
8868 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
8869 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
8870 socket_tcp.agent.server = &socket_tcp;
8871
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008872 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008873
8874#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008875 /* Init TCP server: unchanged parameters */
8876 memset(&socket_ssl, 0, sizeof(socket_ssl));
8877 socket_ssl.next = NULL;
8878 socket_ssl.proxy = &socket_proxy;
8879 socket_ssl.obj_type = OBJ_TYPE_SERVER;
8880 LIST_INIT(&socket_ssl.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008881 socket_ssl.pendconns = EB_ROOT;
Willy Tarreaub784b352019-02-07 14:48:24 +01008882 socket_ssl.priv_conns = NULL;
8883 socket_ssl.idle_conns = NULL;
8884 socket_ssl.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008885 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008886 socket_ssl.last_change = 0;
8887 socket_ssl.id = "LUA-SSL-CONN";
8888 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8889 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8890 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8891
8892 /* XXX: Copy default parameter from default server,
8893 * but the default server is not initialized.
8894 */
8895 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8896 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8897 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8898 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8899 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8900 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8901 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8902 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8903 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8904 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8905
8906 socket_ssl.check.status = HCHK_STATUS_INI;
8907 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8908 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8909 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8910 socket_ssl.check.server = &socket_ssl;
8911
8912 socket_ssl.agent.status = HCHK_STATUS_INI;
8913 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8914 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8915 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8916 socket_ssl.agent.server = &socket_ssl;
8917
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008918 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008919 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008920
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008921 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008922 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8923 /*
8924 *
8925 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008926 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008927 * features like client certificates and ssl_verify.
8928 *
8929 */
8930 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8931 if (tmp_error != 0) {
8932 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8933 abort(); /* This must be never arrives because the command line
8934 not editable by the user. */
8935 }
8936 idx += kw->skip;
8937 }
8938 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008939#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008940
8941 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008942}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008943
Willy Tarreau80713382018-11-26 10:19:54 +01008944static void hlua_register_build_options(void)
8945{
Willy Tarreaubb57d942016-12-21 19:04:56 +01008946 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +01008947
Willy Tarreaubb57d942016-12-21 19:04:56 +01008948 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8949 hap_register_build_opts(ptr, 1);
8950}
Willy Tarreau80713382018-11-26 10:19:54 +01008951
8952INITCALL0(STG_REGISTER, hlua_register_build_options);